From 2aca90b034ac09b84ac6290513b52f1da7152503 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 05:07:40 +0000 Subject: [PATCH 1/4] fix(reverb): connect diffusion, decay and low-pass controls - Filter the Echo delay path and feedback loop with lpf1 and lpf2 - Scale the Schroeder and SmallRoom allpass gains with diffusion - Filter two Schroeder comb paths with lpf1 and lpf2 - Drive the first Schroeder comb path with decay - Add filtered decay feedback to the Binaural delay lines - Update the reverb tail budget for Binaural and SmallRoom --- src/effects/reverb.rs | 51 +++++++++++++++++++++++-------------------- 1 file changed, 27 insertions(+), 24 deletions(-) diff --git a/src/effects/reverb.rs b/src/effects/reverb.rs index 3a7dfce..8358ee3 100644 --- a/src/effects/reverb.rs +++ b/src/effects/reverb.rs @@ -64,23 +64,22 @@ pub struct ReverbConfig { pub mix: f32, /// The diffusion control without a unit, 0..=1. /// - /// The default is 0.5. MediumHall and LargeHall scale their allpass - /// coefficients with it. Binaural uses it as the gain of its early taps. - /// In Echo, it sets the distance of the feedback tap. Schroeder and - /// SmallRoom do not use it. + /// The default is 0.5. Schroeder, SmallRoom, MediumHall and LargeHall + /// scale their allpass coefficients with it. Binaural uses it as the gain + /// of its early taps. In Echo, it sets the distance of the feedback tap. pub diffusion: f32, /// The feedback control without a unit, 0..=1. /// /// The default is 0.6. The prepared coefficient is approximately /// `decay / 1.05`. It is less than unity also at the maximum. This value - /// is not a decay time in seconds. Some paths also use fixed feedback - /// coefficients. Binaural does not use this control. + /// is not a decay time in seconds. All six networks scale feedback paths + /// with this control. Some paths also use fixed feedback coefficients. pub decay: f32, - /// The low-pass cutoff in hertz for networks with damped paths, 80..=20000. + /// The low-pass cutoff in hertz for the two low-pass filters, 80..=20000. /// - /// The default is 4000 Hz. The preparation also limits it to 0.49 × - /// sample rate. A change of the cutoff keeps the sample histories of the - /// filters. + /// The default is 4000 Hz. All six networks damp their delay paths with + /// these filters. The preparation also limits the cutoff to 0.49 × sample + /// rate. A change of the cutoff keeps the sample histories of the filters. pub brightness_hz: f32, } impl Default for ReverbConfig { @@ -243,20 +242,23 @@ impl Reverb { let mut result = match self.config.mode { ReverbMode::Echo => { d.put(mono, t[0]); + d.lpf(t[2], &mut self.lpf1); let echo: Fixed<0> = Fixed::<0>::from_bits(t[39] as i32).mul(self.diffuse); - d.comb(t[0], echo.to_bits() as usize, self.decay); + d.comb_lpf(t[0], echo.to_bits() as usize, self.decay, &mut self.lpf2); [ mul(left, dry) + mul(self.mix, d.get(t[25]) - d.get(t[32])), mul(right, dry) - mul(self.mix, d.get(t[26]) - d.get(t[31])), ] } ReverbMode::Schroeder => { + let input = mono.div::<0, 14>(TWO); for i in [0, 13, 23, 29] { - d.put(mono.div::<0, 14>(TWO), t[i]); - } - for (a, b, g) in [(0, 12, 0.9), (13, 22, 0.89), (23, 28, 0.87), (29, 34, 0.86)] { - d.comb(t[a], t[b], q14(g)); + d.put(input, t[i]); } + d.comb_lpf(t[0], t[12], self.decay, &mut self.lpf1); + d.comb_lpf(t[13], t[22], q14(0.89), &mut self.lpf2); + d.comb(t[23], t[28], q14(0.87)); + d.comb(t[29], t[34], q14(0.86)); d.fir( t[40], &[ @@ -266,8 +268,8 @@ impl Reverb { (t[34], q14(0.25)), ], ); - d.allpass(t[40], t[43], self.decay); - d.allpass(t[44], t[45], self.decay); + d.allpass(t[40], t[43], mul(self.diffuse, q14(0.7))); + d.allpass(t[44], t[45], mul(self.diffuse, self.decay)); let value = mul(mono, dry) + mul(self.mix, d.get(t[45])); [value, value] } @@ -275,11 +277,11 @@ impl Reverb { d.put(left, t[0]); d.put(right, t[40]); for (a, b, g) in [(1, 15, 0.3), (2, 7, 0.7), (8, 14, 0.5), (18, 24, 0.5)] { - d.allpass(t[a], t[b], q14(g)); + d.allpass(t[a], t[b], mul(self.diffuse, q14(g))); } d.comb_lpf(t[40], t[35], self.decay, &mut self.lpf1); for (a, b, g) in [(41, 50, 0.3), (42, 46, 0.6), (53, 57, 0.5)] { - d.allpass(t[a], t[b], q14(g)); + d.allpass(t[a], t[b], mul(self.diffuse, q14(g))); } d.comb_lpf(t[0], t[66], self.decay, &mut self.lpf2); [ @@ -303,14 +305,16 @@ impl Reverb { self.diffuse >> 1, d.get(t[0] + seed) + d.get(t[11] + seed) + d.get(t[21] + seed), ); - d.put(a, tap); + let fb_a = mul(self.decay, d.get(t[35]) + (d.get(t[24]) >> 2)); + d.put(a + fb_a, tap); d.lpf(filter, &mut self.lpf1); let out = mul(mono, dry) + mul(self.mix, d.get(t[40] + filter) + a); let b = mul( self.diffuse >> 1, d.get(t[47] + seed) + d.get(t[48] + seed) + d.get(t[54] + seed), ); - d.put(b, t[40] + tap); + let fb_b = mul(self.decay, d.get(t[66]) + (d.get(t[57]) >> 2)); + d.put(b + fb_b, t[40] + tap); d.lpf(t[40] + filter, &mut self.lpf2); [out, mul(mono, dry) + mul(self.mix, d.get(filter) + b)] } @@ -409,10 +413,9 @@ pub(crate) fn tail_frames(rate: SampleRate, config: ReverbConfig) -> usize { let decay = config.decay as f64 / 1.05; let diffuse = config.diffusion as f64; let gain = match config.mode { - ReverbMode::Binaural => 0.0, - ReverbMode::Echo => decay, + ReverbMode::Binaural | ReverbMode::Echo => decay, ReverbMode::Schroeder => 0.9f64.max(decay), - ReverbMode::SmallRoom => 0.7f64.max(decay), + ReverbMode::SmallRoom => (0.7 * diffuse).max(decay), ReverbMode::MediumHall => (0.9 * diffuse).max(decay), ReverbMode::LargeHall => (0.95 * diffuse).max(decay), }; From 55da57132de221525e3a2311c4d3ba0b5f72a769 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 05:10:48 +0000 Subject: [PATCH 2/4] fix(harmony): apply voice limits and scale voice telemetry - Enforce HarmonyConfig::voices across all seven harmony sources - Limit voiced chord tones to the active voice slots - Scale harmony entries in Telemetry::voice_gains by harmony_gain - Compact active harmony voices in Telemetry::voice_ratios - Report one plus the active harmony voices in voice_count - Document the harmony voice limit and scaled telemetry gains --- README.md | 13 ++++++------ src/harmony.rs | 50 ++++++++++++++++++++++++---------------------- src/processor.rs | 25 ++++++++++++----------- src/resynthesis.rs | 22 ++++++++++++-------- 4 files changed, 59 insertions(+), 51 deletions(-) diff --git a/README.md b/README.md index 83a8f47..a4a2a6c 100644 --- a/README.md +++ b/README.md @@ -193,13 +193,12 @@ with `resynthesis.harmony.source`: | `MidiOmni` | MIDI notes from all channels, on the first free voice | | `MidiChannels` | MIDI channel `n` for voice `n` (channels 0–3), default | -`resynthesis.harmony.voices` sets the number of interval voices, in `0..=4`. -The default is 4. `FixedInterval` and `SmartInterval` use the first `voices` -voices. The other voices release with the usual gain envelope. The chord -and MIDI sources ignore this field. +`resynthesis.harmony.voices` sets the maximum number of active harmony voices, +in `0..=4`. The default is 4. All harmony sources obey this limit. Extra +voices release with the usual gain envelope. -`resynthesis.harmony_gain` scales the four harmony voices in mono and in -stereo. It does not scale the lead voice. +`resynthesis.harmony_gain` scales the harmony voices in mono, in stereo and in +`Telemetry::voice_gains`. It does not scale the lead voice. ## Process audio @@ -304,7 +303,7 @@ These calls read the state of the processor. They do not change the audio. The telemetry includes these items: -- The pitch ratio and the gain of each voice. +- The active voice count, and the pitch ratio and scaled gain of each voice. - The peaks of the input, of the two output channels and of the reverb wet signal. - The pitch clarity, which is a confidence score from 0 to 1. diff --git a/src/harmony.rs b/src/harmony.rs index ce9fb1f..68d8f6e 100644 --- a/src/harmony.rs +++ b/src/harmony.rs @@ -239,7 +239,7 @@ pub enum Inversion { /// - A tonic major chord in root position. /// - A register of 50%. /// - A closed voicing and zero portamento. -/// - Four voices for the interval sources. +/// - A limit of four harmony voices. /// /// These settings configure all sources. Only the fields for the selected /// source change the target notes. Validation always checks all fields. @@ -315,13 +315,12 @@ pub struct HarmonyConfig { /// a glide. In the interval sources, if the input moves more than one /// semitone bin, each voice starts at its new target without a glide. pub portamento_ms: f32, - /// The number of voices that sound in the interval sources, 0..=4. + /// The maximum number of harmony voices that sound, 0..=4. /// - /// The default is 4. [`HarmonySource::FixedInterval`] and - /// [`HarmonySource::SmartInterval`] use the first `voices` voices. The - /// other voices release with the usual gain envelope. The chord and MIDI - /// sources ignore this field. In JavaScript, the field is optional and - /// a missing value gives the default. + /// The default is 4. All [`HarmonySource`] variants use a maximum of + /// `voices` active voices. Extra voices release with the usual gain + /// envelope. In JavaScript, the field is optional and a missing value + /// gives the default. #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), serde(default = "default_voices"), @@ -330,7 +329,7 @@ pub struct HarmonyConfig { pub voices: u8, } -/// The default count of interval voices: all of them. +/// The default count of harmony voices: all of them. #[cfg(all(feature = "wasm", target_arch = "wasm32"))] fn default_voices() -> u8 { HARMONY_VOICES as u8 @@ -857,15 +856,13 @@ impl HarmonyState { /// this index changes by more than one bin, the voice restarts its /// portamento. fn select_target(&mut self, period: Q6, voice: usize) -> Q12 { + if voice >= usize::from(self.config.voices) { + // A voice after the configured count releases. A zero target + // keeps its last period until the gain gets to zero. + self.target_period[voice] = Q6::ZERO; + return Q12::ZERO; + } match self.config.source { - HarmonySource::FixedInterval | HarmonySource::SmartInterval - if voice >= self.config.voices as usize => - { - // A voice after the configured count releases. A zero target - // keeps its last period until the gain gets to zero. - self.target_period[voice] = Q6::ZERO; - Q12::ZERO - } HarmonySource::FixedInterval | HarmonySource::SmartInterval => { let previous = self.scale_note[voice]; let (target, note) = self.find_scale_period(period, voice); @@ -907,9 +904,9 @@ impl HarmonyState { } } /// Prepares the chord periods and their gains from the selected source. - /// The lowest tones go into the voice slots with the highest numbers. - /// Inactive slots get zero periods, so the output does not use their - /// sentinel gains. + /// The lowest tones go into the active voice slots with the highest + /// numbers. Inactive slots get zero periods, so the output does not use + /// their sentinel gains. fn setup_chord(&mut self) { let (tones, gains, count) = chords::voice_chord( &self.config, @@ -917,17 +914,22 @@ impl HarmonyState { self.midi_period, self.midi_gain, ); + let voices = usize::from(self.config.voices); + let count = count.min(voices); if count == 0 { self.chord_period.fill(Q6::ZERO); return; } + let top = voices - 1; for i in 0..count { - self.chord_gain[3 - i] = gains[i]; - self.chord_period[3 - i] = self.cents_period(f64::from(tones[i]) * 100.0); + self.chord_gain[top - i] = gains[i]; + self.chord_period[top - i] = self.cents_period(f64::from(tones[i]) * 100.0); } - for i in count..4 { - self.chord_period[3 - i] = Q6::ZERO; - self.chord_gain[3 - i] = -Q12::ONE; + for slot in 0..HARMONY_VOICES { + if slot + count < voices || slot >= voices { + self.chord_period[slot] = Q6::ZERO; + self.chord_gain[slot] = -Q12::ONE; + } } } } diff --git a/src/processor.rs b/src/processor.rs index 83bccf6..f1c3fac 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -833,27 +833,28 @@ pub struct Telemetry { /// The number of valid entries in [`voice_ratios`](Self::voice_ratios) /// and [`voice_gains`](Self::voice_gains). /// - /// The value is 5 in Harmony mode. In Choir mode, it is - /// [`crate::ResynthesisConfig::choir_voices`], in 1..=16. + /// In Harmony mode, the value is 1 plus the active harmony voices, in + /// 1..=5. In Choir mode, it is [`crate::ResynthesisConfig::choir_voices`], + /// in 1..=16. pub voice_count: u8, /// The pitch ratio of each voice on the last frame, where 1 is the input /// pitch. /// - /// Entry zero is the lead voice. In Harmony mode, entries 1 to 4 are the - /// harmony voices. In Choir mode, the entries after the lead are the - /// secondary voices. Each ratio includes the correction, the configured - /// pitch shift and the ratio of the voice. The entries after - /// [`voice_count`](Self::voice_count) are zero. + /// Entry zero is the lead voice. In Harmony mode, the entries after the + /// lead are the active harmony voices. In Choir mode, the entries after + /// the lead are the secondary voices. Each ratio includes the correction, + /// the configured pitch shift and the ratio of the voice. The entries + /// after [`voice_count`](Self::voice_count) are zero. pub voice_ratios: [f32; 16], /// The linear gain of each voice, in the order of /// [`voice_ratios`](Self::voice_ratios). /// /// The lead and the choir voices have a gain of 1. The gain of a harmony - /// voice includes the MIDI velocity gain, in 0..=3.98095703125. MIDI - /// velocity 127 gives the maximum, approximately +12 dB. The gain is zero - /// for a voice that does not sound. It does not include the configured - /// harmony level or the pan. The harmony controller updates it every 101 - /// frames. + /// voice includes the MIDI velocity gain and + /// [`crate::ResynthesisConfig::harmony_gain`], in 0..=3.98095703125. MIDI + /// velocity 127 at unity `harmony_gain` gives the maximum, approximately + /// +12 dB. It does not include the stereo pan. The harmony controller + /// updates its envelope every 101 frames. pub voice_gains: [f32; 16], /// The current drive of Punch, divided by its base drive. /// diff --git a/src/resynthesis.rs b/src/resynthesis.rs index 7f5eda5..00a75b7 100644 --- a/src/resynthesis.rs +++ b/src/resynthesis.rs @@ -834,11 +834,11 @@ impl Resynthesis { pub(crate) fn is_tracking(&self) -> bool { !self.pitch.is_detecting() } - /// Writes the effective ratio and the linear gain of each voice from the - /// last frame, and returns the number of voices. + /// Writes the effective ratio and the linear gain of each active voice + /// from the last frame, and returns `1` plus the active secondary voices. /// - /// Slot zero is the lead. In Harmony mode, slots 1 to 4 are the harmony - /// voices, and the gain is the envelope of the harmony controller. In + /// Slot zero is the lead. In Harmony mode, the entries after the lead are + /// the active harmony voices, with each gain scaled by `harmony_gain`. In /// Choir mode, the slots after the lead are the secondary voices with a /// gain of 1. Each ratio includes the correction, the global shift and /// the ratio of the voice. The entries after the count do not change. @@ -855,12 +855,18 @@ impl Resynthesis { } count as u8 } else { + let mut count = 1; + let level = self.config.harmony_gain as f64; for voice in 0..HARMONY_VOICES { - ratios[voice + 1] = - (self.voice_ratios[voice + 1].to_bits() as f64 / 16384.0) as f32; - gains[voice + 1] = (self.harmony_gains[voice].to_bits() as f64 / 4096.0) as f32; + let gain = self.harmony_gains[voice]; + if gain > Q12::ZERO { + ratios[count] = + (self.voice_ratios[voice + 1].to_bits() as f64 / 16384.0) as f32; + gains[count] = (gain.to_bits() as f64 / 4096.0 * level) as f32; + count += 1; + } } - (HARMONY_VOICES + 1) as u8 + count as u8 } } /// Returns the wrapping count of formant model designs. From ab448d640dd37f750d0b37057a2d1003b8777640 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 05:11:02 +0000 Subject: [PATCH 3/4] fix(pitch): extend acquisition lags and enforce pitch bounds - Increase ACQUISITION_LAGS to 305 for 40 Hz pitch detection - Replace the correlation wrap constant with 2 * ACQUISITION_LAGS - 1 - Check Q6 periods against PitchConfig bounds with boundary tolerance - Gate Resynthesis::is_tracking and clarity with PitchConfig::in_bounds - If a period is out of bounds, move correction toward 1.0 - Document the active frequency bounds across Rust and Wasm --- README.md | 11 ++++--- src/lib.rs | 10 +++---- src/pitch.rs | 68 ++++++++++++++++++++++++++++++-------------- src/pitch/tracker.rs | 10 +++---- src/processor.rs | 19 +++++++------ src/resynthesis.rs | 44 ++++++++++++++++------------ src/wasm.rs | 2 +- 7 files changed, 101 insertions(+), 63 deletions(-) diff --git a/README.md b/README.md index a4a2a6c..ab1032e 100644 --- a/README.md +++ b/README.md @@ -306,12 +306,15 @@ The telemetry includes these items: - The active voice count, and the pitch ratio and scaled gain of each voice. - The peaks of the input, of the two output channels and of the reverb wet signal. -- The pitch clarity, which is a confidence score from 0 to 1. +- The `tracking` flag and the pitch clarity, inside the `resynthesis.pitch` + bounds. - The current gains of Punch and Warm, and the position in the Alien loop. The peak windows of the telemetry are independent of the peak window of the -feedback. The latency is nominal. Dry mixes, resampled voices and effects -have different timing. +feedback. If a pitch is outside `min_frequency_hz..=max_frequency_hz`, it +reports as unvoiced, sets `tracking` to `false` and moves correction toward 1. +The latency is nominal. Dry mixes, resampled voices and effects have different +timing. `formant_envelope()` writes two LPC envelopes into slices of equal length: @@ -488,7 +491,7 @@ the cases where `voiced` is `false`: - The kept pitch estimate is unvoiced. This includes the time before the first detection and after a reset or a drain completion. -- The estimated frequency is outside the inclusive reporting bounds +- The estimated frequency is outside the inclusive frequency bounds `resynthesis.pitch.minFrequencyHz` and `resynthesis.pitch.maxFrequencyHz`. `formantEnvelope(maxFrequencyHz, input, output)` fills two `Float32Array` diff --git a/src/lib.rs b/src/lib.rs index f17bc85..c34e0f7 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -50,11 +50,11 @@ //! //! [`Processor::feedback`] gives the pitch, the correction ratio, the //! accumulated stereo peak and the frame count. -//! [`Processor::take_feedback`] also clears the peak window. The pitch -//! reporting bounds change only the reports. They do not change the detection -//! or the audio signal. [`Processor::latency_frames`] gives a nominal -//! resynthesis delay. Voice delays, pitch changes and effects have their own -//! timing. +//! [`Processor::take_feedback`] also clears the peak window. The frequency +//! bounds of [`PitchConfig`] gate the pitch reports, [`Telemetry::tracking`] +//! and the selection of correction targets. [`Processor::latency_frames`] +//! gives a nominal resynthesis delay. Voice delays, pitch changes and effects +//! have their own timing. //! //! [`Processor::telemetry`] gives data for meters and displays: the ratio and //! the gain of each voice, the input and output peaks, the pitch clarity and diff --git a/src/pitch.rs b/src/pitch.rs index 6b682ca..9b82aba 100644 --- a/src/pitch.rs +++ b/src/pitch.rs @@ -2,16 +2,18 @@ //! estimates. //! //! Acquisition checks that repeated minima agree. Tracking refines the period -//! in a window of 40 lags. The reporting bounds filter only the feedback to -//! the host. +//! in a window of 40 lags. The frequency bounds gate host feedback, the +//! `tracking` flag and pitch correction. mod search; pub(crate) mod tracker; use crate::error::{check_range, ConfigProblem}; -use crate::Error; +use crate::numeric::fixed::Q6; +use crate::{Error, SampleRate}; -/// The acquisition sensitivity and the bounds for pitch reports to the host. +/// The acquisition sensitivity and the frequency bounds for pitch analysis +/// and correction. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] #[cfg_attr( @@ -26,18 +28,20 @@ pub struct PitchConfig { /// This value controls acquisition. It is not an output gain or an /// amplitude gate. pub threshold: f32, - /// The lower bound of the feedback in hertz (inclusive), 40..=2000. + /// The lower frequency bound in hertz (inclusive), 40..=2000. /// /// The default is 40. It must be strictly less than `max_frequency_hz`. - /// These bounds do not change the tracking, the correction or the - /// resampling. A feedback query applies the current bounds to the kept - /// analysis. It does not process another sample. + /// If a pitch is outside the bounds, it reports as unvoiced, sets + /// [`crate::Telemetry::tracking`] to `false` and moves the correction + /// ratio toward 1.0. Feedback and telemetry queries apply the current + /// bounds to the kept analysis. pub min_frequency_hz: f32, - /// The upper bound of the feedback in hertz (inclusive), 40..=2000. + /// The upper frequency bound in hertz (inclusive), 40..=2000. /// /// The default is 1100. It must be strictly greater than - /// `min_frequency_hz`. Results outside the bounds are reported as - /// unvoiced, with zero frequency and zero period. + /// `min_frequency_hz`. If a result is outside the bounds, it reports as + /// unvoiced with zero frequency and zero period, and it bypasses target + /// selection. pub max_frequency_hz: f32, } @@ -52,17 +56,39 @@ impl Default for PitchConfig { } impl PitchConfig { - /// Applies only the bounds for host reports to a kept estimate. + /// Returns `true` if a positive Q6 period is inside the configured + /// frequency bounds at `rate`. /// - /// If the estimate is not voiced or is out of range, the result is the - /// unvoiced value with all fields zero. The function does not change the - /// tracker state or the correction state. - pub(crate) fn report(self, estimate: PitchEstimate) -> PitchEstimate { - if estimate.voiced - && estimate.frequency_hz >= self.min_frequency_hz - && estimate.frequency_hz <= self.max_frequency_hz - { - estimate + /// A tolerance of `1/256` of the boundary period (at least `1/8` of a + /// sample) absorbs the parabolic quantization at the boundaries. + pub(crate) fn in_bounds(self, rate: SampleRate, period: Q6) -> bool { + let bits = period.to_bits(); + if bits <= 0 { + return false; + } + let scale = f64::from(rate.as_u32()) * 64.0; + let min_exact = (scale / f64::from(self.max_frequency_hz)).floor() as i32; + let max_exact = (scale / f64::from(self.min_frequency_hz)).ceil() as i32; + let min_period = min_exact - (min_exact >> 8).max(8); + let max_period = max_exact + (max_exact >> 8).max(8); + bits >= min_period && bits <= max_period + } + + /// Converts a kept Q6 period to a host estimate and applies the frequency + /// bounds. + /// + /// If the period is not positive or is out of range, the result is the + /// unvoiced value with all fields zero. + pub(crate) fn report(self, rate: SampleRate, period: Q6) -> PitchEstimate { + if self.in_bounds(rate, period) { + let period_samples = (period.to_bits() as f64 / 64.0) as f32; + let frequency_hz = + (rate.hz() / period_samples).clamp(self.min_frequency_hz, self.max_frequency_hz); + PitchEstimate { + period_samples, + frequency_hz, + voiced: true, + } } else { PitchEstimate::default() } diff --git a/src/pitch/tracker.rs b/src/pitch/tracker.rs index c46ed9b..fa070b2 100644 --- a/src/pitch/tracker.rs +++ b/src/pitch/tracker.rs @@ -10,8 +10,8 @@ //! The 40-lag window moves to keep the minimum near its center. If the //! minimum is at a boundary or the curvature is not usable, acquisition //! starts again. The last usable period stays available as a fallback for -//! resynthesis. The public frequency bounds apply only to feedback reports. -//! They do not change the size of these windows. +//! resynthesis. The public frequency bounds gate pitch reports, the `tracking` +//! flag and pitch correction. They do not change the size of these windows. use super::search::{tracking_minimum, TRACKING_LAGS}; use crate::filter::{Biquad, Design}; @@ -44,7 +44,7 @@ pub(crate) struct PitchStep { } /// The number of lags that acquisition compares. -const ACQUISITION_LAGS: usize = 137; +const ACQUISITION_LAGS: usize = 305; /// The two-stage pitch tracker. /// @@ -140,7 +140,7 @@ impl PitchTracker { } /// Updates only the acquisition sensitivity. - /// The reporting bounds apply outside the tracker. A change of the + /// The frequency bounds apply outside the tracker. A change of the /// sensitivity does not reset a tracked period. pub(crate) fn set_config(&mut self, config: PitchConfig) { self.threshold = Q14::from_f64(config.threshold as f64); @@ -321,7 +321,7 @@ impl PitchTracker { &mut self.cross[lag..end], ); index1 = if count == index1 + 1 { - 273 + 2 * ACQUISITION_LAGS - 1 } else { index1 - count }; diff --git a/src/processor.rs b/src/processor.rs index f1c3fac..4bc71c8 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -725,7 +725,7 @@ pub struct Feedback { pub resample_ratio: f32, /// The reported input pitch period in samples, with fractional samples. /// - /// It is zero if the input is unvoiced or outside the reporting bounds of + /// It is zero if the input is unvoiced or outside the frequency bounds of /// [`crate::PitchConfig`]. pub period_samples: f32, /// The reported input pitch frequency in hertz. @@ -749,11 +749,11 @@ pub struct Feedback { /// /// The value is `None` if [`voiced`](Self::voiced) is `false`, and only /// then. This occurs if the input is unvoiced or if its frequency is - /// outside the current reporting bounds. A target table that has no + /// outside the current frequency bounds. A target table that has no /// selected target does not give `None`. pub target_midi_note: Option, /// This field is `true` if the current pitch estimate is positive and - /// inside the current reporting bounds. + /// inside the current frequency bounds. /// /// This is not an amplitude gate or a confidence score. A tracking result /// can stay between detector updates. @@ -822,13 +822,14 @@ pub struct Telemetry { /// How periodic the tracked input is, in 0..=1. /// /// The value is 1 for a signal that repeats exactly at the tracked - /// period. It is 0 for a signal with no relation between cycles and - /// during pitch acquisition. Use it as a confidence score for - /// [`Feedback::voiced`]. The tracker updates the related sums on each - /// frame. + /// period. It is 0 for a signal with no relation between cycles, during + /// pitch acquisition or if the pitch is outside [`crate::PitchConfig`]. + /// Use it as a confidence score for [`Feedback::voiced`]. The tracker + /// updates the related sums on each frame. pub clarity: f32, - /// This field is `true` if the pitch tracker follows a period. It is - /// `false` during pitch acquisition. + /// This field is `true` if the pitch tracker follows a period inside the + /// current frequency bounds of [`crate::PitchConfig`]. If pitch + /// acquisition is active or the pitch is out of bounds, it is `false`. pub tracking: bool, /// The number of valid entries in [`voice_ratios`](Self::voice_ratios) /// and [`voice_gains`](Self::voice_gains). diff --git a/src/resynthesis.rs b/src/resynthesis.rs index 00a75b7..0a73eb9 100644 --- a/src/resynthesis.rs +++ b/src/resynthesis.rs @@ -166,7 +166,7 @@ impl CorrectionConfig { tsify(large_number_types_as_bigints) )] pub struct ResynthesisConfig { - /// The acquisition sensitivity and the reporting bounds. The + /// The acquisition sensitivity and the frequency bounds. The /// default is [`PitchConfig::default`]. pub pitch: PitchConfig, /// The target notes and the retune time. The default is enabled @@ -789,20 +789,13 @@ impl Resynthesis { } } /// Converts the latest period to samples and hertz and applies the - /// current report limits. + /// current frequency bounds. /// /// The analysis does not advance, and the correction does not change. pub(crate) fn estimate(&self) -> PitchEstimate { - let period = (self.periods[self.write].to_bits() as f64 / 64.0) as f32; - self.config.pitch.report(PitchEstimate { - period_samples: period, - frequency_hz: if period > 0.0 { - self.rate.hz() / period - } else { - 0.0 - }, - voiced: period > 0.0, - }) + self.config + .pitch + .report(self.rate, self.periods[self.write]) } /// Returns the current Q14 correction factor as f32. The result does not /// include other ratios. @@ -827,12 +820,20 @@ impl Resynthesis { /// Returns how periodic the tracked input is, from 0 to 1. Refer to /// `PitchTracker::clarity`. pub(crate) fn clarity(&self) -> f32 { - self.pitch.clarity() + if self.is_tracking() { + self.pitch.clarity() + } else { + 0.0 + } } - /// Returns `true` if the pitch tracker follows a period, and `false` - /// during acquisition. + /// Returns `true` if the pitch tracker follows a period inside the + /// configured frequency bounds. If not, returns `false`. pub(crate) fn is_tracking(&self) -> bool { !self.pitch.is_detecting() + && self + .config + .pitch + .in_bounds(self.rate, self.periods[self.write]) } /// Writes the effective ratio and the linear gain of each active voice /// from the last frame, and returns `1` plus the active secondary voices. @@ -904,7 +905,9 @@ impl Resynthesis { /// period is not positive, the ratio becomes 1.0 immediately. fn update_correction(&mut self, period: Q6) { let mut target_ratio = Q14::ONE; - if self.config.correction.enabled && self.scale.count != 0 { + if !self.config.pitch.in_bounds(self.rate, period) { + self.scale_initialized = false; + } else if self.config.correction.enabled && self.scale.count != 0 { let count = self.scale.count; // The correction table holds periods normalized to one octave. // They use the same units as the shifted target period below. @@ -1105,6 +1108,7 @@ impl Resynthesis { /// tracking was active before this frame. pub(crate) fn process_sample(&mut self, input: i16, numeric: &mut NumericContext) -> [Q14; 2] { let sample = Q14::from_bits(i32::from(input) >> 1); + let was_tracking = self.is_tracking(); self.write += 1; if self.write == HISTORY { self.write = 0; @@ -1113,7 +1117,6 @@ impl Resynthesis { self.written += 1; } self.raw[self.write] = sample; - let was_tracking = !self.pitch.is_detecting(); let step = self.pitch.process_sample(sample.to_bits()); let write = self.write; // Readers have signed fractional coordinates. When the writer wraps, @@ -1139,7 +1142,12 @@ impl Resynthesis { self.formant.detection_mode_off(); } if step.tracking_update { - self.update_correction(step.period); + let period = if self.config.pitch.in_bounds(self.rate, step.period) { + step.period + } else { + Q6::ZERO + }; + self.update_correction(period); } // Use the state from before this sample. If acquisition occurs on // this frame, the choir drift counter starts on the next frame. Read diff --git a/src/wasm.rs b/src/wasm.rs index 15262e2..53a9079 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -366,7 +366,7 @@ impl WasmProcessor { /// /// - The kept pitch estimate is unvoiced. This includes the time before /// the first detection and after a reset or a drain completion. - /// - The estimated frequency is outside the inclusive reporting bounds + /// - The estimated frequency is outside the inclusive frequency bounds /// `minFrequencyHz` and `maxFrequencyHz` of the pitch configuration. /// /// # Errors From d314e17f8556ffcea66736a7297f6f9350459612 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 05:11:03 +0000 Subject: [PATCH 4/4] fix(formant): rebuild active models and align generation tags - Store reflection coefficients and generation tags for each bank - Rebuild valid synthesis banks in set_config on width or stretch edits - Read Telemetry::formant_generation from the active history stamp - If the formant stage has no model, report generation zero - Document immediate envelope updates and stamp generation tags --- README.md | 8 ++- src/formant.rs | 148 +++++++++++++++++++++++++++++++-------------- src/processor.rs | 20 +++--- src/resynthesis.rs | 7 ++- src/wasm.rs | 9 +-- 5 files changed, 129 insertions(+), 63 deletions(-) diff --git a/README.md b/README.md index ab1032e..7f2735e 100644 --- a/README.md +++ b/README.md @@ -309,6 +309,7 @@ The telemetry includes these items: - The `tracking` flag and the pitch clarity, inside the `resynthesis.pitch` bounds. - The current gains of Punch and Warm, and the position in the Alien loop. +- The generation tag of the active formant model. The peak windows of the telemetry are independent of the peak window of the feedback. If a pitch is outside `min_frequency_hz..=max_frequency_hz`, it @@ -319,11 +320,12 @@ timing. `formant_envelope()` writes two LPC envelopes into slices of equal length: - The vocal-tract envelope from the analysis. -- The envelope after the width and stretch controls. +- The envelope after the current width and stretch controls. The values are linear and have no absolute level. The formant stage must be -enabled. The envelopes are those of the model that the audio used for the -last frame. The method returns `Result`: +enabled. The envelopes come from the model stamp of the last audio frame. If +`width` or `stretch` changes, the output envelope and `formant_generation` +update immediately. The method returns `Result`: | Result | Description | | ----------- | ---------------------------------------------------------------- | diff --git a/src/formant.rs b/src/formant.rs index bf9ee5a..4ffbc54 100644 --- a/src/formant.rs +++ b/src/formant.rs @@ -164,12 +164,19 @@ pub(crate) struct Formant { temporary: Vec, /// The Q14 coefficient banks for the inverse filter. inverse: Vec<[i32; ORDER]>, + /// The Q14 reflection coefficients for each bank. `set_config` uses them + /// to rebuild active synthesis models without a new analysis. + parcor: Vec<[i32; ORDER]>, /// The Q14 coefficient banks for the forward filter. `orders` holds the /// active lengths. models: Vec<[i32; MAX_ORDER]>, /// The valid synthesis order for each bank. Zero means that there is no /// feedback model. orders: [usize; BANKS], + /// `true` for banks where the Levinson-Durbin analysis succeeded. + valid: [bool; BANKS], + /// The generation tag of each bank, from the synthesis stamp. + generations: [u32; BANKS], /// One record of a bank pair and a blend for each frame of input history. stamps: Vec, /// The index of the current coefficient bank. @@ -233,8 +240,7 @@ pub(crate) struct Formant { /// The Q14 compensation, from the aspiration cutoff divided by the /// sample rate. noise_amplitude: i32, - /// The wrapping count of model designs that the stage tried. Only the - /// telemetry reads it. + /// The modular count of synthesis model builds and rebuilds. generation: u32, } @@ -272,8 +278,11 @@ impl Formant { input: vec![0; HISTORY_FRAMES], temporary: vec![0_i32; (2 * (rate.as_u32() as usize / 40) + MAX_ORDER + 256).max(2865)], inverse: vec![[0; ORDER]; BANKS], + parcor: vec![[0; ORDER]; BANKS], models: vec![[0; MAX_ORDER]; BANKS], orders: [0; BANKS], + valid: [false; BANKS], + generations: [0; BANKS], stamps: vec![Stamp::default(); HISTORY_FRAMES], current: 1, previous: 0, @@ -303,13 +312,15 @@ impl Formant { result.set_config(config); result } - /// Quantizes the validated controls, prepares the Q7 map for the area - /// interpolation and updates the coefficients of the aspiration filter. + /// Quantizes the validated controls, prepares the Q7 area map and updates + /// the aspiration filter. If width or stretch changes, it also rebuilds + /// the active synthesis models. /// - /// The histories do not change. A valid stretch gives a model with 25 to - /// 99 entries. Thus, the last point of the map and the denominators of - /// the interpolation are always defined. + /// The audio histories do not change. A valid stretch gives a model with + /// 25 to 99 entries. Thus, the last point of the map and the denominators + /// of the interpolation are always defined. pub(crate) fn set_config(&mut self, config: FormantConfig) { + let rebuild = self.config.width != config.width || self.config.stretch != config.stretch; self.config = config; self.width = (config.width as f64 * 16384.0) as i32; self.width_squared = (config.width as f64 * config.width as f64 * 16384.0) as i32; @@ -328,6 +339,20 @@ impl Formant { self.noise_amplitude = (frequency as f64 * 0.8 / self.rate.hz() as f64 * 16384.0) as i32; self.noise_filter .set_design(Design::high_pass(self.rate.hz(), frequency as f32, 0.707)); + if rebuild { + for offset in 1..=BANKS { + let bank = (self.current + offset) % BANKS; + if self.valid[bank] { + self.build_model(bank); + if self.orders[bank] != 0 { + self.generation = self.generation.wrapping_add(1); + self.generations[bank] = self.generation; + } else { + self.generations[bank] = 0; + } + } + } + } } /// Clears the audio, the stamps, the synthesis history and the history of /// the aspiration filter. @@ -343,6 +368,9 @@ impl Formant { self.input.fill(0_i32); self.stamps.fill(Stamp::default()); + self.orders.fill(0); + self.valid.fill(false); + self.generations.fill(0); self.history = [[0; MAX_ORDER]; 2]; self.history_index = 0; self.current = BANKS - 1; @@ -410,9 +438,54 @@ impl Formant { } self.blend = 0; self.inverse[self.current].fill(0_i32); - + self.parcor[self.current].fill(0_i32); self.models[self.current].fill(0_i32); self.orders[self.current] = 0; + self.valid[self.current] = false; + self.generations[self.current] = 0; + } + + /// Builds the forward synthesis model for `bank` from its kept reflection + /// and inverse coefficients. + fn build_model(&mut self, bank: usize) { + let one = 16384; + self.models[bank].fill(0_i32); + self.orders[bank] = 0; + if self.width != one || self.stretch != one { + if let Some(scale) = lpc::parcor_to_areas(&self.parcor[bank], &mut self.areas) { + for i in 0..self.stretch_count { + let map = self.stretch_map[i]; + let index = map.wrapping_shr(7).min((ORDER - 2) as i32) as usize; + let fraction = map.wrapping_sub((index as i32) << 7).wrapping_shl(7); + self.stretched_areas[i] = mul14( + mul14(one.wrapping_sub(fraction), self.areas[index]) + .wrapping_add(mul14(fraction, self.areas[index + 1])), + self.width_squared, + ); + if self.stretched_areas[i] == 0_i32 { + self.stretched_areas[i] = 1; + } + } + let mut parcor = [0; MAX_ORDER]; + let mut scratch = [0; 112]; + if lpc::areas_to_parcor( + &self.stretched_areas[..self.stretch_count], + &mut parcor, + scale, + ) { + lpc::parcor_to_pef( + &parcor[..self.stretch_count], + &mut self.models[bank], + &mut scratch, + 14, + ); + self.orders[bank] = self.stretch_count; + } + } + } else { + self.models[bank][..ORDER].copy_from_slice(&self.inverse[bank]); + self.orders[bank] = ORDER; + } } /// Calculates the average of a maximum of two autocorrelation vectors. It /// does not allocate memory. @@ -601,52 +674,23 @@ impl Formant { // inverse coefficients can stay in the bank. But the synthesis // order stays zero until all necessary model changes complete. self.next_filter(); - self.generation = self.generation.wrapping_add(1); let design_gain = ((db_to_gain(-60.0) + 1.0) * 16384.0) as i32; correlations[0] = mul14(correlations[0], design_gain).wrapping_add(200); - let mut parcor = [0; MAX_ORDER]; let mut scratch = [0; 112]; let valid = lpc::durbin( &correlations, &mut self.inverse[self.current], - &mut parcor, + &mut self.parcor[self.current], &mut scratch, ); + self.valid[self.current] = valid; if valid { - if self.width != one || self.stretch != one { - if let Some(scale) = lpc::parcor_to_areas(&parcor[..ORDER], &mut self.areas) { - for i in 0..self.stretch_count { - let map = self.stretch_map[i]; - let index = map.wrapping_shr(7).min((ORDER - 2) as i32) as usize; - let fraction = map.wrapping_sub((index as i32) << 7).wrapping_shl(7); - self.stretched_areas[i] = mul14( - mul14(one.wrapping_sub(fraction), self.areas[index]) - .wrapping_add(mul14(fraction, self.areas[index + 1])), - self.width_squared, - ); - if self.stretched_areas[i] == 0_i32 { - self.stretched_areas[i] = 1; - } - } - if lpc::areas_to_parcor( - &self.stretched_areas[..self.stretch_count], - &mut parcor, - scale, - ) { - lpc::parcor_to_pef( - &parcor[..self.stretch_count], - &mut self.models[self.current], - &mut scratch, - 14, - ); - self.orders[self.current] = self.stretch_count; - } - } - } else { - self.models[self.current][..ORDER].copy_from_slice(&self.inverse[self.current]); - self.orders[self.current] = ORDER; + self.build_model(self.current); + if self.orders[self.current] != 0 { + self.generation = self.generation.wrapping_add(1); + self.generations[self.current] = self.generation; } } else { self.smooth_reset = true; @@ -740,9 +784,21 @@ impl Formant { } &output[..order] } - /// Returns the wrapping count of model designs that the stage tried. - pub(crate) fn generation(&self) -> u32 { - self.generation + /// Returns the generation tag of the synthesis model at a signed history + /// frame. If the stamp has no synthesis model, returns zero. + pub(crate) fn generation(&self, position: i32) -> u32 { + let stamp = self.stamps[position.rem_euclid(HISTORY_FRAMES as i32) as usize]; + let current = usize::from(stamp.current); + if self.orders[current] != 0 { + self.generations[current] + } else { + let previous = usize::from(stamp.previous); + if stamp.blend < 16384 && self.orders[previous] != 0 { + self.generations[previous] + } else { + 0 + } + } } /// Finds and blends the analysis coefficients of the stamp at a signed /// history frame, in the same way as [`Self::coefficients`]. diff --git a/src/processor.rs b/src/processor.rs index 4bc71c8..e49c118 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -411,10 +411,12 @@ impl Processor { /// last frame. /// /// `input` gets the vocal-tract envelope that the LPC analysis found. - /// `output` gets the envelope after the width and stretch controls. Point - /// `k` of `n` is at the frequency `max_frequency_hz * k / (n - 1)`. The - /// values are linear magnitudes. They have no absolute level, because the - /// analysis normalizes the signal energy. Scale them for a display. + /// `output` gets the envelope after the current width and stretch + /// controls. If `width` or `stretch` changes, `output` updates + /// immediately. Point `k` of `n` is at the frequency + /// `max_frequency_hz * k / (n - 1)`. The values are linear magnitudes. + /// They have no absolute level, because the analysis normalizes the signal + /// energy. Scale them for a display. /// /// `max_frequency_hz` must be finite, more than zero and not more than /// half of the sample rate. The two slices must have the same length. @@ -879,10 +881,12 @@ pub struct Telemetry { /// The reverse reader is two times this number of frames behind the /// recording position. The value advances also while Alien is disabled. pub alien_phase_frames: u32, - /// The wrapping count of formant analyses since construction. + /// The generation tag of the formant synthesis model for the last frame. /// - /// The count increases every 441 frames while the formant stage is - /// enabled. Compare two values to find if - /// [`Processor::formant_envelope`] can give a new result. + /// While the formant stage is disabled or has no synthesis model, the + /// value is zero. If playback reaches a new analysis bank or a + /// configuration change updates `width` or `stretch`, the value changes. + /// Compare two values to find if [`Processor::formant_envelope`] has a + /// new result. pub formant_generation: u32, } diff --git a/src/resynthesis.rs b/src/resynthesis.rs index 0a73eb9..7e57916 100644 --- a/src/resynthesis.rs +++ b/src/resynthesis.rs @@ -870,9 +870,12 @@ impl Resynthesis { count as u8 } } - /// Returns the wrapping count of formant model designs. + /// Returns the generation tag of the active formant stamp. pub(crate) fn formant_generation(&self) -> u32 { - self.formant.generation() + if !self.config.formant.enabled { + return 0; + } + self.formant.generation(self.formant_position) } /// Writes the formant envelopes of the model that the audio used for the /// last frame. Refer to `Formant::envelope`. diff --git a/src/wasm.rs b/src/wasm.rs index 53a9079..b72a772 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -426,10 +426,11 @@ impl WasmProcessor { /// `Float32Array` buffers of equal length. /// /// `input` gets the vocal-tract envelope that the LPC analysis found. - /// `output` gets the envelope after the width and stretch controls. Point - /// `k` of `n` is at the frequency `maxFrequencyHz * k / (n - 1)`. The - /// values are linear magnitudes with no absolute level. Scale them for a - /// display. + /// `output` gets the envelope after the current width and stretch + /// controls. If `width` or `stretch` changes, `output` updates + /// immediately. Point `k` of `n` is at the frequency + /// `maxFrequencyHz * k / (n - 1)`. The values are linear magnitudes with + /// no absolute level. Scale them for a display. /// /// `maxFrequencyHz` must be finite, more than zero and not more than half /// of the sample rate.