From e36c2d88611205bb168a0f50f56f780724c37e6d 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:37:18 +0000 Subject: [PATCH] perf: guard unchanged stage controls and mute drain aspiration - Add an aspiration mute flag on Formant for tail drains. - Mute formant aspiration in Processor::drain_into directly. - Initialize all stage tables and filters at construction. - Guard sub-stage setters and coefficients in Resynthesis. - Guard width, stretch and aspiration updates in Formant. - Guard envelope decays and gains in Punch::set_config. - Guard mix, diffusion, decay and brightness in Reverb. - Preserve exact fixed-point audio, feedback and telemetry. --- src/effects/punch.rs | 71 ++++++++++++++++++++++--------- src/effects/reverb.rs | 43 ++++++++++++++++--- src/formant.rs | 73 +++++++++++++++++++++++++------- src/processor.rs | 18 +++----- src/resynthesis.rs | 98 ++++++++++++++++++++++++++++++++++++------- 5 files changed, 235 insertions(+), 68 deletions(-) diff --git a/src/effects/punch.rs b/src/effects/punch.rs index 867dc09..6a35c42 100644 --- a/src/effects/punch.rs +++ b/src/effects/punch.rs @@ -91,6 +91,8 @@ impl PunchConfig { pub(crate) struct Punch { /// The prepared rate, which converts the envelope times to sample windows. rate: SampleRate, + /// The validated controls for this stage. + config: PunchConfig, /// The adaptive Q14 peak envelope. The impact control sets its release. slow: Q14, /// The second Q14 peak envelope, with a fixed release half-life of 5 @@ -119,18 +121,22 @@ impl Punch { pub(crate) fn new(rate: SampleRate, config: PunchConfig) -> Self { let mut result = Self { rate, + config, slow: Q14::default(), fast: Q14::default(), counter: 0, peak: Q14::default(), slow_decay: Q14::default(), - fast_decay: Q14::default(), + fast_decay: Self::decay(rate, 5000.0), attack_decay: Q14::default(), gain: Q8::ONE, ceiling_gain: Q14::default(), drive: BASE_DRIVE, }; - result.set_config(config); + result.prepare_impact(); + result.prepare_attack(); + result.prepare_gain(); + result.prepare_ceiling(); result.reset(); result } @@ -141,24 +147,51 @@ impl Punch { pub(crate) fn drive_ratio(&self) -> f32 { (self.drive.to_bits() as f64 / BASE_DRIVE.to_bits() as f64) as f32 } - /// Calculates the quantized controls again, and keeps the envelopes and - /// the cached drive. - /// The processor controls the bypass. This stage never reads an enabled - /// flag. + /// Calculates the quantized controls that changed, and keeps the envelopes + /// and the cached drive. + /// The processor controls the bypass. The audio path of this stage does + /// not read `enabled`. pub(crate) fn set_config(&mut self, config: PunchConfig) { - let impact = coefficient_to_exp_value(1.0, 250.0, 5000.0, 1.0 - config.impact); - let decay = |milliseconds: f64| { - Q14::from_f64(envelope_decay( - milliseconds, - self.rate.hz() as f64, - WINDOW_FRAMES, - )) - }; - self.slow_decay = decay(impact as f64); - self.fast_decay = decay(5000.0); - self.attack_decay = decay(config.attack_ms as f64); - self.gain = Q8::from_f64(db_to_gain(config.gain_db as f64)); - self.ceiling_gain = Q14::from_f64(db_to_gain(config.ceiling_db as f64)); + let old = self.config; + self.config = config; + if old.impact != config.impact { + self.prepare_impact(); + } + if old.attack_ms != config.attack_ms { + self.prepare_attack(); + } + if old.gain_db != config.gain_db { + self.prepare_gain(); + } + if old.ceiling_db != config.ceiling_db { + self.prepare_ceiling(); + } + } + /// Converts a half-life in milliseconds to a Q14 coefficient for the + /// 100-frame window. + fn decay(rate: SampleRate, milliseconds: f64) -> Q14 { + Q14::from_f64(envelope_decay( + milliseconds, + rate.hz() as f64, + WINDOW_FRAMES, + )) + } + /// Calculates the release coefficient of the adaptive follower. + fn prepare_impact(&mut self) { + let impact = coefficient_to_exp_value(1.0, 250.0, 5000.0, 1.0 - self.config.impact); + self.slow_decay = Self::decay(self.rate, impact as f64); + } + /// Calculates the shared attack coefficient of the two followers. + fn prepare_attack(&mut self) { + self.attack_decay = Self::decay(self.rate, self.config.attack_ms as f64); + } + /// Quantizes the linear input gain to Q8. + fn prepare_gain(&mut self) { + self.gain = Q8::from_f64(db_to_gain(self.config.gain_db as f64)); + } + /// Quantizes the linear output ceiling to Q14. + fn prepare_ceiling(&mut self) { + self.ceiling_gain = Q14::from_f64(db_to_gain(self.config.ceiling_db as f64)); } /// Clears both envelopes and the current window, then calculates the drive /// again from the base drive and the input gain. diff --git a/src/effects/reverb.rs b/src/effects/reverb.rs index fe60cd4..bf06a49 100644 --- a/src/effects/reverb.rs +++ b/src/effects/reverb.rs @@ -185,19 +185,50 @@ impl Reverb { scratch: layout.capacity - 1, wet_peak: 0, }; - result.set_config(config); + result.prepare_mix(); + result.prepare_diffusion(); + result.prepare_decay(); + result.prepare_brightness(); result } - /// Updates the coefficients and does not clear the delay or filter state. + /// Updates the coefficients that changed and does not clear the delay or + /// filter state. /// The f32 multiplication by 100 occurs before the f64 division and the /// quantization. If you combine these expressions, the quantized /// coefficients can change. pub(crate) fn set_config(&mut self, config: ReverbConfig) { + let old = self.config; self.config = config; - self.mix = Q14::from_f64((config.mix * 100.0) as f64 / 100.0); - self.diffuse = Q14::from_f64((config.diffusion * 100.0) as f64 / 100.0); - self.decay = Q14::from_f64((config.decay * 100.0) as f64 / 105.0); - let brightness = config + if old.mix != config.mix { + self.prepare_mix(); + } + if old.diffusion != config.diffusion { + self.prepare_diffusion(); + } + if old.decay != config.decay { + self.prepare_decay(); + } + if old.brightness_hz != config.brightness_hz { + self.prepare_brightness(); + } + } + /// Quantizes the wet fraction to Q14. + fn prepare_mix(&mut self) { + self.mix = Q14::from_f64((self.config.mix * 100.0) as f64 / 100.0); + } + /// Quantizes the diffusion control to Q14. + fn prepare_diffusion(&mut self) { + self.diffuse = Q14::from_f64((self.config.diffusion * 100.0) as f64 / 100.0); + } + /// Quantizes the feedback coefficient to Q14. + fn prepare_decay(&mut self) { + self.decay = Q14::from_f64((self.config.decay * 100.0) as f64 / 105.0); + } + /// Updates the coefficients of the two low-pass filters and keeps their + /// histories. + fn prepare_brightness(&mut self) { + let brightness = self + .config .brightness_hz .min((self.rate.hz() as f64 * 0.49) as f32); let design = Design::low_pass_one_pole(self.rate.hz(), brightness); diff --git a/src/formant.rs b/src/formant.rs index 5072ee1..851179a 100644 --- a/src/formant.rs +++ b/src/formant.rs @@ -230,6 +230,9 @@ pub(crate) struct Formant { /// The Q14 compensation, from the aspiration cutoff divided by the /// sample rate. noise_amplitude: i32, + /// If `true`, `add_noise` returns the input and does not advance the + /// random stream or the aspiration filter. + aspiration_muted: bool, /// The wrapping count of model designs that the stage tried. Only the /// telemetry reads it. generation: u32, @@ -276,32 +279,70 @@ impl Formant { noise_filter: Biquad::new(), noise_gain: 0_i32, noise_amplitude: 0_i32, + aspiration_muted: false, generation: 0, }; - result.set_config(config); + result.prepare_width(); + result.prepare_stretch(); + result.prepare_aspiration_mix(); + result.prepare_aspiration_cutoff(); result.reset(); 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 that changed, updates the Q7 area map + /// and updates the aspiration filter. /// - /// 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 histories do not change. pub(crate) fn set_config(&mut self, config: FormantConfig) { + let old = self.config; 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; - self.stretch = (config.stretch as f64 * 16384.0) as i32; + if old.width != config.width { + self.prepare_width(); + } + if old.stretch != config.stretch { + self.prepare_stretch(); + } + if old.aspiration_mix != config.aspiration_mix { + self.prepare_aspiration_mix(); + } + if old.aspiration_cutoff_hz != config.aspiration_cutoff_hz { + self.prepare_aspiration_cutoff(); + } + } + /// Mutes or restores the random aspiration and keeps the configured + /// controls. + pub(crate) fn set_aspiration_muted(&mut self, muted: bool) { + self.aspiration_muted = muted; + } + /// Quantizes the width and its square to Q14. + fn prepare_width(&mut self) { + self.width = (self.config.width as f64 * 16384.0) as i32; + self.width_squared = (self.config.width as f64 * self.config.width as f64 * 16384.0) as i32; + } + /// Quantizes the stretch and prepares the Q7 map for the area + /// interpolation. + /// + /// 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. + fn prepare_stretch(&mut self) { + self.stretch = (self.config.stretch as f64 * 16384.0) as i32; self.stretch_count = - (((ORDER - 1) as f64 * config.stretch as f64 + 1.001) as usize).min(MAX_ORDER); + (((ORDER - 1) as f64 * self.config.stretch as f64 + 1.001) as usize).min(MAX_ORDER); for i in 0..self.stretch_count - 1 { let fraction = i as f64 / (self.stretch_count - 1) as f64; self.stretch_map[i] = ((ORDER - 1) as f64 * fraction * 128.0) as i32; } self.stretch_map[self.stretch_count - 1] = ((ORDER - 1) * 128) as i32; - self.noise_gain = (config.aspiration_mix as f64 * 16384.0) as i32; - let frequency = (config.aspiration_cutoff_hz as i32) + } + /// Quantizes the aspiration level to Q14. + fn prepare_aspiration_mix(&mut self) { + self.noise_gain = (self.config.aspiration_mix as f64 * 16384.0) as i32; + } + /// Updates the compensation and the high-pass coefficients of the + /// aspiration filter, and keeps the filter history. + fn prepare_aspiration_cutoff(&mut self) { + let frequency = (self.config.aspiration_cutoff_hz as i32) .min((self.rate.hz() as f64 * 0.48) as i32) .max(500); self.noise_amplitude = (frequency as f64 * 0.8 / self.rate.hz() as f64 * 16384.0) as i32; @@ -660,11 +701,11 @@ impl Formant { /// Blends random aspiration into a Q14 sample word. The signal modulates /// the aspiration, and a high-pass filter changes it. /// - /// If the level is 0.01 or less, the function returns immediately. The - /// random stream and the noise filter then do not advance. If not, the - /// function reads one random value. + /// If aspiration is muted or the level is 0.01 or less, the function + /// returns immediately. The random stream and the noise filter then do not + /// advance. If not, the function reads one random value. fn add_noise(&mut self, sample: i32, context: &mut NumericContext) -> i32 { - if self.config.aspiration_mix <= 0.01 { + if self.aspiration_muted || self.config.aspiration_mix <= 0.01 { return sample; } let random = context.random.next_u31() >> 17; diff --git a/src/processor.rs b/src/processor.rs index cc910f4..80401ec 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -662,9 +662,9 @@ impl Processor { /// unused frames. /// /// The method mutes aspiration temporarily, but does not change the - /// settings that the host sees. It restores the configuration before - /// completion resets the state. `Some(0)` records completion, so later - /// drain calls continue to return zero. + /// settings that the host sees. It restores aspiration before completion + /// resets the state. `Some(0)` records completion, so later drain calls + /// continue to return zero. fn drain_into( &mut self, frames: usize, @@ -672,19 +672,11 @@ impl Processor { ) -> Result { self.check_block(frames)?; let count = self.drain_remaining.unwrap_or(0).min(frames); - let configured = self.config.resynthesis; - if configured.formant.aspiration_mix != 0.0 { - let mut silent = configured; - silent.formant.aspiration_mix = 0.0; - // Zero aspiration is valid in all validated configurations. - self.resynthesis.apply_config(silent); - } + self.resynthesis.set_aspiration_muted(true); for index in 0..count { write(index, self.next(0)); } - if configured.formant.aspiration_mix != 0.0 { - self.resynthesis.apply_config(configured); - } + self.resynthesis.set_aspiration_muted(false); if let Some(remaining) = self.drain_remaining { let remaining = remaining - count; if remaining == 0 { diff --git a/src/resynthesis.rs b/src/resynthesis.rs index 34e98fa..5846807 100644 --- a/src/resynthesis.rs +++ b/src/resynthesis.rs @@ -352,6 +352,12 @@ fn position_of(frame: i32) -> Q14 { Q14::from_bits(frame.wrapping_shl(14)) } +/// Returns the decay factor for the random choir drift at `rate`. +fn drift_decay_factor(rate: SampleRate) -> f64 { + let base = (rate.hz() / 100.0) as f64 * 0.2; + (-std::f64::consts::LN_2 / base).exp() +} + /// The resynthesis stage. /// /// The units are as follows: @@ -545,7 +551,7 @@ impl Resynthesis { fade: Q14::ONE, current_output_period: Q6::ZERO, control_counter: CONTROL_DUE, - drift_decay: Q14::ZERO, + drift_decay: Q14::from_f64(drift_decay_factor(rate)), drift_amount: Q14::ZERO, previous_output: [Q14::ZERO; 2], }; @@ -555,27 +561,53 @@ impl Resynthesis { result } - /// Quantizes the controls and calculates the decay coefficients and the - /// voice pan gains again. + /// Quantizes all scalar controls and prepares the decay coefficients and + /// the voice pan gains. /// - /// The coefficients are the correction decay, the drift decay and the - /// drift amount. The histories and the controller phase do not change. - /// The harmony level is part of the stereo pan gains. Thus, the path - /// without pan never applies that control. + /// The histories and the controller phase do not change. fn configure_coefficients(&mut self) { + self.configure_pitch_ratio(); + self.configure_modulation(); + self.configure_dry_mix(); + self.configure_retune(); + self.configure_choir_detune(); + self.configure_choir_pan(); + self.configure_harmony_pan(); + } + + /// Quantizes the global pitch multiplier to Q14. + fn configure_pitch_ratio(&mut self) { self.shift = Q14::from_f64(self.config.pitch_ratio as f64); + } + + /// Quantizes the harmonic modulation depth. + fn configure_modulation(&mut self) { self.modulation = (self.config.harmonic_modulation as f64 / 8.0 * 16.0) as i32; + } + + /// Quantizes the dry mix fraction to Q8. + fn configure_dry_mix(&mut self) { self.dry_mix = Q8::from_f64((self.config.dry_mix * 100.0) as f64 / 100.0); + } + + /// Calculates the Q14 half-life coefficient for correction updates. + fn configure_retune(&mut self) { self.correction_decay = if self.config.correction.retune_ms == 0.0 { Q14::ZERO } else { 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 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); + } + + /// Calculates the Q14 step weight for the random choir drift. + fn configure_choir_detune(&mut self) { + let decay = drift_decay_factor(self.rate); self.drift_amount = Q14::from_f64((1.0 - decay) * 0.008 * self.config.choir_detune as f64); + } + + /// Calculates the Q14 stereo pan gains for the active choir voices. + fn configure_choir_pan(&mut self) { for voice in 0..self.config.choir_voices as usize { if self.config.choir_voices > 1 { let normalized = @@ -588,6 +620,13 @@ impl Resynthesis { self.pan[voice] = [Q14::ONE; 2]; } } + } + + /// Calculates the Q14 stereo pan gains for the four harmony voices. + /// + /// The harmony level is part of the stereo pan gains. Thus, the path + /// without pan never applies that control. + fn configure_harmony_pan(&mut self) { for (voice, fraction) in [0.3333333333333333, 0.6666666666666666, 0.0, 1.0] .into_iter() .enumerate() @@ -641,16 +680,26 @@ impl Resynthesis { pub(crate) fn apply_config(&mut self, config: ResynthesisConfig) { let old = self.config; self.config = config; - self.pitch.set_config(config.pitch); - self.formant.set_config(config.formant); - self.harmony.apply_config(config.harmony); + if old.pitch != config.pitch { + self.pitch.set_config(config.pitch); + } + if old.formant != config.formant { + self.formant.set_config(config.formant); + } + if old.harmony != config.harmony { + self.harmony.apply_config(config.harmony); + } if old.correction.notes != config.correction.notes || old.correction.enabled != config.correction.enabled { self.scale.set_notes(config.correction.notes); self.scale_initialized = false; } + if old.correction.retune_ms != config.correction.retune_ms { + self.configure_retune(); + } if old.pitch_ratio != config.pitch_ratio { + self.configure_pitch_ratio(); self.configure_shift_filters(); } if old.mode != config.mode || old.choir_delay != config.choir_delay { @@ -661,7 +710,23 @@ impl Resynthesis { self.positions[voice] = self.positions[0]; } } - self.configure_coefficients(); + if old.choir_detune != config.choir_detune { + self.configure_choir_detune(); + } + if old.choir_voices != config.choir_voices + || old.choir_spread_percent != config.choir_spread_percent + { + self.configure_choir_pan(); + } + if old.harmony_gain != config.harmony_gain { + self.configure_harmony_pan(); + } + if old.harmonic_modulation != config.harmonic_modulation { + self.configure_modulation(); + } + if old.dry_mix != config.dry_mix { + self.configure_dry_mix(); + } if old.stereo_output != config.stereo_output { // A stereo change resets the audio state. The correction keyboard // keeps its held keys. @@ -669,6 +734,11 @@ impl Resynthesis { } } + /// Mutes or restores formant aspiration and keeps the configured controls. + pub(crate) fn set_aspiration_muted(&mut self, muted: bool) { + self.formant.set_aspiration_muted(muted); + } + /// Releases the correction keys 0..=126 and resets the audio state. /// /// The active correction table, key 127 and the items that