From ae0978b1c4e34bb89e17e051eb52f78f5b873a99 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Tue, 24 Nov 2026 04:43:02 +0000 Subject: [PATCH 1/2] feat(pitch)!: enforce vocal range presets and period holdoff - Add VocalRange presets to PitchConfig for Rust and Wasm - Convert the active vocal range bounds into Q6 period limits - Increase ACQUISITION_LAGS to 305 for bass pitch acquisition - Enforce the Q6 period limits in PitchTracker and host reports - Check the cycle clarity at each 5-frame period update - Clear previous_period after 20 ms without a tracked pitch - Clear previous_period and the harmony envelopes on reset - Release the harmony gains when the output period is zero - Set the voice ratios to unity when the output period is zero --- README.md | 11 ++- src/harmony.rs | 41 ++++++++--- src/lib.rs | 11 ++- src/pitch.rs | 112 ++++++++++++++++++++++++------ src/pitch/tracker.rs | 161 ++++++++++++++++++++++++++++++------------- src/processor.rs | 16 ++--- src/resynthesis.rs | 61 ++++++++++------ src/wasm.rs | 4 +- 8 files changed, 296 insertions(+), 121 deletions(-) diff --git a/README.md b/README.md index 83a8f47..ab48f21 100644 --- a/README.md +++ b/README.md @@ -178,6 +178,13 @@ multi-voice mixes. `resynthesis.dry_mix` sets the dry fraction at the resynthesis stage. The dry path starts after Warm and has a delay of 1,543 frames. +`resynthesis.pitch.vocal_range` selects `Custom`, `Soprano` (240 to 1,100 Hz), +`AltoTenor` (120 to 600 Hz) or `BaritoneBass` (45 to 360 Hz). The default is +`Custom`, which uses `min_frequency_hz` to `max_frequency_hz` (40 to 1,100 Hz +by default). Pitches outside the active vocal range do not acquire or track. If +there is no tracked pitch for 20 ms, the fallback period becomes zero. Then the +lead ratio returns to 1 and the harmony voices release toward zero. + ### Harmony sources Set `resynthesis.mode` to `Harmony`. Then select the source of the voices @@ -489,8 +496,8 @@ 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 - `resynthesis.pitch.minFrequencyHz` and `resynthesis.pitch.maxFrequencyHz`. +- The estimated period is outside the active `resynthesis.pitch.vocalRange` + preset or the custom `minFrequencyHz` and `maxFrequencyHz` bounds. `formantEnvelope(maxFrequencyHz, input, output)` fills two `Float32Array` buffers of equal length and returns `false` if no envelope is available. diff --git a/src/harmony.rs b/src/harmony.rs index ce9fb1f..e53fbcc 100644 --- a/src/harmony.rs +++ b/src/harmony.rs @@ -27,7 +27,8 @@ const GAIN_ATTACK: Q12 = Q12::from_bits(163); /// The Q12 step that decreases the gain envelope of a voice toward a lower /// target gain (release). /// -/// The step applies one time at each voiced control step. From a gain of 1.0 +/// The step applies one time at each control step toward a lower target, +/// also on unvoiced steps after the period becomes zero. From a gain of 1.0 /// to zero, the release takes 51 steps. The period portamento does not use /// this value. const GAIN_RELEASE: Q12 = Q12::from_bits(81); @@ -251,8 +252,9 @@ pub enum Inversion { /// /// The gain attack, the gain release and the period portamento advance at /// the controller cadence. This cadence is usually every 101 frames. A MIDI -/// event can make the next control step occur sooner. The envelopes and the -/// portamento advance only while the input is voiced. +/// event can make the next control step occur sooner. The attack and the +/// portamento advance only while the input is voiced. If the kept period is +/// zero, the gain envelopes release toward zero. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] #[cfg_attr( @@ -423,8 +425,8 @@ pub(crate) struct HarmonyState { /// The last usable Q14 ratio of the input period to the smoothed target /// period for each voice. current_ratio: [Q14; HARMONY_VOICES], - /// The Q12 attack and release envelope. A MIDI release or a reset does - /// not clear it. + /// The Q12 attack and release envelope. A MIDI release keeps it, and an + /// audio reset clears it. smoothed_gain: [Q12; HARMONY_VOICES], /// The last active Q6 target. It is kept while the gain of a released /// voice decreases to zero. @@ -570,6 +572,14 @@ impl HarmonyState { self.setup_chord(); } } + /// Clears the gain envelopes, the output periods and the voice ratios at + /// an audio reset. + pub(crate) fn clear_envelopes(&mut self) { + self.smoothed_gain.fill(Q12::ZERO); + self.period_output.fill(Q6::ZERO); + self.target_period.fill(Q6::ZERO); + self.current_ratio.fill(Q14::ONE); + } /// Converts cents above C4 to a Q6 sample period. C4 is 900 cents below /// A4 at 440 Hz. /// The intermediate period is rounded to f32 before the fixed-point @@ -817,17 +827,20 @@ impl HarmonyState { /// Advances one voice from the Q6 tracked input period to a Q14 ratio and /// a Q12 gain. /// The voice index must be less than `HARMONY_VOICES`. If the input is - /// unvoiced (zero), the function returns a unity ratio and silence. It - /// also clears the portamento start state and keeps the gain envelope. + /// unvoiced (zero), the function decreases the gain envelope by + /// `GAIN_RELEASE` and clears the portamento start state. Then it returns a + /// unity ratio and the new gain. /// If the input is voiced, the function advances the gain envelope. It /// keeps the target of a released voice until the gain is zero. Then, in /// the same step, it applies portamento in the period domain. pub(crate) fn advance_voice(&mut self, period: Q6, voice: usize) -> (Q14, Q12) { - if period == Q6::ZERO { + let target_gain = if period == Q6::ZERO { + self.target_period[voice] = Q6::ZERO; self.portamento_period[voice] = Q6::ZERO; - return (Q14::ONE, Q12::ZERO); - } - let target_gain = self.select_target(period, voice); + Q12::ZERO + } else { + self.select_target(period, voice) + }; if self.smoothed_gain[voice] < target_gain { self.smoothed_gain[voice] = (self.smoothed_gain[voice] + GAIN_ATTACK).min(target_gain); } else if self.smoothed_gain[voice] > target_gain { @@ -839,6 +852,12 @@ impl HarmonyState { self.period_output[voice] = Q6::ZERO; self.portamento_period[voice] = Q6::ZERO; } + if period == Q6::ZERO { + if self.smoothed_gain[voice] == Q12::ZERO { + self.current_ratio[voice] = Q14::ONE; + } + return (Q14::ONE, self.smoothed_gain[voice]); + } if self.period_output[voice] > Q6::ZERO { self.portamento_period[voice] = if self.portamento_period[voice] == Q6::ZERO { self.period_output[voice] diff --git a/src/lib.rs b/src/lib.rs index f17bc85..110233b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -50,11 +50,10 @@ //! //! [`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 active vocal +//! range limits acquisition, tracking and feedback reports. +//! [`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 @@ -133,7 +132,7 @@ pub use harmony::{ ChordDegree, ChordName, HarmonyConfig, HarmonyScale, HarmonySource, Inversion, HARMONY_VOICES, }; pub use midi::MidiEvent; -pub use pitch::PitchConfig; +pub use pitch::{PitchConfig, VocalRange}; pub use processor::{Feedback, Processor, Telemetry}; pub use resynthesis::{CorrectionConfig, MultiVoiceMode, ResynthesisConfig}; pub use scale::{CorrectionScale, NoteMask, PitchClass}; diff --git a/src/pitch.rs b/src/pitch.rs index 6b682ca..57cf3e3 100644 --- a/src/pitch.rs +++ b/src/pitch.rs @@ -1,17 +1,44 @@ //! The acquisition and tracking of pitch with fixed-point cycle-difference //! 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. +//! Acquisition checks that repeated minima agree inside the active vocal +//! range. Tracking refines the period in a window of 40 lags and checks cycle +//! clarity. The active vocal range filters acquisition, tracking and feedback +//! to the host. 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. +/// A vocal range preset or custom bounds for pitch detection and reports. +/// +/// The default is [`Self::Custom`], which uses `min_frequency_hz` and +/// `max_frequency_hz` from [`PitchConfig`]. Each other variant sets fixed +/// inclusive bounds for pitch acquisition, tracking and feedback reports. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + derive(serde::Serialize, serde::Deserialize, tsify::Tsify), + serde(rename_all = "camelCase") +)] +pub enum VocalRange { + /// Custom bounds from `min_frequency_hz` and `max_frequency_hz` in + /// [`PitchConfig`]. + #[default] + Custom, + /// The soprano range, 240..=1100 Hz. + Soprano, + /// The alto and tenor range, 120..=600 Hz. + AltoTenor, + /// The baritone and bass range, 45..=360 Hz. + BaritoneBass, +} + +/// The vocal range, acquisition sensitivity and bounds for pitch detection and +/// host reports. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] #[cfg_attr( @@ -20,30 +47,40 @@ use crate::Error; serde(rename_all = "camelCase") )] pub struct PitchConfig { + /// The vocal range preset, or [`VocalRange::Custom`] for custom bounds. + /// + /// The default is [`VocalRange::Custom`]. If you select a named preset, + /// its frequency bounds override `min_frequency_hz` and `max_frequency_hz` + /// for detection and reports. Validation still checks those two fields. + pub vocal_range: VocalRange, /// The normalized cycle-difference threshold for acquisition, 0.002..=0.2. /// /// The default is 0.1. Larger values accept less exact cycle agreement. /// 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 bound for [`VocalRange::Custom`] 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. + /// The default is 40. It must be strictly less than `max_frequency_hz`, + /// also when a named preset in `vocal_range` overrides it. Pitches below + /// the active range do not acquire or track, and feedback reports them as + /// unvoiced. pub min_frequency_hz: f32, - /// The upper bound of the feedback in hertz (inclusive), 40..=2000. + /// The upper bound for [`VocalRange::Custom`] 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`, also when a named preset in `vocal_range` overrides + /// it. Pitches above the active range do not acquire or track, and + /// feedback reports them as unvoiced. pub max_frequency_hz: f32, } impl Default for PitchConfig { fn default() -> Self { Self { + vocal_range: VocalRange::Custom, threshold: 0.1, min_frequency_hz: 40.0, max_frequency_hz: 1100.0, @@ -52,16 +89,44 @@ impl Default for PitchConfig { } impl PitchConfig { - /// Applies only the bounds for host reports to a kept estimate. + /// Returns the active inclusive frequency bounds `(min_hz, max_hz)`. + pub(crate) fn frequency_bounds(self) -> (f32, f32) { + match self.vocal_range { + VocalRange::Custom => (self.min_frequency_hz, self.max_frequency_hz), + VocalRange::Soprano => (240.0, 1100.0), + VocalRange::AltoTenor => (120.0, 600.0), + VocalRange::BaritoneBass => (45.0, 360.0), + } + } + + /// Converts the active frequency bounds into inclusive Q6 period limits + /// `(min_period, max_period)` at `rate`. + pub(crate) fn period_bounds(self, rate: SampleRate) -> (Q6, Q6) { + let (min_hz, max_hz) = self.frequency_bounds(); + let scale = f64::from(rate.as_u32()) * 64.0; + let raw_min = (scale / f64::from(max_hz)).floor() as i32; + let raw_max = (scale / f64::from(min_hz)).ceil() as i32; + let min_slop = (raw_min >> 10).max(8); + let max_slop = (raw_max >> 10).max(8); + ( + Q6::from_bits((raw_min - min_slop).max(1)), + Q6::from_bits(raw_max.saturating_add(max_slop)), + ) + } + + /// Applies the active Q6 period limits at `rate` to a kept estimate. /// - /// 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 - { + /// If the estimate is not voiced or its period is outside the active + /// 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, + rate: SampleRate, + period: Q6, + estimate: PitchEstimate, + ) -> PitchEstimate { + let (min_period, max_period) = self.period_bounds(rate); + if estimate.voiced && period >= min_period && period <= max_period { estimate } else { PitchEstimate::default() @@ -71,6 +136,9 @@ impl PitchConfig { /// Checks the threshold, then each frequency range, then the order of the /// frequencies. /// + /// Validation checks `min_frequency_hz` and `max_frequency_hz` also when + /// `vocal_range` selects a named preset. + /// /// # Errors /// /// Returns [`Error::InvalidConfig`] for a value that is not finite or is diff --git a/src/pitch/tracker.rs b/src/pitch/tracker.rs index c46ed9b..71026c2 100644 --- a/src/pitch/tracker.rs +++ b/src/pitch/tracker.rs @@ -8,10 +8,10 @@ //! resolution of the period. //! //! 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. +//! minimum is at a boundary, the cycle clarity is too low or the curvature is +//! zero, acquisition starts again. If the period leaves the active vocal +//! range, acquisition also starts again. The last usable period stays +//! available for 20 ms as a fallback for resynthesis, then becomes zero. use super::search::{tracking_minimum, TRACKING_LAGS}; use crate::filter::{Biquad, Design}; @@ -30,8 +30,8 @@ pub(crate) struct PitchStep { /// The current Q6 period. It is zero while acquisition has no refined /// tracking result. pub period: Q6, - /// The last refined Q6 period. It stays when the current tracking starts - /// again. + /// The last refined Q6 period. It stays for 20 ms after tracking restarts, + /// then becomes zero. pub previous_period: Q6, /// `true` if this sample gave a new refined period. pub tracking_update: bool, @@ -44,13 +44,15 @@ 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. /// /// The audio history and the filtered samples are Q14 words. The acquisition /// energies and cross terms are plain wrapping words. pub(crate) struct PitchTracker { + /// The fixed sample rate, which converts frequency bounds into Q6 periods. + rate: SampleRate, /// Two low-pass sections before the 8:1 decimation for acquisition. /// /// Full-rate tracking uses the raw audio. @@ -92,9 +94,19 @@ pub(crate) struct PitchTracker { tracking_counter: i32, /// The latest refined Q6 period. A restart of acquisition sets it to zero. period: Q6, - /// The last refined Q6 period. A restart or an audio reset does not clear - /// it. + /// The last refined Q6 period. An audio reset clears it. After 20 ms + /// without a tracked period, it becomes zero. previous_period: Q6, + /// The active inclusive lower Q6 period bound, from the maximum frequency. + min_period: Q6, + /// The active inclusive upper Q6 period bound, from the minimum frequency. + max_period: Q6, + /// The number of unvoiced frames before `previous_period` becomes zero + /// (20 ms). + holdoff_limit: u16, + /// The count of consecutive frames without a tracked period while + /// `previous_period` is not zero. + holdoff_frames: u16, /// The Q14 threshold of the normalized difference. It applies only to the /// acceptance of acquisition minima. threshold: Q14, @@ -107,13 +119,16 @@ impl PitchTracker { /// Prepares the acquisition filters and allocates the silent full-rate /// history. /// The two supported rates use low-pass cutoffs at rate/32 and at 1.5 - /// times that cutoff. The validated sensitivity is quantized to Q14. + /// times that cutoff. The validated sensitivity is quantized to Q14, and + /// the vocal range sets the Q6 period bounds. pub(crate) fn new(rate: SampleRate, config: PitchConfig) -> Self { let mut pre = [Biquad::new(), Biquad::new()]; let cutoff = rate.hz() / 16.0 / 2.0; pre[0].set_design(Design::low_pass(rate.hz(), cutoff, 0.707)); pre[1].set_design(Design::low_pass(rate.hz(), cutoff * 1.5, 0.707)); + let (min_period, max_period) = config.period_bounds(rate); Self { + rate, pre, raw: vec![0; HISTORY] .into_boxed_slice() @@ -134,22 +149,41 @@ impl PitchTracker { tracking_counter: 0, period: Q6::default(), previous_period: Q6::default(), + min_period, + max_period, + holdoff_limit: (rate.as_u32() / 50) as u16, + holdoff_frames: 0, threshold: Q14::from_f64(config.threshold as f64), best: 0, } } - /// Updates only the acquisition sensitivity. - /// The reporting 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) { + /// Updates the acquisition sensitivity and the Q6 period limits. + /// + /// If the tracked period is outside the new limits, acquisition starts + /// again and the function returns `true`. If the fallback period is + /// outside the new limits, the function clears it immediately. + pub(crate) fn set_config(&mut self, config: PitchConfig) -> bool { + let was_tracking = !self.detecting; self.threshold = Q14::from_f64(config.threshold as f64); + let (min_period, max_period) = config.period_bounds(self.rate); + self.min_period = min_period; + self.max_period = max_period; + if self.period != Q6::ZERO && (self.period < min_period || self.period > max_period) { + self.restart(); + } + if self.previous_period != Q6::ZERO + && (self.previous_period < min_period || self.previous_period > max_period) + { + self.previous_period = Q6::ZERO; + self.holdoff_frames = 0; + } + was_tracking && self.detecting } - /// Clears the full-rate audio, the current period and the prefilter - /// memories, and requests acquisition. - /// The acquisition tables clear at the next decimated call. The previous - /// usable period stays until another tracking update replaces it. + /// Clears the full-rate audio, the current and previous periods and the + /// prefilter memories, and requests acquisition. + /// The acquisition tables clear at the next decimated call. pub(crate) fn reset(&mut self) { let written = usize::from(self.written); if written == HISTORY { @@ -159,6 +193,8 @@ impl PitchTracker { } self.written = 0; self.write = 0; + self.previous_period = Q6::ZERO; + self.holdoff_frames = 0; self.restart(); for pre in &mut self.pre { pre.reset(); @@ -321,7 +357,7 @@ impl PitchTracker { &mut self.cross[lag..end], ); index1 = if count == index1 + 1 { - 273 + 2 * ACQUISITION_LAGS - 1 } else { index1 - count }; @@ -424,7 +460,13 @@ impl PitchTracker { if best == 0 { 0 } else { - ((128_i32.wrapping_add(best)) >> 8).wrapping_sub(20) + let candidate = Q6::from_bits(best.wrapping_add(2) >> 2); + let margin = Q6::from_bits(8 * 64); + if candidate + margin < self.min_period || candidate - margin > self.max_period { + 0 + } else { + ((128_i32.wrapping_add(best)) >> 8).wrapping_sub(20) + } } } @@ -563,9 +605,10 @@ impl PitchTracker { /// Q6 period. If the minimum is outside slots 18..=21, the lag window /// first moves one lag toward it. /// - /// If the minimum is at a window boundary, its lag is 19 or less, or the - /// curvature is zero, acquisition starts again. The last usable period is - /// not discarded. + /// If the minimum is at a boundary, its lag is 19 or less, its clarity is + /// below 0.5 or the curvature is zero, acquisition starts again. If its + /// period is outside the vocal range, acquisition also starts again. The + /// last usable period stays for 20 ms, then becomes zero. pub(crate) fn process_sample(&mut self, sample: i32) -> PitchStep { self.write += 1; if self.write == HISTORY { @@ -665,39 +708,61 @@ impl PitchTracker { } } if !self.detecting { - let y0 = (self.tracking_energy[best - 1] >> 1) - .wrapping_sub(self.tracking_cross[best - 1]); - let y1 = (self.tracking_energy[best] >> 1) - .wrapping_sub(self.tracking_cross[best]); - let y2 = (self.tracking_energy[best + 1] >> 1) - .wrapping_sub(self.tracking_cross[best + 1]); - let mut numerator = y0.wrapping_sub(y2) >> 1; - let mut denominator = y1.wrapping_mul(-2).wrapping_add(y0).wrapping_add(y2); - let abs = numerator.wrapping_abs(); - if abs > ONE { - let sh0 = 31 - ((abs as u32) >> 14).leading_zeros(); - let sh = sh0 + u32::from((numerator >> sh0).wrapping_abs() > ONE); - numerator >>= sh; - denominator >>= sh; - } - if denominator == 0 { + let energy = self.tracking_energy[best]; + let cross = self.tracking_cross[best]; + if energy <= 0 || i64::from(cross) * 4 < i64::from(energy) { self.restart(); step.restarted = true; } else { - let fraction = numerator.wrapping_shl(14).wrapping_div(denominator); - // The lag in Q8 plus the parabolic fraction - // (Q14 >> 6), rounded to Q6. - let lag = self.base.wrapping_add(best as i32).wrapping_shl(8); - self.period = - Q6::from_bits(lag.wrapping_add(fraction >> 6).wrapping_add(2) >> 2); - self.previous_period = self.period; - self.best = best; - step.tracking_update = true; + let y0 = (self.tracking_energy[best - 1] >> 1) + .wrapping_sub(self.tracking_cross[best - 1]); + let y1 = (energy >> 1).wrapping_sub(cross); + let y2 = (self.tracking_energy[best + 1] >> 1) + .wrapping_sub(self.tracking_cross[best + 1]); + let mut numerator = y0.wrapping_sub(y2) >> 1; + let mut denominator = + y1.wrapping_mul(-2).wrapping_add(y0).wrapping_add(y2); + let abs = numerator.wrapping_abs(); + if abs > ONE { + let sh0 = 31 - ((abs as u32) >> 14).leading_zeros(); + let sh = sh0 + u32::from((numerator >> sh0).wrapping_abs() > ONE); + numerator >>= sh; + denominator >>= sh; + } + if denominator == 0 { + self.restart(); + step.restarted = true; + } else { + let fraction = numerator.wrapping_shl(14).wrapping_div(denominator); + // The lag in Q8 plus the parabolic fraction + // (Q14 >> 6), rounded to Q6. + let lag = self.base.wrapping_add(best as i32).wrapping_shl(8); + let period = Q6::from_bits( + lag.wrapping_add(fraction >> 6).wrapping_add(2) >> 2, + ); + if period < self.min_period || period > self.max_period { + self.restart(); + step.restarted = true; + } else { + self.period = period; + self.previous_period = period; + self.holdoff_frames = 0; + self.best = best; + step.tracking_update = true; + } + } } } } } } + if self.period == Q6::ZERO && self.previous_period != Q6::ZERO { + self.holdoff_frames += 1; + if self.holdoff_frames >= self.holdoff_limit { + self.previous_period = Q6::ZERO; + self.holdoff_frames = 0; + } + } step.period = self.period; step.previous_period = self.previous_period; step diff --git a/src/processor.rs b/src/processor.rs index 83bccf6..1758207 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -517,10 +517,6 @@ impl Processor { /// - the random stream and the arctangent lookup position of Punch /// - the reverb low-pass memories and the reverb write position /// - correction key 127 and the active correction note table - /// - the last usable period of the pitch tracker, which fills unvoiced - /// gaps - /// - the harmony gain envelopes and the last voice ratios of the harmony - /// controller /// - the prepared chord targets of the named and degree chord sources /// - the choir drift /// - the control-step counter of Choir and Harmony @@ -725,8 +721,8 @@ 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 - /// [`crate::PitchConfig`]. + /// It is zero if the input is unvoiced or outside the active vocal range + /// of [`crate::PitchConfig`]. pub period_samples: f32, /// The reported input pitch frequency in hertz. /// @@ -748,12 +744,12 @@ pub struct Feedback { /// is not the final pitch of shifted output or harmony output. /// /// 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 - /// selected target does not give `None`. + /// then. This occurs if the input is unvoiced or if its period is outside + /// the active vocal range. 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 active vocal range. /// /// This is not an amplitude gate or a confidence score. A tracking result /// can stay between detector updates. diff --git a/src/resynthesis.rs b/src/resynthesis.rs index 7f5eda5..27cfaf5 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 vocal range, acquisition sensitivity and frequency bounds. The /// default is [`PitchConfig::default`]. pub pitch: PitchConfig, /// The target notes and the retune time. The default is enabled @@ -394,8 +394,8 @@ pub(crate) struct Resynthesis { /// replace a delayed entry with its resampled output period. This aligns /// the secondary voices. periods: Box<[Q6; HISTORY]>, - /// The last usable Q6 tracker periods. The code keeps them through - /// unvoiced gaps. + /// The last usable Q6 tracker periods. Each period stays for 20 ms across + /// short unvoiced gaps, then becomes zero. previous_periods: Box<[Q6; HISTORY]>, /// The Q14 ratios of the correction only, aligned to each recorded input /// frame. @@ -427,7 +427,7 @@ pub(crate) struct Resynthesis { /// The last Q14 target ratios from the harmony controller. harmony_ratios: [Q14; HARMONY_VOICES], /// The last Q12 gain envelopes from the harmony controller. An audio - /// reset keeps them. + /// reset clears them. harmony_gains: [Q12; HARMONY_VOICES], /// The effective Q14 ratios of the lead and the four harmony readers from /// the last frame. In Choir mode, only the lead slot changes. Only the @@ -649,7 +649,10 @@ impl Resynthesis { pub(crate) fn apply_config(&mut self, config: ResynthesisConfig) { let old = self.config; self.config = config; - self.pitch.set_config(config.pitch); + if self.pitch.set_config(config.pitch) { + self.correction = Q14::ONE; + self.scale_initialized = false; + } self.formant.set_config(config.formant); self.harmony.apply_config(config.harmony); if old.correction.notes != config.correction.notes @@ -697,7 +700,6 @@ impl Resynthesis { /// - The choir drift. /// - The modulation phase. /// - The control counter. - /// - The harmony release envelopes and the last harmony gains. fn reset_audio(&mut self) { let written = usize::from(self.written); self.written = 0; @@ -730,6 +732,7 @@ impl Resynthesis { self.write = 0; self.formant.reset(); self.harmony.reset(); + self.harmony.clear_envelopes(); if written >= OVERLAP_FRAMES { self.overlap.fill(Q14::ZERO); } else if written > 0 { @@ -745,6 +748,7 @@ impl Resynthesis { self.old_position = self.positions[0]; self.fade = Q14::ONE; self.harmony_ratios.fill(Q14::ONE); + self.harmony_gains.fill(Q12::ZERO); self.voice_ratios.fill(Q14::ONE); self.formant_position = 0; self.current_output_period = Q6::ZERO; @@ -789,20 +793,25 @@ impl Resynthesis { } } /// Converts the latest period to samples and hertz and applies the - /// current report limits. + /// active vocal range limits. /// /// 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 + let raw_period = self.periods[self.write]; + let period = (raw_period.to_bits() as f64 / 64.0) as f32; + self.config.pitch.report( + self.rate, + raw_period, + PitchEstimate { + period_samples: period, + frequency_hz: if period > 0.0 { + self.rate.hz() / period + } else { + 0.0 + }, + voiced: period > 0.0, }, - voiced: period > 0.0, - }) + ) } /// Returns the current Q14 correction factor as f32. The result does not /// include other ratios. @@ -848,9 +857,13 @@ impl Resynthesis { gains[0] = 1.0; if self.config.mode == MultiVoiceMode::Choir { let count = self.config.choir_voices as usize; + let unvoiced = self.current_output_period == Q6::ZERO; for voice in 1..count { - ratios[voice] = - (lead as f64 * self.drift_ratio[voice].to_bits() as f64 / 16384.0) as f32; + ratios[voice] = if unvoiced { + 1.0 + } else { + (lead as f64 * self.drift_ratio[voice].to_bits() as f64 / 16384.0) as f32 + }; gains[voice] = 1.0; } count as u8 @@ -1213,7 +1226,11 @@ impl Resynthesis { let delay = ring(delayed as i32 - self.delays[current_voice]); let (period, _) = self.period_for(delay, write); self.current_output_period = period; - let ratio = self.drift_ratio[current_voice]; + let ratio = if period == Q6::ZERO { + Q14::ONE + } else { + self.drift_ratio[current_voice] + }; final_ratio = ratio; *position = self.move_reader( current_voice, @@ -1245,7 +1262,11 @@ impl Resynthesis { let delay = ring(delayed as i32 - self.delays[voice]); let (period, _) = self.period_for(delay, write); self.current_output_period = period; - let ratio = self.drift_ratio[voice]; + let ratio = if period == Q6::ZERO { + Q14::ONE + } else { + self.drift_ratio[voice] + }; final_ratio = ratio; let position = self.move_reader(voice, ratio, period, self.delays[voice], false); diff --git a/src/wasm.rs b/src/wasm.rs index 15262e2..747547d 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -366,8 +366,8 @@ 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 - /// `minFrequencyHz` and `maxFrequencyHz` of the pitch configuration. + /// - The estimated period is outside the active `vocalRange` preset or the + /// custom `minFrequencyHz` and `maxFrequencyHz` bounds. /// /// # Errors /// From 1055bc20760cd359696e4bc97215dd64537524b9 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 16:03:18 +0000 Subject: [PATCH 2/2] fix(pitch): make vocalRange optional in Wasm and non-exhaustive - Mark VocalRange as #[non_exhaustive] in src/pitch.rs - Make PitchConfig::vocal_range optional in Wasm and TypeScript - Map an absent or undefined vocalRange value to VocalRange::Custom - Document optional resynthesis.pitch.vocalRange in src/wasm.rs - Document optional resynthesis.pitch.vocalRange in README.md --- README.md | 9 +++++---- src/pitch.rs | 20 +++++++++++++++++++- src/wasm.rs | 1 + 3 files changed, 25 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 1c0ac59..3b76387 100644 --- a/README.md +++ b/README.md @@ -472,10 +472,11 @@ and show enums as string literals. To change the configuration, do these steps: 3. Call `setConfig()`. If a required field is absent or a value is not valid, the call throws a -JavaScript `Error`. The optional `resynthesis.harmony.voices` field defaults -to 4 if it is absent or `undefined`. The conversion ignores extra object -properties. The generated declarations contain the parameter documentation from -the Rust types. +JavaScript `Error`. The optional `resynthesis.pitch.vocalRange` field defaults +to `"custom"` if it is absent or `undefined`. The optional +`resynthesis.harmony.voices` field defaults to 4 if it is absent or +`undefined`. The conversion ignores extra object properties. The generated +declarations contain the parameter documentation from the Rust types. `resynthesis.randomSeed` and the `processedFrames` field of feedback and telemetry use `bigint`. Frame offsets, block lengths and latency use diff --git a/src/pitch.rs b/src/pitch.rs index 57cf3e3..d25fa86 100644 --- a/src/pitch.rs +++ b/src/pitch.rs @@ -19,6 +19,7 @@ use crate::{Error, SampleRate}; /// `max_frequency_hz` from [`PitchConfig`]. Each other variant sets fixed /// inclusive bounds for pitch acquisition, tracking and feedback reports. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), derive(serde::Serialize, serde::Deserialize, tsify::Tsify), @@ -51,7 +52,14 @@ pub struct PitchConfig { /// /// The default is [`VocalRange::Custom`]. If you select a named preset, /// its frequency bounds override `min_frequency_hz` and `max_frequency_hz` - /// for detection and reports. Validation still checks those two fields. + /// for detection and reports. Validation still checks those two fields. In + /// JavaScript, the field is optional and an absent or `undefined` value + /// gives the default. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(default, deserialize_with = "deserialize_vocal_range"), + tsify(optional, type = "VocalRange | undefined") + )] pub vocal_range: VocalRange, /// The normalized cycle-difference threshold for acquisition, 0.002..=0.2. /// @@ -77,6 +85,16 @@ pub struct PitchConfig { pub max_frequency_hz: f32, } +/// Decodes an optional vocal range and maps an absent value to +/// [`VocalRange::Custom`]. +#[cfg(all(feature = "wasm", target_arch = "wasm32"))] +fn deserialize_vocal_range<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result { + use serde::Deserialize; + Ok(Option::::deserialize(deserializer)?.unwrap_or_default()) +} + impl Default for PitchConfig { fn default() -> Self { Self { diff --git a/src/wasm.rs b/src/wasm.rs index cb0f19c..cf0ec6c 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -19,6 +19,7 @@ //! - Field names use camelCase. //! - Enum values are strings. //! - Each object must contain all required fields. +//! - The optional `resynthesis.pitch.vocalRange` field defaults to `"custom"`. //! - The optional harmony `voices` field defaults to 4. //! //! [`default_config`] gives a configuration to start from. Control events use