From d2f7d11395fd807740bbd93bb5b2b00a40b8ac4e Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Sat, 21 Nov 2026 01:51:44 +0000 Subject: [PATCH] feat(resynthesis): split vibrato from the mean pitch contour - Add vibrato_preserve to CorrectionConfig with a default of zero. - Validate vibrato_preserve in 0..=1 before state changes. - Accept an absent vibratoPreserve field in JavaScript. - Add a Q24 period filter at the five-frame update cadence. - Select correction targets from the secular Q6 period. - Apply the vibrato modulation ratio to the smoothed secular ratio. - Seed the period filter at acquisition. - Clear the period filter on a restart and on an audio reset. - Skip the period filter at zero to keep exact v0.2.0 output. - Document vibrato_preserve in rustdoc, wasm and the README. --- README.md | 14 ++- src/resynthesis.rs | 141 +++++++++++++++++++++++---- src/resynthesis/vibrato.rs | 189 +++++++++++++++++++++++++++++++++++++ src/wasm.rs | 1 + 4 files changed, 323 insertions(+), 22 deletions(-) create mode 100644 src/resynthesis/vibrato.rs diff --git a/README.md b/README.md index d2993dc..a195723 100644 --- a/README.md +++ b/README.md @@ -174,6 +174,11 @@ voice. It disables the effects and the formant stage. `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.correction.vibrato_preserve` sets the fraction of 4..=8 Hz +vibrato that bypasses correction, in `0..=1`. The default is 0. At 1, +correction moves the mean pitch to the target note and keeps natural +vibrato, also at zero retune time. + ### Harmony sources Set `resynthesis.mode` to `Harmony`. Then select the source of the voices @@ -444,10 +449,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. The conversion ignores extra object properties. The -generated declarations contain the parameter documentation from the Rust -types. +JavaScript `Error`. If an optional field is absent, it gets its default: +`resynthesis.correction.vibratoPreserve` defaults to 0, and +`resynthesis.harmony.voices` defaults to 4. 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/resynthesis.rs b/src/resynthesis.rs index 34e98fa..a856c93 100644 --- a/src/resynthesis.rs +++ b/src/resynthesis.rs @@ -28,6 +28,7 @@ //! - The order of the wrapping arithmetic. mod history; +mod vibrato; use crate::error::{check_count, check_range}; use crate::filter::{Biquad, Design}; @@ -41,6 +42,7 @@ use crate::pitch::{PitchConfig, PitchEstimate}; use crate::scale::{CorrectionTable, NoteMask}; use crate::{Error, SampleRate}; use history::prepare_history; +use vibrato::PeriodFilter; /// The method that resynthesis uses to render its voices. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -106,6 +108,18 @@ pub struct CorrectionConfig { /// tracking update. A value that is not zero is a half-life. It is not a /// fixed time to get exactly to the target. pub retune_ms: f32, + /// The fraction of 4..=8 Hz vibrato that bypasses correction, 0..=1. + /// + /// The default is 0, which applies full correction to the vibrato. A + /// value of 1 keeps the 4..=8 Hz vibrato while the mean pitch moves to + /// the active target note. In JavaScript, the field is optional and an + /// absent value gives the default. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(default), + tsify(optional) + )] + pub vibrato_preserve: f32, } impl Default for CorrectionConfig { @@ -114,6 +128,7 @@ impl Default for CorrectionConfig { enabled: true, notes: NoteMask::default(), retune_ms: 0.0, + vibrato_preserve: 0.0, } } } @@ -121,20 +136,27 @@ impl Default for CorrectionConfig { impl CorrectionConfig { /// Validates all fields, also if correction is disabled. /// - /// All values of `enabled` and `notes` are valid. `retune_ms` must be - /// finite and in its documented inclusive range. Validation does not - /// clamp values. It does not change the state of the processor. + /// All values of `enabled` and `notes` are valid. `retune_ms` and + /// `vibrato_preserve` must be finite and in their documented inclusive + /// ranges. Validation does not clamp values. It does not change the state + /// of the processor. /// /// # Errors /// /// Returns [`Error::InvalidConfig`], with the dotted path of the field and - /// the problem, if `retune_ms` is not valid. + /// the problem, if a field is not valid. pub fn validate(self) -> Result<(), Error> { check_range( "resynthesis.correction.retune_ms", self.retune_ms, 0.0, 400.0, + )?; + check_range( + "resynthesis.correction.vibrato_preserve", + self.vibrato_preserve, + 0.0, + 1.0, ) } } @@ -440,6 +462,17 @@ pub(crate) struct Resynthesis { /// The current smoothed Q14 correction ratio. It does not include the /// global shift or the voice ratios. correction: Q14, + /// The smoothed Q24 ratio of the secular pitch contour when vibrato + /// preservation is active. + secular_correction: i64, + /// The smoothed Q24 modulation ratio when vibrato preservation is active. + vibrato_ratio: i64, + /// If `true`, `vibrato_preserve` is nonzero and the contour filter runs. + vibrato_enabled: bool, + /// The Q24 vibrato preservation weight. + vibrato_preserve: i64, + /// The Q24 contour filter that separates secular periods from vibrato. + period_filter: PeriodFilter, /// The Q14 half-life coefficient for correction updates. These updates /// usually occur every five frames. correction_decay: Q14, @@ -533,6 +566,11 @@ impl Resynthesis { formant_position: 0, post: [Biquad::new(), Biquad::new()], correction: Q14::ONE, + secular_correction: 1 << 24, + vibrato_ratio: 1 << 24, + vibrato_enabled: false, + vibrato_preserve: 0, + period_filter: PeriodFilter::new(rate), correction_decay: Q14::ZERO, scale_initialized: false, scale_index: 0, @@ -572,6 +610,24 @@ impl Resynthesis { let t = self.config.correction.retune_ms / 1000.0; Q14::from_f64(0.5_f64.powf(1.0 / ((self.rate.hz() / 5.0) * t) as f64)) }; + let was_vibrato_enabled = self.vibrato_enabled; + self.period_filter.configure(self.rate); + if self.config.correction.vibrato_preserve == 0.0 { + self.vibrato_enabled = false; + self.vibrato_preserve = 0; + if was_vibrato_enabled { + self.period_filter.reset(); + self.vibrato_ratio = 1 << 24; + } + } else { + self.vibrato_enabled = true; + self.vibrato_preserve = + vibrato::quantize_preserve(self.config.correction.vibrato_preserve); + if !was_vibrato_enabled { + self.secular_correction = i64::from(self.correction.to_bits()) << 10; + self.vibrato_ratio = 1 << 24; + } + } let base = (self.rate.hz() / 100.0) as f64 * 0.2; let decay = (-std::f64::consts::LN_2 / base).exp(); self.drift_decay = Q14::from_f64(decay); @@ -715,7 +771,10 @@ impl Resynthesis { self.voice_ratios.fill(Q14::ONE); self.formant_position = 0; self.current_output_period = Q6::ZERO; + self.period_filter.reset(); self.correction = Q14::ONE; + self.secular_correction = 1 << 24; + self.vibrato_ratio = 1 << 24; self.scale_initialized = false; } @@ -853,18 +912,13 @@ impl Resynthesis { self.formant .envelope(self.formant_position, max_frequency_hz, input, output) } - /// Selects a target in the period domain and smooths the Q14 correction - /// ratio. - /// - /// The Q6 input period must be a usable tracking result. The target - /// search moves through the midpoints, also across octave limits. The - /// global shift is part of the normalization. + /// Selects a target in the period domain and returns the Q14 target ratio. /// - /// If correction is disabled or the active table is empty, the ratio moves - /// toward 1.0. If the target selection starts again and the shifted - /// period is not positive, the ratio becomes 1.0 immediately. A - /// multiplication by fixed-point 1.0 still wraps. Do not remove it. - fn update_correction(&mut self, period: Q6) { + /// Returns `None` if target selection starts again and the shifted period + /// is not positive. If correction is disabled or the active table is + /// empty, returns `Some(Q14::ONE)`. A multiplication by fixed-point 1.0 + /// still wraps. Do not remove it. + fn select_target_ratio(&mut self, period: Q6) -> Option { let mut target_ratio = Q14::ONE; if self.config.correction.enabled && self.scale.count != 0 { let count = self.scale.count; @@ -878,8 +932,7 @@ impl Resynthesis { self.octave = 0; target = self.shift.mul(period); if target <= Q6::ZERO { - self.correction = Q14::ONE; - return; + return None; } while table_period(1) > target { self.octave += 1; @@ -917,7 +970,47 @@ impl Resynthesis { target_ratio = target.div(denominator); } } - self.correction = self.correction_decay.mul(self.correction - target_ratio) + target_ratio; + Some(target_ratio) + } + + /// Selects a target in the period domain and smooths the Q14 correction + /// ratio. + /// + /// When `vibrato_preserve` is zero, this method skips the contour filter + /// and the modulation product to keep the Q14 wrap order unchanged. When + /// `vibrato_preserve` is nonzero, the contour filter supplies a secular + /// period for target selection and a modulation ratio for vibrato. + fn update_correction(&mut self, period: Q6) { + if !self.vibrato_enabled { + let Some(target_ratio) = self.select_target_ratio(period) else { + self.correction = Q14::ONE; + return; + }; + self.correction = + self.correction_decay.mul(self.correction - target_ratio) + target_ratio; + return; + } + let (secular_period, mod_ratio) = self.period_filter.split(period, self.vibrato_preserve); + let Some(target_ratio) = self.select_target_ratio(secular_period) else { + self.secular_correction = 1 << 24; + self.vibrato_ratio = 1 << 24; + self.correction = Q14::ONE; + return; + }; + let target_mod = if self.config.correction.enabled && self.scale.count != 0 { + mod_ratio + } else { + Q14::ONE + }; + let decay = i64::from(self.correction_decay.to_bits()); + let target_q24 = i64::from(target_ratio.to_bits()) << 10; + self.secular_correction = + target_q24 + ((self.secular_correction - target_q24) * decay) / 16_384; + let mod_q24 = i64::from(target_mod.to_bits()) << 10; + self.vibrato_ratio = mod_q24 + ((self.vibrato_ratio - mod_q24) * decay) / 16_384; + let secular_q14 = Q14::from_bits(((self.secular_correction + 512) >> 10) as i32); + let mod_q14 = Q14::from_bits(((self.vibrato_ratio + 512) >> 10) as i32); + self.correction = secular_q14.mul(mod_q14); } /// Selects the period and the correction. @@ -1064,10 +1157,22 @@ impl Resynthesis { self.old_position = self.old_position - position_of(HISTORY as i32); } if step.restarted { + if self.vibrato_enabled { + self.period_filter.reset(); + self.secular_correction = 1 << 24; + self.vibrato_ratio = 1 << 24; + } self.correction = Q14::ONE; self.scale_initialized = false; } if step.acquired { + if self.vibrato_enabled { + if step.period > Q6::ZERO { + self.period_filter.seed(step.period); + } else { + self.period_filter.reset(); + } + } self.formant.detection_mode_off(); } if step.tracking_update { diff --git a/src/resynthesis/vibrato.rs b/src/resynthesis/vibrato.rs new file mode 100644 index 0000000..37f3816 --- /dev/null +++ b/src/resynthesis/vibrato.rs @@ -0,0 +1,189 @@ +//! The Q24 period filter that separates the mean pitch contour from vibrato. +//! +//! The pitch tracker updates the period once every five audio frames. At 44.1 +//! kHz and 48 kHz, a Q14 biquad with a 3 Hz cutoff loses its numerator bits. +//! Thus, this filter uses Q24 coefficients and Q24 state words. + +use crate::numeric::fixed::{Q14, Q6}; +use crate::SampleRate; + +/// The number of fractional bits in Q24. +const Q24_SHIFT: u32 = 24; +/// The left shift from a Q6 period word to a Q24 period word. +const Q6_TO_Q24_SHIFT: u32 = 18; +/// The geometric center of the 4..=8 Hz vibrato band, in hertz. +const BAND_CENTER_HZ: f64 = 5.656_854_249_492_381; +/// The -3 dB width of the vibrato band-pass section, in hertz. +const BAND_WIDTH_HZ: f64 = 8.2; +/// The one-pole cutoff after the vibrato notch, in hertz. +/// +/// The combined secular -3 dB cutoff is below 3 Hz, and the group delay is +/// below 80 ms at both sample rates. +const SECULAR_LP_HZ: f64 = 4.4; +/// The lowest Q14 modulation ratio (0.25). +const MIN_MOD_RATIO_BITS: i128 = 4_096; +/// The highest Q14 modulation ratio (4.0). +const MAX_MOD_RATIO_BITS: i128 = 65_536; + +/// Scales a finite control in 0..=1 to a Q24 word. +pub(super) fn quantize_preserve(value: f32) -> i64 { + PeriodFilter::quantize_q24(f64::from(value)) +} + +/// A Q24 contour filter that runs at the five-frame period cadence. +/// +/// A second-order band-pass section extracts the 4..=8 Hz vibrato residual. A +/// first-order low-pass section filters the difference to get the secular +/// period below 3 Hz. Error feedback keeps the sub-unit remainders, so a step +/// converges to the exact input period. +pub(super) struct PeriodFilter { + /// The Q24 feed-forward gain of the band-pass section. + bp_b0: i64, + /// The first Q24 feedback coefficient of the band-pass section. + bp_a1: i64, + /// The second Q24 feedback coefficient of the band-pass section. + bp_a2: i64, + /// The Q24 step coefficient of the secular one-pole low-pass section. + lp_alpha: i64, + /// If `true`, the state holds a valid initial period. + seeded: bool, + /// The two previous Q24 input periods for the band-pass section. + bp_x: [i64; 2], + /// The two previous Q24 outputs of the band-pass section. + bp_y: [i64; 2], + /// The sub-unit remainder of the band-pass sum. + bp_rem: i64, + /// The current Q24 secular period estimate. + lp_y: i64, + /// The sub-unit remainder of the low-pass product. + lp_rem: i64, +} + +impl PeriodFilter { + /// Scales a finite value to Q24 with a half-unit adjustment. + fn quantize_q24(value: f64) -> i64 { + let scaled = value * f64::from(1_u32 << Q24_SHIFT); + if scaled >= 0.0 { + (scaled + 0.5) as i64 + } else { + (scaled - 0.5) as i64 + } + } + + /// Creates a cleared filter with coefficients for `rate`. + pub(super) fn new(rate: SampleRate) -> Self { + let mut filter = Self { + bp_b0: 0, + bp_a1: 0, + bp_a2: 0, + lp_alpha: 0, + seeded: false, + bp_x: [0; 2], + bp_y: [0; 2], + bp_rem: 0, + lp_y: 0, + lp_rem: 0, + }; + filter.configure(rate); + filter + } + + /// Calculates the Q24 coefficients for the five-frame update rate. + /// + /// The filter state does not change. + pub(super) fn configure(&mut self, rate: SampleRate) { + let update_hz = f64::from(rate.as_u32()) / 5.0; + let q = BAND_CENTER_HZ / BAND_WIDTH_HZ; + let w0 = 2.0 * std::f64::consts::PI * BAND_CENTER_HZ / update_hz; + let sin = w0.sin(); + let cos = w0.cos(); + let alpha = sin / (2.0 * q); + let a0 = 1.0 + alpha; + self.bp_b0 = Self::quantize_q24(alpha / a0); + self.bp_a1 = Self::quantize_q24((-2.0 * cos) / a0); + self.bp_a2 = Self::quantize_q24((1.0 - alpha) / a0); + let w_lp = 2.0 * std::f64::consts::PI * SECULAR_LP_HZ / update_hz; + self.lp_alpha = Self::quantize_q24(1.0 - (-w_lp).exp()); + } + + /// Clears the filter histories and marks the filter as not seeded. + /// + /// The coefficients do not change. + pub(super) fn reset(&mut self) { + self.seeded = false; + self.bp_x = [0; 2]; + self.bp_y = [0; 2]; + self.bp_rem = 0; + self.lp_y = 0; + self.lp_rem = 0; + } + + /// Sets the secular state to `period` and clears the vibrato residual. + pub(super) fn seed(&mut self, period: Q6) { + let p_q24 = i64::from(period.to_bits()) << Q6_TO_Q24_SHIFT; + self.bp_x = [p_q24; 2]; + self.bp_y = [0; 2]; + self.bp_rem = 0; + self.lp_y = p_q24; + self.lp_rem = 0; + self.seeded = true; + } + + /// Splits `period` into a secular Q6 period and a Q14 modulation ratio. + /// + /// If the filter is not seeded yet, this call seeds the state to `period` + /// and returns unity modulation. All calculations use integer arithmetic. + pub(super) fn split(&mut self, period: Q6, preserve_q24: i64) -> (Q6, Q14) { + if period <= Q6::ZERO { + return (period, Q14::ONE); + } + if !self.seeded { + self.seed(period); + return (period, Q14::ONE); + } + let x = i64::from(period.to_bits()) << Q6_TO_Q24_SHIFT; + let acc = i128::from(self.bp_b0) * i128::from(x.wrapping_sub(self.bp_x[1])) + - i128::from(self.bp_a1) * i128::from(self.bp_y[0]) + - i128::from(self.bp_a2) * i128::from(self.bp_y[1]) + + i128::from(self.bp_rem); + let vib = (acc >> Q24_SHIFT) as i64; + self.bp_rem = (acc - (i128::from(vib) << Q24_SHIFT)) as i64; + self.bp_x[1] = self.bp_x[0]; + self.bp_x[0] = x; + self.bp_y[1] = self.bp_y[0]; + self.bp_y[0] = vib; + + let notched = x.wrapping_sub(vib); + let lp_acc = i128::from(self.lp_alpha) * i128::from(notched.wrapping_sub(self.lp_y)) + + i128::from(self.lp_rem); + let lp_step = (lp_acc >> Q24_SHIFT) as i64; + self.lp_rem = (lp_acc - (i128::from(lp_step) << Q24_SHIFT)) as i64; + self.lp_y = self.lp_y.wrapping_add(lp_step); + + let half_q6 = 1_i64 << (Q6_TO_Q24_SHIFT - 1); + let secular_bits = if self.lp_y >= 0 { + self.lp_y.saturating_add(half_q6) >> Q6_TO_Q24_SHIFT + } else { + self.lp_y.saturating_sub(half_q6) >> Q6_TO_Q24_SHIFT + }; + let secular_q6 = Q6::from_bits(secular_bits.clamp(1, i64::from(i32::MAX)) as i32); + + let half_q24 = 1_i128 << (Q24_SHIFT - 1); + let vib_prod = i128::from(vib) * i128::from(preserve_q24); + let preserved = if vib_prod >= 0 { + ((vib_prod + half_q24) >> Q24_SHIFT) as i64 + } else { + ((vib_prod - half_q24) >> Q24_SHIFT) as i64 + }; + let min_denom = (x >> 2).max(1); + let max_denom = x.saturating_mul(4); + let denom = i128::from( + self.lp_y + .saturating_add(preserved) + .clamp(min_denom, max_denom), + ); + let ratio_bits = (((i128::from(x) << 14) + (denom >> 1)) / denom) + .clamp(MIN_MOD_RATIO_BITS, MAX_MOD_RATIO_BITS) as i32; + (secular_q6, Q14::from_bits(ratio_bits)) + } +} diff --git a/src/wasm.rs b/src/wasm.rs index c9cec08..9655519 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 `correction.vibratoPreserve` field defaults to 0. //! - The optional harmony `voices` field defaults to 4. //! //! [`default_config`] gives a configuration to start from. Control events use