From 10f19037eec9bb66effdd4843d06d2a597b790e2 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 02:17:18 +0000 Subject: [PATCH 1/7] fix: crossfade voice cursors and ramp live stage changes - Crossfade period wraps and cursor jumps across all 16 voices. - Silence secondary Choir voices until fresh lead frames arrive. - Backfill the formant history when the formant stage becomes active. - Crossfade delayed raw audio with LPC output after the overlap delay. - Ramp the Q14 pan weights over 256 frames on stereo switches. - Capture a fresh Alien loop before the 200-frame wet ramp. - Ramp the Alien wet mix over 200 frames on each toggle. - Set the Alien boundary fade to zero for a one-frame loop. - Ramp the reverb wet gain over 256 frames across mode switches. - Clear the reverb delay buffer and filters between modes. - Feed zero input into the reverb until a bypass tail finishes. - Include active transition and bypass tails in tail_frames. - Update README.md for the continuous stereo_output behavior. --- README.md | 4 +- src/effects.rs | 5 +- src/effects/alien.rs | 217 +++++++++++++---- src/effects/reverb.rs | 549 ++++++++++++++++++++++++++++++++++-------- src/formant.rs | 48 +++- src/processor.rs | 67 +++--- src/resynthesis.rs | 454 +++++++++++++++++++++++++++------- 7 files changed, 1057 insertions(+), 287 deletions(-) diff --git a/README.md b/README.md index d2993dc..01da1c8 100644 --- a/README.md +++ b/README.md @@ -280,7 +280,9 @@ sets the configuration cancels the drain. `reset()` also cancels the drain. ### Reset `reset()` keeps the configuration, the random stream and some controller and -filter state. If you need a fully new state, construct a new processor. +filter state. Configuration changes keep the audio histories, also when +`resynthesis.stereo_output` changes the voice pan. If you need a fully new +state, construct a new processor. ## Feedback and telemetry diff --git a/src/effects.rs b/src/effects.rs index eefeb20..c84d24d 100644 --- a/src/effects.rs +++ b/src/effects.rs @@ -3,8 +3,9 @@ //! Punch and Warm operate on mono PCM before resynthesis. The processor does //! not call their sample methods while they are disabled. Alien and reverb //! accept stereo Q14 frames after resynthesis. They have their own bypass -//! behavior. Alien continues to record during bypass. Reverb keeps its -//! current delay state during bypass. +//! transitions. Alien captures a fresh loop when you enable it, and ramps its +//! wet mix on each toggle. Reverb lets an active tail decay with zero input +//! during bypass, then clears its histories. //! //! The configuration types validate the public controls. The prepared stage //! types assume that these checks were successful. diff --git a/src/effects/alien.rs b/src/effects/alien.rs index 5e1f509..97100c1 100644 --- a/src/effects/alien.rs +++ b/src/effects/alien.rs @@ -1,4 +1,4 @@ -//! Reverse-loop playback with a continuous input history and boundary fades. +//! Reverse-loop playback with a captured input history and boundary fades. use crate::error::check_count; use crate::numeric::fixed::{Fixed, Q14}; @@ -6,16 +6,28 @@ use crate::Error; /// The number of history frames that the loop reads from. const HISTORY_FRAMES: usize = 192_000; -/// The number of frames for the boundary fade at each loop boundary. +/// The maximum number of frames for the boundary fade and the wet ramp. const FADE_FRAMES: usize = 200; +/// Returns the boundary fade length for a validated loop length. +#[inline] +fn boundary_fade_frames(loop_frames: usize) -> usize { + if loop_frames == 1 { + 0 + } else { + FADE_FRAMES.min(loop_frames / 2) + } +} + /// Reverse playback of recent stereo audio in repeated loops with fades. /// -/// Alien comes after resynthesis. Its input history and loop phase advance -/// also when Alien is disabled. Thus, when you enable Alien, it can play -/// audio that it recorded during bypass. A change of the loop length keeps -/// the history and clamps the current phase into the new loop. The boundary -/// fades are 200 frames long at all sample rates. +/// Alien comes after resynthesis. When you enable Alien, it captures one loop +/// of fresh input while it holds the dry signal. Then it ramps the wet mix to +/// full level over 200 frames. When you disable Alien, it ramps the wet mix to +/// zero over 200 frames. A change of the loop length keeps the captured history +/// and clamps the current phase into the new loop. The boundary fade length is +/// zero at a loop length of one frame, and `min(200, loop_frames / 2)` at +/// longer loop lengths. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] #[cfg_attr( @@ -25,13 +37,12 @@ const FADE_FRAMES: usize = 200; )] pub struct AlienConfig { /// Selects reversed playback instead of the direct input. The default is - /// `false`. The recording and the phase continue to advance in both - /// states. + /// `false`. Each toggle ramps the wet mix over 200 frames. pub enabled: bool, /// The loop length in frames, 1..=96000. The default is 95,999. /// This value is a frame count at the two rates. Thus, its duration in - /// seconds changes with the sample rate. A short loop can be fully inside - /// the fades. + /// seconds changes with the sample rate. The boundary fade is shorter for + /// short loops and is zero when `loop_frames` is 1. pub loop_frames: u32, } impl Default for AlienConfig { @@ -66,32 +77,65 @@ pub(crate) struct Alien { /// 192,000 stereo Q14 frames, which are allocated one time at /// construction. buffer: Vec<[Q14; 2]>, - /// The current recording position. The position of the reverse reader - /// comes from this cursor. + /// The current write position. The position of the reverse reader comes + /// from this cursor. read: usize, /// The current frame in the loop. It is always less than `loop_len`. phase: usize, /// The validated loop length. It is not more than half of the history /// capacity. loop_len: usize, + /// The number of frames captured since Alien became active. + captured: usize, + /// The current frame in the 200-frame wet mix ramp, in 0..=200. + wet_frames: usize, + /// If `true`, the wet mix ramps to zero before a new capture starts. + restart_pending: bool, } impl Alien { /// Allocates a silent stereo ring from validated loop settings. pub(crate) fn new(config: AlienConfig) -> Self { + let (captured, wet_frames) = if config.enabled { + (HISTORY_FRAMES, FADE_FRAMES) + } else { + (0, 0) + }; Self { config, buffer: vec![[Q14::default(); 2]; HISTORY_FRAMES], read: 0, phase: 0, loop_len: config.loop_frames as usize, + captured, + wet_frames, + restart_pending: false, } } - /// Applies a validated configuration, keeps the recorded audio and clamps - /// the phase into the new loop, which is not empty. + /// Applies a validated configuration and does not clear the buffer. + /// + /// If you enable Alien, this method resets the loop phase and the captured + /// frame count. It also clamps the phase into the new loop, which is not + /// empty. pub(crate) fn set_config(&mut self, config: AlienConfig) { + let was_enabled = self.config.enabled; self.config = config; self.loop_len = config.loop_frames as usize; self.phase = self.phase.min(self.loop_len - 1); + if !was_enabled && config.enabled { + if self.wet_frames == 0 { + self.phase = 0; + self.captured = 0; + self.restart_pending = false; + } else { + self.restart_pending = true; + } + } else if was_enabled && config.enabled { + if self.captured < self.loop_len && self.wet_frames > 0 { + self.restart_pending = true; + } + } else if !config.enabled { + self.restart_pending = false; + } } /// Returns the loop length and the current frame in the loop. /// @@ -100,59 +144,126 @@ impl Alien { pub(crate) fn loop_state(&self) -> (usize, usize) { (self.loop_len, self.phase) } - /// Clears the recorded audio and sets both cursors to zero, but keeps the - /// configured loop. + /// Returns the finite tail budget for the active state or an active ramp. + pub(crate) fn tail_frames(&self) -> usize { + if self.config.enabled { + 2 * self.config.loop_frames as usize + FADE_FRAMES + } else { + self.wet_frames + } + } + /// Clears the recorded audio and resets the cursors and ramps, while it + /// keeps the configured loop. pub(crate) fn reset(&mut self) { self.buffer.fill([Q14::default(); 2]); self.read = 0; self.phase = 0; + if self.config.enabled { + self.captured = HISTORY_FRAMES; + self.wet_frames = FADE_FRAMES; + } else { + self.captured = 0; + self.wet_frames = 0; + } + self.restart_pending = false; } - /// Records a frame, selects the direct or reverse output, then advances - /// both cursors. - /// The recording cursor moves forward by one and the reverse offset - /// increases by two. Thus, the playback moves backward by one frame. The - /// validated loop limit keeps that subtraction in a single ring wrap. - pub(crate) fn process_sample(&mut self, input: [Q14; 2]) -> [Q14; 2] { - self.buffer[self.read] = input; - let result = if self.config.enabled { - let read = self.read + HISTORY_FRAMES - self.phase * 2; - let read = if read >= HISTORY_FRAMES { - read - HISTORY_FRAMES - } else { - read - }; - let distance = self.phase.min(self.loop_len - self.phase); - let mut result = self.buffer[read]; - if distance < FADE_FRAMES { - let gain: Q14 = Fixed::<0>::from_bits(distance as i32) - .div(Fixed::<0>::from_bits(FADE_FRAMES as i32)); - result = result.map(|sample| sample.mul::<14, 14>(gain)); - } - result + /// Reads the current reverse frame and applies the loop boundary fade. + #[inline] + fn reverse_sample(&self) -> [Q14; 2] { + let read = self.read + HISTORY_FRAMES - self.phase * 2; + let read = if read >= HISTORY_FRAMES { + read - HISTORY_FRAMES } else { - input + read }; + let distance = self.phase.min(self.loop_len - self.phase); + let fade_frames = boundary_fade_frames(self.loop_len); + let mut result = self.buffer[read]; + if distance < fade_frames { + let gain: Q14 = Fixed::<0>::from_bits(distance as i32) + .div(Fixed::<0>::from_bits(fade_frames as i32)); + result = result.map(|sample| sample.mul::<14, 14>(gain)); + } + result + } + /// Blends the direct input and the reverse sample with the Q14 wet ramp. + #[inline] + fn mix_wet(&self, input: [Q14; 2], reverse: [Q14; 2]) -> [Q14; 2] { + if self.wet_frames == 0 { + input + } else if self.wet_frames >= FADE_FRAMES { + reverse + } else { + let wet: Q14 = Fixed::<0>::from_bits(self.wet_frames as i32) + .div(Fixed::<0>::from_bits(FADE_FRAMES as i32)); + let dry = Q14::ONE - wet; + [ + input[0].mul::<14, 14>(dry) + reverse[0].mul::<14, 14>(wet), + input[1].mul::<14, 14>(dry) + reverse[1].mul::<14, 14>(wet), + ] + } + } + /// Advances the write cursor by one frame in the history ring. + #[inline] + fn advance_read(&mut self) { self.read += 1; if self.read == HISTORY_FRAMES { self.read = 0; } + } + /// Advances the loop phase by one frame and wraps at `loop_len`. + #[inline] + fn advance_phase(&mut self) { self.phase += 1; if self.phase == self.loop_len { self.phase = 0; } - result } -} - -/// Returns the finite tail budget: two loop lengths plus the boundary -/// fade. -/// -/// The value is zero when Alien is disabled. It is a configured budget, -/// not a measured tail. -pub(crate) fn tail_frames(config: AlienConfig) -> usize { - if config.enabled { - 2 * config.loop_frames as usize + FADE_FRAMES - } else { - 0 + /// Captures input, holds the dry signal until the loop fills, and ramps + /// the Q14 wet mix over 200 frames on each toggle. + pub(crate) fn process_sample(&mut self, input: [Q14; 2]) -> [Q14; 2] { + if !self.config.enabled && self.wet_frames == 0 { + return input; + } + self.buffer[self.read] = input; + if self.restart_pending { + let reverse = self.reverse_sample(); + self.wet_frames -= 1; + let result = self.mix_wet(input, reverse); + self.advance_read(); + self.advance_phase(); + if self.wet_frames == 0 { + self.phase = 0; + self.captured = 0; + self.restart_pending = false; + } + return result; + } + if self.config.enabled { + self.captured = (self.captured + 1).min(HISTORY_FRAMES); + if self.captured < self.loop_len { + self.advance_read(); + return input; + } + let reverse = self.reverse_sample(); + if self.wet_frames < FADE_FRAMES { + self.wet_frames += 1; + } + let result = self.mix_wet(input, reverse); + self.advance_read(); + self.advance_phase(); + result + } else { + let reverse = self.reverse_sample(); + self.wet_frames -= 1; + let result = self.mix_wet(input, reverse); + self.advance_read(); + self.advance_phase(); + if self.wet_frames == 0 { + self.phase = 0; + self.captured = 0; + } + result + } } } diff --git a/src/effects/reverb.rs b/src/effects/reverb.rs index fe60cd4..33d886f 100644 --- a/src/effects/reverb.rs +++ b/src/effects/reverb.rs @@ -5,13 +5,17 @@ use crate::filter::{Biquad, Design}; use crate::numeric::fixed::{Fixed, Q14}; use crate::{Error, SampleRate}; +/// The step for a 256-frame Q14 gain ramp (`16384 / 256`). +const RAMP_STEP: Q14 = Q14::from_bits(64); + /// The echo or reverberation network. The default is [`Self::Echo`]. /// -/// All modes share one delay buffer. A mode change uses the same buffer -/// contents and damping filter memories. Thus a transition can play audio -/// from the previous network. The stereo layout of the buffer does not make -/// all modes give different left and right signals. Schroeder gives the same -/// value on the two channels. +/// All modes share one delay buffer. If the mode changes while the reverb is +/// active, the stage ramps the wet gain to zero over 256 frames. Then it +/// clears the delay buffer and the damping filters, and ramps the new mode +/// over 256 frames. The stereo layout of the buffer does not make all modes +/// give different left and right signals. Schroeder gives the same value on +/// the two channels. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), @@ -36,12 +40,13 @@ pub enum ReverbMode { /// The reverb after Alien, with controls for the network, the wet mix and the /// decay. /// -/// The reverb is disabled by default. In bypass, the stage returns the input -/// and does not advance the delay network or the damping filters. If the -/// stage is enabled and the mix is zero, the network still operates. A reset -/// clears the delay buffer but keeps the memories of the damping filters. The -/// mix, diffusion and decay controls are quantized to Q14. The function of -/// each control changes with the network. +/// The reverb is disabled by default. If you disable an active reverb, the +/// stage feeds zero input into the network until the decay tail finishes, then +/// clears the delay buffer and the damping filters. If the stage is enabled +/// and the mix is zero, the network still operates. A reset clears the delay +/// buffer and keeps the memories of the damping filters. The mix, diffusion +/// and decay controls are quantized to Q14. The function of each control +/// changes with the network. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] #[cfg_attr( @@ -50,8 +55,8 @@ pub enum ReverbMode { serde(rename_all = "camelCase") )] pub struct ReverbConfig { - /// Enables the selected network. The default is `false`. In bypass, the - /// histories do not change. + /// Enables the selected network. The default is `false`. If you set this + /// field to `false`, an active tail decays with zero input before a clear. pub enabled: bool, /// The topology of the delay network. The default is /// [`ReverbMode::Echo`]. @@ -121,24 +126,39 @@ impl ReverbConfig { pub(crate) struct Reverb { /// The prepared sample rate for the cutoff and tap calculations. rate: SampleRate, - /// The validated controls and the selected network. + /// The validated controls that the host requested. config: ReverbConfig, + /// The controls that currently drive the delay topology. + active_config: ReverbConfig, /// The shared circular storage for all network topologies. delay: DelayLine, - /// The first damping filter. A delay reset or a mode change does not - /// clear its memories. + /// The first damping filter. A processor reset keeps its memories, while a + /// mode switch or a completed bypass tail clears them. lpf1: Biquad, - /// The second damping filter. It keeps its memories in the same way as - /// the first filter. + /// The second damping filter. It keeps and clears its memories in the same + /// way as the first filter. lpf2: Biquad, /// 67 prepared frame offsets into the shared ring. taps: [usize; 67], - /// The Q14 wet contribution. + /// The Q14 wet contribution of `active_config`. mix: Q14, + /// The Q14 wet contribution of `config`, for dry transitions across modes. + target_mix: Q14, /// The Q14 control for the diffusion or the echo distance. diffuse: Q14, /// The Q14 feedback coefficient, scaled by 100/105. decay: Q14, + /// The Q14 ramp between bypass dry and enabled dry, in 0..=1. + enable_fade: Q14, + /// The Q14 wet gain scale for mode switches, in 0..=1. + mode_fade: Q14, + /// If `true`, `mode_fade` moves to zero before the network clears. + fading_out_mode: bool, + /// The frames of silent-input decay that are left in bypass. + bypass_remaining: usize, + /// Consecutive bypass frames within the two-unit fixed-point limit-cycle + /// floor. + bypass_quiet_frames: usize, /// The Binaural delay of approximately 0.8 ms between the tap that gets /// the early sum and the filtered tap. Both channels use it. binaural_offset: usize, @@ -160,41 +180,67 @@ fn q14(coefficient: f64) -> Q14 { Q14::from_f64(coefficient) } +/// Quantizes a public mix control to Q14 after single-precision multiplication. +#[inline] +fn quantize_mix(mix: f32) -> Q14 { + Q14::from_f64((mix * 100.0) as f64 / 100.0) +} + /// Multiplies two Q14 values with a wrapping 32-bit product before the shift. #[inline] fn mul(left: Q14, right: Q14) -> Q14 { left.mul(right) } +/// Returns the enabled dry pair for a mode, a dry weight and a frame. +#[inline] +fn mode_dry(mode: ReverbMode, left: Q14, right: Q14, mono: Q14, dry: Q14) -> [Q14; 2] { + if matches!(mode, ReverbMode::Schroeder | ReverbMode::Binaural) { + let value = mul(mono, dry); + [value, value] + } else { + [mul(left, dry), mul(right, dry)] + } +} + impl Reverb { /// Allocates the shared delay layout and prepares the filters from /// validated controls. pub(crate) fn new(rate: SampleRate, config: ReverbConfig) -> Self { let layout = reverb_layout(rate.hz()); + let enable_fade = if config.enabled { Q14::ONE } else { Q14::ZERO }; let mut result = Self { rate, config, + active_config: config, delay: DelayLine::new(layout.capacity), lpf1: Biquad::new(), lpf2: Biquad::new(), taps: layout.taps, mix: Q14::default(), + target_mix: quantize_mix(config.mix), diffuse: Q14::default(), decay: Q14::default(), + enable_fade, + mode_fade: Q14::ONE, + fading_out_mode: false, + bypass_remaining: 0, + bypass_quiet_frames: 0, binaural_offset: layout.binaural_offset, scratch: layout.capacity - 1, wet_peak: 0, }; - result.set_config(config); + result.apply_active_config(config); result } - /// Updates the coefficients and does not clear the delay or filter state. + /// Quantizes the active controls and updates the damping filter designs. + /// /// 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) { - self.config = config; - self.mix = Q14::from_f64((config.mix * 100.0) as f64 / 100.0); + fn apply_active_config(&mut self, config: ReverbConfig) { + self.active_config = config; + self.mix = quantize_mix(config.mix); 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 @@ -204,10 +250,82 @@ impl Reverb { self.lpf1.set_design(design); self.lpf2.set_design(design); } - /// Clears only the delay contents, and keeps the write cursor and the - /// damping memories. + /// Clears the delay buffer and both damping filters after a transition. + fn clear_all(&mut self) { + self.delay.reset(); + self.lpf1.reset(); + self.lpf2.reset(); + self.bypass_quiet_frames = 0; + } + /// Applies validated controls and starts mode fades or bypass tails when + /// necessary. + pub(crate) fn set_config(&mut self, config: ReverbConfig) { + let was_running = + self.config.enabled || self.bypass_remaining > 0 || self.enable_fade > Q14::ZERO; + let prev_enabled = self.config.enabled; + self.config = config; + self.target_mix = quantize_mix(config.mix); + if !was_running { + self.apply_active_config(config); + self.fading_out_mode = false; + self.mode_fade = Q14::ONE; + return; + } + if config.mode != self.active_config.mode { + self.fading_out_mode = true; + if prev_enabled && !config.enabled { + let mut active = self.active_config; + active.enabled = true; + self.bypass_remaining = tail_frames(self.rate, active); + self.bypass_quiet_frames = 0; + } + return; + } + self.fading_out_mode = false; + if config.enabled { + self.apply_active_config(config); + self.bypass_remaining = 0; + self.bypass_quiet_frames = 0; + } else if prev_enabled { + let mut active = self.active_config; + active.enabled = true; + self.bypass_remaining = tail_frames(self.rate, active); + self.bypass_quiet_frames = 0; + if self.bypass_remaining == 0 { + self.clear_all(); + } + } + } + /// Clears the delay contents and transition state, while it keeps the + /// write cursor and the damping memories. pub(crate) fn reset(&mut self) { self.delay.reset(); + self.apply_active_config(self.config); + self.enable_fade = if self.config.enabled { + Q14::ONE + } else { + Q14::ZERO + }; + self.mode_fade = Q14::ONE; + self.fading_out_mode = false; + self.bypass_remaining = 0; + self.bypass_quiet_frames = 0; + } + /// Returns the finite tail budget, with active bypass tails included. + pub(crate) fn tail_frames(&self) -> usize { + let fade_frames = |fade: Q14| (fade.to_bits().max(0) as usize).div_ceil(64); + if self.config.enabled { + let base = tail_frames(self.rate, self.config); + if self.fading_out_mode { + base.saturating_add(fade_frames(self.mode_fade)) + } else { + base + } + } else if self.fading_out_mode { + fade_frames(self.mode_fade).max(fade_frames(self.enable_fade)) + } else { + self.bypass_remaining.max(fade_frames(self.enable_fade)) + } } /// Returns the largest absolute Q14 wet contribution since the last /// clear, as f32. @@ -220,31 +338,241 @@ impl Reverb { } /// Calculates the selected network one time and advances the ring by one /// frame. - /// In bypass, no delay or filter history advances. The internal mono - /// averages use integer division toward zero. The PCM downmix in the - /// processor uses a shift. + /// + /// When the stage is idle in bypass, no delay or filter history advances. + /// The internal mono averages use integer division toward zero. The PCM + /// downmix in the processor uses a shift. pub(crate) fn process_sample(&mut self, frame: [Q14; 2]) -> [Q14; 2] { + if !self.config.enabled + && self.bypass_remaining == 0 + && !self.fading_out_mode + && self.enable_fade == Q14::ZERO + { + return frame; + } + if self.config.enabled && self.enable_fade < Q14::ONE { + self.enable_fade = (self.enable_fade + RAMP_STEP).min(Q14::ONE); + } else if !self.config.enabled && self.enable_fade > Q14::ZERO { + self.enable_fade = (self.enable_fade - RAMP_STEP).max(Q14::ZERO); + } + if self.fading_out_mode { + self.mode_fade = (self.mode_fade - RAMP_STEP).max(Q14::ZERO); + } else if self.mode_fade < Q14::ONE { + self.mode_fade = (self.mode_fade + RAMP_STEP).min(Q14::ONE); + } + let [left, right] = frame; let mono = (left + right).div::<0, 14>(TWO); let t = self.taps; let dry = Q14::ONE - self.mix; - let d = &mut self.delay; - if !self.config.enabled { - return frame; + + // Keep the exact steady-state arithmetic when no transition is active. + if self.config.enabled + && !self.fading_out_mode + && self.enable_fade == Q14::ONE + && self.mode_fade == Q14::ONE + { + let d = &mut self.delay; + let mut result = match self.active_config.mode { + ReverbMode::Echo => { + d.put(mono, t[0]); + 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); + [ + 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 => { + 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.fir( + t[40], + &[ + (t[12], q14(0.25)), + (t[22], q14(0.25)), + (t[28], q14(0.25)), + (t[34], q14(0.25)), + ], + ); + d.allpass(t[40], t[43], self.decay); + d.allpass(t[44], t[45], self.decay); + let value = mul(mono, dry) + mul(self.mix, d.get(t[45])); + [value, value] + } + ReverbMode::SmallRoom => { + 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.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.comb_lpf(t[0], t[66], self.decay, &mut self.lpf2); + [ + d.fir( + self.scratch, + &[(t[16], q14(0.2)), (t[32], q14(0.2)), (t[51], q14(0.2))], + ), + d.fir( + self.scratch, + &[(t[49], q14(0.2)), (t[65], q14(0.2)), (t[17], q14(0.2))], + ), + ] + } + ReverbMode::Binaural => { + let seed = t[10]; + let tap = t[25]; + let filter = tap + self.binaural_offset; + d.put(left, t[0]); + d.put(right, t[40]); + let a = mul( + self.diffuse >> 1, + d.get(t[0] + seed) + d.get(t[11] + seed) + d.get(t[21] + seed), + ); + d.put(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); + d.lpf(t[40] + filter, &mut self.lpf2); + [out, mul(mono, dry) + mul(self.mix, d.get(filter) + b)] + } + ReverbMode::MediumHall => { + d.put(mono.div::<0, 14>(TWO), t[0]); + d.lpf(t[2], &mut self.lpf1); + for (a, b, g) in [(3, 15, 0.4), (4, 7, 0.9), (8, 14, 0.6), (18, 24, 0.6)] { + d.allpass(t[a], t[b], mul(self.diffuse, q14(g))); + } + d.put(d.get(t[35]), t[40]); + for (a, b, g) in [(41, 50, 0.5), (42, 46, 0.8)] { + d.allpass(t[a], t[b], mul(self.diffuse, q14(g))); + } + d.comb_lpf(t[0], t[66], self.decay, &mut self.lpf2); + [ + d.fir( + self.scratch, + &[ + (t[16], q14(-0.25)), + (t[33], q14(0.25)), + (t[51], q14(-0.25)), + (t[55], q14(0.25)), + ], + ), + d.fir( + self.scratch, + &[ + (t[16], q14(0.25)), + (t[32], q14(0.25)), + (t[52], q14(0.25)), + (t[56], q14(0.2)), + ], + ), + ] + } + ReverbMode::LargeHall => { + d.put(mono, t[0]); + d.lpf(t[2], &mut self.lpf1); + for (a, b, g) in [(3, 5, 0.6), (6, 9, 0.6), (19, 30, 0.95), (20, 27, 0.5)] { + d.allpass(t[a], t[b], mul(self.diffuse, q14(g))); + } + d.put(d.get(t[38]), t[40]); + for (a, b, g) in [(41, 63, 0.95), (42, 58, 0.5), (59, 62, 0.5)] { + d.allpass(t[a], t[b], mul(self.diffuse, q14(g))); + } + d.comb_lpf(t[1], t[64], self.decay, &mut self.lpf2); + [ + d.fir( + self.scratch, + &[(t[10], q14(0.6)), (t[36], q14(0.3)), (t[61], q14(0.3))], + ), + d.fir( + self.scratch, + &[(t[10], q14(0.6)), (t[37], q14(0.3)), (t[60], q14(0.3))], + ), + ] + } + }; + if matches!( + self.active_config.mode, + ReverbMode::SmallRoom | ReverbMode::MediumHall | ReverbMode::LargeHall + ) { + result[0] = mul(left, dry) + mul(self.mix, result[0]); + result[1] = mul(right, dry) + mul(self.mix, result[1]); + } + d.step(); + let dry_input = if matches!( + self.active_config.mode, + ReverbMode::Schroeder | ReverbMode::Binaural + ) { + [mono, mono] + } else { + [left, right] + }; + for (value, input) in result.iter().zip(dry_input) { + let wet = (*value - mul(input, dry)).to_bits().wrapping_abs(); + self.wet_peak = self.wet_peak.max(wet); + } + return result; } - let mut result = match self.config.mode { + + // Transition or bypass-tail path: zero network input in bypass, + // ramped input when reverb becomes active, and ramped wet gain across + // mode switches. + let (net_left, net_right, net_mono) = if self.config.enabled { + let nl = mul(left, self.enable_fade); + let nr = mul(right, self.enable_fade); + (nl, nr, (nl + nr).div::<0, 14>(TWO)) + } else { + (Q14::ZERO, Q14::ZERO, Q14::ZERO) + }; + let wet_gain = mul(self.mix, self.mode_fade); + let active_dry = mode_dry(self.active_config.mode, left, right, mono, dry); + let enabled_dry = if self.fading_out_mode && self.config.enabled { + let target = mode_dry( + self.config.mode, + left, + right, + mono, + Q14::ONE - self.target_mix, + ); + [ + mul(active_dry[0], self.mode_fade) + mul(target[0], Q14::ONE - self.mode_fade), + mul(active_dry[1], self.mode_fade) + mul(target[1], Q14::ONE - self.mode_fade), + ] + } else { + active_dry + }; + let bypass_weight = Q14::ONE - self.enable_fade; + let dry_terms = [ + mul(left, bypass_weight) + mul(enabled_dry[0], self.enable_fade), + mul(right, bypass_weight) + mul(enabled_dry[1], self.enable_fade), + ]; + + let d = &mut self.delay; + let wet_terms = match self.active_config.mode { ReverbMode::Echo => { - d.put(mono, t[0]); + d.put(net_mono, t[0]); 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); [ - 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])), + mul(wet_gain, d.get(t[25]) - d.get(t[32])), + -mul(wet_gain, d.get(t[26]) - d.get(t[31])), ] } ReverbMode::Schroeder => { for i in [0, 13, 23, 29] { - d.put(mono.div::<0, 14>(TWO), t[i]); + d.put(net_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)); @@ -260,12 +588,12 @@ impl Reverb { ); d.allpass(t[40], t[43], self.decay); d.allpass(t[44], t[45], self.decay); - let value = mul(mono, dry) + mul(self.mix, d.get(t[45])); - [value, value] + let wet = mul(wet_gain, d.get(t[45])); + [wet, wet] } ReverbMode::SmallRoom => { - d.put(left, t[0]); - d.put(right, t[40]); + d.put(net_left, t[0]); + d.put(net_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)); } @@ -274,40 +602,40 @@ impl Reverb { d.allpass(t[a], t[b], q14(g)); } d.comb_lpf(t[0], t[66], self.decay, &mut self.lpf2); - [ - d.fir( - self.scratch, - &[(t[16], q14(0.2)), (t[32], q14(0.2)), (t[51], q14(0.2))], - ), - d.fir( - self.scratch, - &[(t[49], q14(0.2)), (t[65], q14(0.2)), (t[17], q14(0.2))], - ), - ] + let l = d.fir( + self.scratch, + &[(t[16], q14(0.2)), (t[32], q14(0.2)), (t[51], q14(0.2))], + ); + let r = d.fir( + self.scratch, + &[(t[49], q14(0.2)), (t[65], q14(0.2)), (t[17], q14(0.2))], + ); + [mul(wet_gain, l), mul(wet_gain, r)] } ReverbMode::Binaural => { let seed = t[10]; let tap = t[25]; let filter = tap + self.binaural_offset; - d.put(left, t[0]); - d.put(right, t[40]); + d.put(net_left, t[0]); + d.put(net_right, t[40]); let a = mul( self.diffuse >> 1, d.get(t[0] + seed) + d.get(t[11] + seed) + d.get(t[21] + seed), ); d.put(a, tap); d.lpf(filter, &mut self.lpf1); - let out = mul(mono, dry) + mul(self.mix, d.get(t[40] + filter) + a); + let wet_l = mul(wet_gain, 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); d.lpf(t[40] + filter, &mut self.lpf2); - [out, mul(mono, dry) + mul(self.mix, d.get(filter) + b)] + let wet_r = mul(wet_gain, d.get(filter) + b); + [wet_l, wet_r] } ReverbMode::MediumHall => { - d.put(mono.div::<0, 14>(TWO), t[0]); + d.put(net_mono.div::<0, 14>(TWO), t[0]); d.lpf(t[2], &mut self.lpf1); for (a, b, g) in [(3, 15, 0.4), (4, 7, 0.9), (8, 14, 0.6), (18, 24, 0.6)] { d.allpass(t[a], t[b], mul(self.diffuse, q14(g))); @@ -317,29 +645,28 @@ impl Reverb { d.allpass(t[a], t[b], mul(self.diffuse, q14(g))); } d.comb_lpf(t[0], t[66], self.decay, &mut self.lpf2); - [ - d.fir( - self.scratch, - &[ - (t[16], q14(-0.25)), - (t[33], q14(0.25)), - (t[51], q14(-0.25)), - (t[55], q14(0.25)), - ], - ), - d.fir( - self.scratch, - &[ - (t[16], q14(0.25)), - (t[32], q14(0.25)), - (t[52], q14(0.25)), - (t[56], q14(0.2)), - ], - ), - ] + let l = d.fir( + self.scratch, + &[ + (t[16], q14(-0.25)), + (t[33], q14(0.25)), + (t[51], q14(-0.25)), + (t[55], q14(0.25)), + ], + ); + let r = d.fir( + self.scratch, + &[ + (t[16], q14(0.25)), + (t[32], q14(0.25)), + (t[52], q14(0.25)), + (t[56], q14(0.2)), + ], + ); + [mul(wet_gain, l), mul(wet_gain, r)] } ReverbMode::LargeHall => { - d.put(mono, t[0]); + d.put(net_mono, t[0]); d.lpf(t[2], &mut self.lpf1); for (a, b, g) in [(3, 5, 0.6), (6, 9, 0.6), (19, 30, 0.95), (20, 27, 0.5)] { d.allpass(t[a], t[b], mul(self.diffuse, q14(g))); @@ -349,39 +676,47 @@ impl Reverb { d.allpass(t[a], t[b], mul(self.diffuse, q14(g))); } d.comb_lpf(t[1], t[64], self.decay, &mut self.lpf2); - [ - d.fir( - self.scratch, - &[(t[10], q14(0.6)), (t[36], q14(0.3)), (t[61], q14(0.3))], - ), - d.fir( - self.scratch, - &[(t[10], q14(0.6)), (t[37], q14(0.3)), (t[60], q14(0.3))], - ), - ] + let l = d.fir( + self.scratch, + &[(t[10], q14(0.6)), (t[36], q14(0.3)), (t[61], q14(0.3))], + ); + let r = d.fir( + self.scratch, + &[(t[10], q14(0.6)), (t[37], q14(0.3)), (t[60], q14(0.3))], + ); + [mul(wet_gain, l), mul(wet_gain, r)] } }; - if matches!( - self.config.mode, - ReverbMode::SmallRoom | ReverbMode::MediumHall | ReverbMode::LargeHall - ) { - result[0] = mul(left, dry) + mul(self.mix, result[0]); - result[1] = mul(right, dry) + mul(self.mix, result[1]); - } d.step(); - // Telemetry only. The wet contribution is the output minus the dry - // term. Schroeder and Binaural use the mono dry signal. - let dry_input = if matches!( - self.config.mode, - ReverbMode::Schroeder | ReverbMode::Binaural - ) { - [mono, mono] - } else { - [left, right] - }; - for (value, input) in result.iter().zip(dry_input) { - let wet = (*value - mul(input, dry)).to_bits().wrapping_abs(); - self.wet_peak = self.wet_peak.max(wet); + let result = [dry_terms[0] + wet_terms[0], dry_terms[1] + wet_terms[1]]; + if self.config.enabled { + for wet in wet_terms { + self.wet_peak = self.wet_peak.max(wet.to_bits().wrapping_abs()); + } + } + if self.fading_out_mode && self.mode_fade == Q14::ZERO { + self.clear_all(); + self.fading_out_mode = false; + self.apply_active_config(self.config); + if self.config.enabled { + self.bypass_remaining = 0; + } else { + self.bypass_remaining = 0; + self.mode_fade = Q14::ONE; + } + } else if !self.config.enabled && self.bypass_remaining > 0 { + let quiet = wet_terms[0].to_bits().wrapping_abs() <= 2 + && wet_terms[1].to_bits().wrapping_abs() <= 2; + if quiet { + self.bypass_quiet_frames += 1; + } else { + self.bypass_quiet_frames = 0; + } + self.bypass_remaining -= 1; + if self.bypass_remaining == 0 || self.bypass_quiet_frames >= self.delay.buffer.len() { + self.bypass_remaining = 0; + self.clear_all(); + } } result } diff --git a/src/formant.rs b/src/formant.rs index 5072ee1..765c387 100644 --- a/src/formant.rs +++ b/src/formant.rs @@ -200,6 +200,8 @@ pub(crate) struct Formant { /// If `true`, the next call to `smooth` clears the state of the /// correlation average. smooth_reset: bool, + /// If `true`, the next model design sets `blend` to 1.0 immediately. + snap_blend: bool, /// The Q14 first-order coefficient for pre-emphasis and de-emphasis. glottal: i32, /// The Q14 width control. The stage also uses it as the output gain of @@ -265,6 +267,7 @@ impl Formant { smooth_index: 0, smooth_filled: 0, smooth_reset: true, + snap_blend: false, glottal: (0.5_f64.powf(1.0 / d2) * 16384.0) as i32, width: 16384, width_squared: 16384, @@ -326,6 +329,44 @@ impl Formant { self.design_counter = 0; self.noise_filter.reset(); self.smooth_reset = true; + self.snap_blend = false; + } + /// Prepares the stage when the formant stage becomes active and backfills + /// at least 491 pre-emphasized samples from `raw`. + pub(crate) fn prepare_enable( + &mut self, + raw: &[Q14; HISTORY_FRAMES], + write: usize, + output_period_q6: i32, + ) { + let period = output_period_q6.wrapping_shr(6).max(0) as usize; + let extra = (period / 10).max(1); + let count = (ANALYSIS_FRAMES + ORDER) + .max(2 * period + extra + 2) + .min(HISTORY_FRAMES - 1); + for offset in (1..=count).rev() { + let index = (write + HISTORY_FRAMES - offset) % HISTORY_FRAMES; + let previous = if index == 0 { + HISTORY_FRAMES - 1 + } else { + index - 1 + }; + self.input[index] = self.remove_glottal(raw[index].to_bits(), raw[previous].to_bits()); + } + self.history = [[0; MAX_ORDER]; 2]; + self.history_index = 0; + self.orders = [0; BANKS]; + self.current = BANKS - 1; + self.next_filter(); + self.next_filter(); + self.design_counter = 0; + self.noise_filter.reset(); + self.smooth_reset = true; + self.snap_blend = true; + } + /// Copies the synthesis feedback history from channel zero to channel one. + pub(crate) fn copy_channel_zero(&mut self) { + self.history[1] = self.history[0]; } /// Starts a new model and a new correlation window when pitch acquisition /// locks. @@ -616,7 +657,10 @@ impl Formant { self.smooth_reset = true; } } - if self.blend < 16384 { + if self.snap_blend { + self.blend = 16384; + self.snap_blend = false; + } else if self.blend < 16384 { self.blend = (self.blend + 1638).min(16384); } self.stamps[position] = Stamp { @@ -664,7 +708,7 @@ impl Formant { /// 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.config.enabled || 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..605b0df 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -1,8 +1,8 @@ //! The processor: audio blocks, timed controls, host feedback and the tail. -use crate::effects::alien::{self, Alien}; +use crate::effects::alien::Alien; use crate::effects::punch::{Punch, PunchConfig}; -use crate::effects::reverb::{self, Reverb}; +use crate::effects::reverb::Reverb; use crate::effects::warm::Warm; use crate::events::{ValidatedEvent, ValidatedEvents}; use crate::numeric::rng::RandomStream; @@ -38,12 +38,12 @@ pub struct Processor { /// The pitch tracking and voice histories, in a box to keep the handle /// small. resynthesis: Box, - /// The reverse-loop history, which records also while its wet output is - /// disabled. + /// The reverse-loop history, with a captured loop and wet mix ramps. alien: Alien, /// The delay network and the damping filters. /// - /// In bypass, their histories do not change. + /// When you disable reverb, an active tail decays with zero input before a + /// clear. reverb: Reverb, /// The random sequence of this instance and the cached arctangent position. numeric: NumericContext, @@ -57,8 +57,7 @@ pub struct Processor { output_peaks: [i32; 2], /// The last ratio from correction only. /// - /// It is zero before the first `process` call, after a reset or after a - /// change of stereo output. + /// It is zero before the first `process` call or after a reset. last_resample_ratio: f32, /// The count of rendered frames since reset, with drain frames included. /// @@ -300,11 +299,8 @@ impl Processor { pub fn tail_frames(&self) -> usize { self.resynthesis .tail_frames() - .saturating_add(alien::tail_frames(self.config.alien)) - .saturating_add(reverb::tail_frames( - self.preparation.sample_rate, - self.config.reverb, - )) + .saturating_add(self.alien.tail_frames()) + .saturating_add(self.reverb.tail_frames()) } /// Returns the fixed sample rate and block limit. @@ -458,17 +454,19 @@ impl Processor { /// /// The validation also examines the fields of disabled stages. A stage /// that does not change keeps its state. A change of `stereo_output` - /// resets the resynthesis audio state, Alien, the reverb delays, the peak - /// and the reported ratio. It also releases the harmony MIDI notes. It - /// keeps Punch, Warm, the correction keys, the random stream, the reverb - /// low-pass memories and the frame count. A change of `random_seed` starts - /// the random stream again. + /// ramps the voice pan weights over 256 frames and keeps the audio + /// histories, the feedback and the held MIDI notes. A change of + /// `random_seed` starts the random stream again. /// /// Each successful call cancels a drain, also for an identical - /// configuration. A change of reverb mode keeps the delay contents. If you - /// disable Punch, Warm or reverb, the history of that stage stops. Alien - /// continues to record. A change in either half of the `u64` seed starts - /// the stream again, but the new sequence uses only the low 32 bits. + /// configuration. If the reverb mode changes, the stage ramps the wet gain + /// to zero over 256 frames. Then it clears the delay buffer and the + /// damping filters, and ramps the new mode over 256 frames. If you disable + /// Punch or Warm, the history of that stage stops. If you disable reverb, + /// its active tail decays with zero input before a clear. When you enable + /// Alien, it captures a fresh loop and ramps the wet mix over 200 frames. + /// A change in either half of the `u64` seed starts the stream again, but + /// the new sequence uses only the low 32 bits. /// /// # Errors /// @@ -491,14 +489,6 @@ impl Processor { if self.config.resynthesis != config.resynthesis { self.resynthesis.apply_config(config.resynthesis); } - if self.config.resynthesis.stereo_output != config.resynthesis.stereo_output { - // Resynthesis resets its histories if its stereo setting changes. - self.alien.reset(); - self.reverb.reset(); - self.peak = 0; - self.clear_telemetry_peaks(); - self.last_resample_ratio = 0.0; - } if self.config.resynthesis.random_seed != config.resynthesis.random_seed { self.numeric.random = RandomStream::new(config.resynthesis.random_seed as u32); } @@ -715,8 +705,8 @@ pub struct Feedback { /// unity. /// /// It does not include the configured pitch shift or the ratios of - /// individual voices. It is zero before processing, after a reset or after - /// a change of stereo output. + /// individual voices. It is zero before the first `process` call or after a + /// reset. pub resample_ratio: f32, /// The reported input pitch period in samples, with fractional samples. /// @@ -755,10 +745,10 @@ pub struct Feedback { pub voiced: bool, /// The largest absolute clipped stereo sample, divided by 32768. /// - /// The peak window starts at construction, at a reset, at a change of - /// stereo output or at a call to [`Processor::take_feedback`]. The value - /// is in 0..=32767/32768. The mono downmix occurs after this measurement. - /// [`Processor::feedback`] does not clear the value. + /// The peak window starts at construction, at a reset or at a call to + /// [`Processor::take_feedback`]. The value is in 0..=32767/32768. The mono + /// downmix occurs after this measurement. [`Processor::feedback`] does not + /// clear the value. pub peak_level: f32, /// The number of frames processed since construction or the last reset, /// with drain frames included. @@ -783,9 +773,8 @@ pub struct Feedback { /// `Default` gives a snapshot with all zeros. /// /// The three peak fields measure a window. The window starts at -/// construction, at a reset, at a change of stereo output or at a call to -/// [`Processor::take_telemetry`]. This window is independent of the peak -/// window of [`Feedback`]. +/// construction, at a reset or at a call to [`Processor::take_telemetry`]. +/// This window is independent of the peak window of [`Feedback`]. #[derive(Clone, Copy, Debug, Default, PartialEq)] #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), @@ -870,7 +859,7 @@ pub struct Telemetry { /// [`alien_loop_frames`](Self::alien_loop_frames). /// /// The reverse reader is two times this number of frames behind the - /// recording position. The value advances also while Alien is disabled. + /// write position after loop capture completes. pub alien_phase_frames: u32, /// The wrapping count of formant analyses since construction. /// diff --git a/src/resynthesis.rs b/src/resynthesis.rs index 34e98fa..4c918ff 100644 --- a/src/resynthesis.rs +++ b/src/resynthesis.rs @@ -16,8 +16,9 @@ //! voices are mixed. //! //! A reader jumps by one pitch period to stay in a range behind the writer. -//! The choir lead uses a crossfade across these jumps. Harmonic modulation -//! applies to the wet mix. Then the code blends in a delayed dry signal. +//! All active Choir and Harmony voices use a crossfade across these jumps. +//! Harmonic modulation applies to the wet mix. Then the code adds a delayed +//! dry signal. //! //! Audio, reader positions and pitch ratios use Q14. Periods use Q6, harmony //! gains use Q12 and the dry mix uses Q8. Some of these units use the same @@ -214,8 +215,9 @@ pub struct ResynthesisConfig { /// Enables a stereo pan for each voice. The default is `false`. /// /// This value is independent of the buffer layout of the process method. - /// A change to this value resets some audio histories and the feedback. - /// [`crate::Processor::set_config`] gives the details. + /// A change to this value ramps the voice pan weights over 256 frames and + /// keeps the audio histories. [`crate::Processor::set_config`] gives the + /// details. pub stereo_output: bool, /// The controls for the four harmony voices. The default is MIDI-channel /// allocation. @@ -345,6 +347,24 @@ const CONTROL_DUE: i32 = 100; const DRIFT_LIMIT: Q14 = Q14::from_bits(3276); /// The step for each frame of the crossfade after a reader jump. const FADE_STEP: Q14 = Q14::from_bits(0x333); +/// The step for each frame of a 256-frame stage ramp (`16384 / 256`). +const STAGE_RAMP_STEP: Q14 = Q14::from_bits(64); + +/// Returns the stereo pair for one voice sample and its Q14 pan weights. +#[inline] +fn apply_pan(value: Q14, pan: [Q14; 2], stereo_fade: Q14) -> [Q14; 2] { + if stereo_fade == Q14::ZERO { + [value, value] + } else if stereo_fade == Q14::ONE { + [value.mul(pan[0]), value.mul(pan[1])] + } else { + let mono = Q14::ONE - stereo_fade; + [ + value.mul(mono + pan[0].mul(stereo_fade)), + value.mul(mono + pan[1].mul(stereo_fade)), + ] + } +} /// Returns the reader position at the start of the history frame `frame`. #[inline] @@ -461,12 +481,29 @@ pub(crate) struct Resynthesis { /// The Q8 weight of the delayed raw audio. The wet weight is 1.0 minus /// this weight. dry_mix: Q8, - /// The previous position of the lead reader. The crossfade after a jump - /// follows this position. - old_position: Q14, - /// The Q14 weight of the new lead reader. After a jump, it increases - /// toward 1.0. - fade: Q14, + /// The previous positions of the voice readers, for crossfades after + /// period wraps or delay changes. + old_positions: [Q14; 16], + /// The Q14 weights of the new voice readers. After a jump, each weight + /// increases toward 1.0. + fades: [Q14; 16], + /// The number of recent contiguous frames in `lead` that `render_lead` + /// wrote. + lead_valid: usize, + /// The state of `formant.enabled` from the previous frame. + was_formant_enabled: bool, + /// The frames that are left before a formant switch reaches `filtered`. + overlap_pending: u16, + /// `true` if `overlap` holds both raw and formant-analyzed frames. + overlap_mixed: bool, + /// `true` if the frames that enter `filtered` come from formant analysis. + filtered_lpc: bool, + /// The number of recent contiguous frames in `filtered` of `filtered_lpc`. + filtered_valid: u16, + /// The Q14 crossfade weight of LPC synthesis, in 0..=1. + formant_fade: Q14, + /// The Q14 ramp weight of the stereo pan, in 0..=1. + stereo_fade: Q14, /// The Q6 period that the code selected last for a voice. The modulation /// uses it. current_output_period: Q6, @@ -541,8 +578,24 @@ impl Resynthesis { modulation: 0, modulation_phase: Q14::ZERO, dry_mix: Q8::ZERO, - old_position: position_of(-READER_LAG_FRAMES), - fade: Q14::ONE, + old_positions: [position_of(-READER_LAG_FRAMES); 16], + fades: [Q14::ONE; 16], + lead_valid: HISTORY, + was_formant_enabled: config.formant.enabled, + overlap_pending: 0, + overlap_mixed: false, + filtered_lpc: config.formant.enabled, + filtered_valid: HISTORY as u16, + formant_fade: if config.formant.enabled { + Q14::ONE + } else { + Q14::ZERO + }, + stereo_fade: if config.stereo_output { + Q14::ONE + } else { + Q14::ZERO + }, current_output_period: Q6::ZERO, control_counter: CONTROL_DUE, drift_decay: Q14::ZERO, @@ -640,6 +693,11 @@ impl Resynthesis { /// Applies a configuration that passed the full validation before. pub(crate) fn apply_config(&mut self, config: ResynthesisConfig) { let old = self.config; + let old_active = if old.mode == MultiVoiceMode::Choir { + old.choir_voices as usize + } else { + HARMONY_VOICES + 1 + }; self.config = config; self.pitch.set_config(config.pitch); self.formant.set_config(config.formant); @@ -654,19 +712,31 @@ impl Resynthesis { self.configure_shift_filters(); } if old.mode != config.mode || old.choir_delay != config.choir_delay { + for voice in 0..old_active { + self.old_positions[voice] = self.positions[voice]; + self.fades[voice] = Q14::ZERO; + } self.create_delays(); - } - if old.choir_voices < config.choir_voices { + for voice in old_active..16 { + self.old_positions[voice] = self.positions[voice]; + self.fades[voice] = Q14::ONE; + } + } else if old.choir_voices < config.choir_voices { for voice in old.choir_voices as usize..config.choir_voices as usize { - self.positions[voice] = self.positions[0]; + let position = + position_of(self.write as i32 - READER_LAG_FRAMES - self.delays[voice]); + self.positions[voice] = position; + self.old_positions[voice] = position; + self.fades[voice] = Q14::ONE; } } - self.configure_coefficients(); - if old.stereo_output != config.stereo_output { - // A stereo change resets the audio state. The correction keyboard - // keeps its held keys. - self.reset_audio(); + if (old.mode == MultiVoiceMode::Choir && config.mode == MultiVoiceMode::Harmony) + || (!old.stereo_output && config.stereo_output && self.stereo_fade == Q14::ZERO) + { + self.formant.copy_channel_zero(); + self.previous_output[1] = self.previous_output[0]; } + self.configure_coefficients(); } /// Releases the correction keys 0..=126 and resets the audio state. @@ -709,8 +779,28 @@ impl Resynthesis { } self.create_delays(); self.drift_ratio.fill(Q14::ONE); - self.old_position = self.positions[0]; - self.fade = Q14::ONE; + self.old_positions = self.positions; + self.fades.fill(Q14::ONE); + self.lead_valid = if self.config.mode == MultiVoiceMode::Choir { + HISTORY + } else { + 0 + }; + self.was_formant_enabled = self.config.formant.enabled; + self.overlap_pending = 0; + self.overlap_mixed = false; + self.filtered_lpc = self.config.formant.enabled; + self.filtered_valid = HISTORY as u16; + self.formant_fade = if self.config.formant.enabled { + Q14::ONE + } else { + Q14::ZERO + }; + self.stereo_fade = if self.config.stereo_output { + Q14::ONE + } else { + Q14::ZERO + }; self.harmony_ratios.fill(Q14::ONE); self.voice_ratios.fill(Q14::ONE); self.formant_position = 0; @@ -938,18 +1028,8 @@ impl Resynthesis { /// Advances one Q14 reader by its ratio and keeps it near the writer. /// /// If the reader gets to one of the two limits, it jumps by one Q6 pitch - /// period. `offset` is an integer voice delay. `voice` must identify an - /// allocated reader slot. If `fade` is `true` and the reader jumps, the - /// function saves the old position and starts the crossfade again. Only - /// the choir lead sets `fade`. - fn move_reader( - &mut self, - voice: usize, - ratio: Q14, - period: Q6, - offset: i32, - fade: bool, - ) -> Q14 { + /// period, saves the old position and starts the crossfade of that voice. + fn move_reader(&mut self, voice: usize, ratio: Q14, period: Q6, offset: i32) -> Q14 { let mut position = self.positions[voice] + ratio; let write = self.write as i32; let upper = position_of(write - 40 - offset); @@ -961,15 +1041,15 @@ impl Resynthesis { .wrapping_sub(offset), ); if position >= upper { - if fade { - self.old_position = position; - self.fade = Q14::ZERO; + if period != Q6::ZERO || self.old_positions[voice] == position { + self.old_positions[voice] = position; + self.fades[voice] = Q14::ZERO; } position = position - period.rescale(); } else if position <= lower { - if fade { - self.old_position = position; - self.fade = Q14::ZERO; + if period != Q6::ZERO || self.old_positions[voice] == position { + self.old_positions[voice] = position; + self.fades[voice] = Q14::ZERO; } position = position + period.rescale(); } @@ -977,12 +1057,48 @@ impl Resynthesis { position } + /// Returns `true` if all taps at and after `min_center` in `filtered` match + /// `want_lpc`. + #[inline] + fn filtered_ready_for(&self, min_center: i32, want_lpc: bool) -> bool { + if self.filtered_lpc != want_lpc { + return false; + } + if self.filtered_valid as usize >= HISTORY { + return true; + } + let needed = self.write as i32 - min_center + 2; + needed <= i32::from(self.filtered_valid) + } + + /// Reads a sample from `lead` and outputs zero until fresh frames from + /// `render_lead` arrive. + #[inline] + fn read_lead(&self, position: Q14) -> Q14 { + if self.lead_valid >= HISTORY { + return history::interpolation(&self.lead, position).0; + } + let (sample, center) = history::interpolation(&self.lead, position); + if center > self.write as i32 { + return Q14::ZERO; + } + let margin = self.lead_valid as i32 - (self.write as i32 - center + 2); + if margin < 0 { + Q14::ZERO + } else if margin < 20 { + let gain = Q14::from_bits(((margin + 1) * FADE_STEP.to_bits()).min(Q14::ONE.to_bits())); + sample.mul(gain) + } else { + sample + } + } + /// Renders the choir lead before a secondary voice reads its history. /// /// The function does these steps: /// 1. It selects the period and the ratio. /// 2. It moves the reader and applies the crossfade. - /// 3. If formants are enabled, it applies them and the glottal envelope. + /// 3. If formants are active or in transition, it applies or blends them. /// 4. It stores the Q14 result in the lead history. /// /// Returns the lead sample and its effective ratio, for the modulation @@ -999,15 +1115,26 @@ impl Resynthesis { if ratio != Q14::ZERO { self.periods[delay] = period.div(ratio); } - self.old_position = self.old_position + ratio; - let position = self.move_reader(0, ratio, period, self.delays[0], true); + self.old_positions[0] = self.old_positions[0] + ratio; + let position = self.move_reader(0, ratio, period, self.delays[0]); + let reader_fade = self.fades[0]; + if reader_fade < Q14::ONE { + self.fades[0] = (reader_fade + FADE_STEP).min(Q14::ONE); + } let (mut value, center) = history::interpolation(&self.filtered, position); - if self.fade < Q14::ONE { - let (old, _) = history::interpolation(&self.filtered, self.old_position); - value = value.mul(self.fade) + old.mul(Q14::ONE - self.fade); - self.fade = (self.fade + FADE_STEP).min(Q14::ONE); + let mut min_center = center; + if reader_fade < Q14::ONE { + let (old, old_center) = history::interpolation(&self.filtered, self.old_positions[0]); + value = value.mul(reader_fade) + old.mul(Q14::ONE - reader_fade); + min_center = min_center.min(old_center); } - if self.config.formant.enabled { + let steady_off = !self.config.formant.enabled + && self.formant_fade == Q14::ZERO + && self.filtered_ready_for(min_center, false); + let steady_on = self.config.formant.enabled + && self.formant_fade == Q14::ONE + && self.filtered_ready_for(min_center, true); + if steady_on { self.formant_position = center - FORMANT_OFFSET_FRAMES; value = Q14::from_bits(self.formant.forward( value.to_bits(), @@ -1019,8 +1146,46 @@ impl Resynthesis { .model_glottal(value.to_bits(), self.previous_output[0].to_bits()), ); self.previous_output[0] = value; + } else if !steady_off { + let raw_shift = position_of(OVERLAP_FRAMES as i32); + let (mut raw_value, _) = history::interpolation(&self.raw, position - raw_shift); + if reader_fade < Q14::ONE { + let (old_raw, _) = + history::interpolation(&self.raw, self.old_positions[0] - raw_shift); + raw_value = raw_value.mul(reader_fade) + old_raw.mul(Q14::ONE - reader_fade); + } + let lpc_ready = self.filtered_ready_for(min_center, true); + if self.config.formant.enabled { + if lpc_ready { + self.formant_fade = (self.formant_fade + STAGE_RAMP_STEP).min(Q14::ONE); + } else { + self.formant_fade = Q14::ZERO; + } + } else if lpc_ready && self.formant_fade > Q14::ZERO { + self.formant_fade = (self.formant_fade - STAGE_RAMP_STEP).max(Q14::ZERO); + } else { + self.formant_fade = Q14::ZERO; + } + if lpc_ready && self.formant_fade > Q14::ZERO { + self.formant_position = center - FORMANT_OFFSET_FRAMES; + let mut lpc_value = Q14::from_bits(self.formant.forward( + value.to_bits(), + self.formant_position, + numeric, + )); + lpc_value = Q14::from_bits( + self.formant + .model_glottal(lpc_value.to_bits(), self.previous_output[0].to_bits()), + ); + self.previous_output[0] = lpc_value; + value = + raw_value.mul(Q14::ONE - self.formant_fade) + lpc_value.mul(self.formant_fade); + } else { + value = raw_value; + } } self.lead[write] = value; + self.lead_valid = (self.lead_valid + 1).min(HISTORY); (value, ratio) } @@ -1058,10 +1223,11 @@ impl Resynthesis { } else { 5 }; + let shift = position_of(HISTORY as i32); for voice in 0..voices { - self.positions[voice] = self.positions[voice] - position_of(HISTORY as i32); + self.positions[voice] = self.positions[voice] - shift; + self.old_positions[voice] = self.old_positions[voice] - shift; } - self.old_position = self.old_position - position_of(HISTORY as i32); } if step.restarted { self.correction = Q14::ONE; @@ -1099,6 +1265,27 @@ impl Resynthesis { if self.overlap_index == OVERLAP_FRAMES { self.overlap_index = 0; } + let mut pending_finished = false; + if self.overlap_pending > 0 { + self.overlap_pending -= 1; + if self.overlap_pending == 0 { + pending_finished = true; + } + } + if self.config.formant.enabled != self.was_formant_enabled { + self.was_formant_enabled = self.config.formant.enabled; + if self.overlap_pending > 0 || pending_finished { + self.overlap_mixed = true; + self.filtered_valid = 0; + } + pending_finished = false; + self.overlap_pending = (OVERLAP_FRAMES - ANALYSIS_FRAMES) as u16; + if self.config.formant.enabled { + self.formant + .prepare_enable(&self.raw, write, step.previous_period.to_bits()); + self.previous_output = [Q14::ZERO; 2]; + } + } self.overlap[self.overlap_index] = if self.config.formant.enabled { let previous = self.raw[ring(write as i32 - 1)]; Q14::from_bits(self.formant.process_analysis( @@ -1120,6 +1307,23 @@ impl Resynthesis { filtered = filter.process_sample(filtered); } self.filtered[write] = filtered; + if pending_finished { + self.overlap_mixed = false; + if self.filtered_lpc != self.config.formant.enabled { + self.filtered_lpc = self.config.formant.enabled; + self.filtered_valid = 1; + } else { + self.filtered_valid = self.filtered_valid.saturating_add(1).min(HISTORY as u16); + } + } else if !self.overlap_mixed { + self.filtered_valid = self.filtered_valid.saturating_add(1).min(HISTORY as u16); + } + if self.config.stereo_output && self.stereo_fade < Q14::ONE { + self.stereo_fade = (self.stereo_fade + STAGE_RAMP_STEP).min(Q14::ONE); + } else if !self.config.stereo_output && self.stereo_fade > Q14::ZERO { + self.stereo_fade = (self.stereo_fade - STAGE_RAMP_STEP).max(Q14::ZERO); + } + let stereo_fade = self.stereo_fade; let delayed = ring(write as i32 - OVERLAP_FRAMES as i32); let dry = self.raw[delayed]; let mut mix = [Q14::ZERO; 2]; @@ -1131,13 +1335,9 @@ impl Resynthesis { let (value, ratio) = self.render_lead(delayed, numeric); final_ratio = ratio; self.voice_ratios[0] = ratio; + let panned = apply_pan(value, self.pan[0], stereo_fade); for (channel, sum) in mix.iter_mut().enumerate() { - *sum = *sum - + if self.config.stereo_output { - value.mul(self.pan[0][channel]) - } else { - value - }; + *sum = *sum + panned[channel]; } } { @@ -1153,26 +1353,33 @@ impl Resynthesis { self.current_output_period = period; let ratio = self.drift_ratio[current_voice]; final_ratio = ratio; + self.old_positions[current_voice] = + self.old_positions[current_voice] + ratio; *position = self.move_reader( current_voice, ratio, period, self.delays[current_voice], - false, ); } - let values = - positions.map(|position| history::interpolation(&self.lead, position).0); + let mut values = [Q14::ZERO; 4]; + for (lane, value) in values.iter_mut().enumerate() { + let current_voice = voice + lane; + let mut sample = self.read_lead(positions[lane]); + let fade = self.fades[current_voice]; + if fade < Q14::ONE { + let old = self.read_lead(self.old_positions[current_voice]); + sample = sample.mul(fade) + old.mul(Q14::ONE - fade); + self.fades[current_voice] = (fade + FADE_STEP).min(Q14::ONE); + } + *value = sample; + } // Keep the voice and channel order of each wrapping sum. for (lane, value) in values.into_iter().enumerate() { let current_voice = voice + lane; + let panned = apply_pan(value, self.pan[current_voice], stereo_fade); for (channel, sum) in mix.iter_mut().enumerate() { - *sum = *sum - + if self.config.stereo_output { - value.mul(self.pan[current_voice][channel]) - } else { - value - }; + *sum = *sum + panned[channel]; } } voice += 4; @@ -1185,16 +1392,18 @@ impl Resynthesis { self.current_output_period = period; let ratio = self.drift_ratio[voice]; final_ratio = ratio; - let position = - self.move_reader(voice, ratio, period, self.delays[voice], false); - let (value, _) = history::interpolation(&self.lead, position); + self.old_positions[voice] = self.old_positions[voice] + ratio; + let position = self.move_reader(voice, ratio, period, self.delays[voice]); + let mut value = self.read_lead(position); + let fade = self.fades[voice]; + if fade < Q14::ONE { + let old = self.read_lead(self.old_positions[voice]); + value = value.mul(fade) + old.mul(Q14::ONE - fade); + self.fades[voice] = (fade + FADE_STEP).min(Q14::ONE); + } + let panned = apply_pan(value, self.pan[voice], stereo_fade); for (channel, sum) in mix.iter_mut().enumerate() { - *sum = *sum - + if self.config.stereo_output { - value.mul(self.pan[voice][channel]) - } else { - value - }; + *sum = *sum + panned[channel]; } } } @@ -1203,6 +1412,7 @@ impl Resynthesis { *sum = Q14::ONE.mul(*sum); } } else { + self.lead_valid = 0; let (period, ratio) = self.period_for(delayed, write); self.current_output_period = period; let counter = self.control_counter; @@ -1220,6 +1430,9 @@ impl Resynthesis { self.harmony_gains[voice] = gain; } } + let mut slot_positions = [Q14::ZERO; 5]; + let mut slot_fades = [Q14::ONE; 5]; + let mut min_center = i32::MAX; for slot in 0..5 { let mut current: Q14 = if slot == 0 { ratio @@ -1232,21 +1445,41 @@ impl Resynthesis { } final_ratio = current; self.voice_ratios[slot] = current; - let position = self.move_reader(slot, current, period, 0, false); - let (mut value, _) = history::interpolation(&self.filtered, position); + self.old_positions[slot] = self.old_positions[slot] + current; + let position = self.move_reader(slot, current, period, 0); + let fade = self.fades[slot]; + if fade < Q14::ONE { + self.fades[slot] = (fade + FADE_STEP).min(Q14::ONE); + } + slot_positions[slot] = position; + slot_fades[slot] = fade; + let (mut value, center) = history::interpolation(&self.filtered, position); + min_center = min_center.min(center); + if fade < Q14::ONE { + let (old, old_center) = + history::interpolation(&self.filtered, self.old_positions[slot]); + value = value.mul(fade) + old.mul(Q14::ONE - fade); + min_center = min_center.min(old_center); + } if slot > 0 { value = value.mul(self.harmony_gains[slot - 1]); } + let panned = if slot > 0 { + apply_pan(value, self.harmony_pan[slot - 1], stereo_fade) + } else { + [value, value] + }; for (channel, sum) in mix.iter_mut().enumerate() { - *sum = *sum - + if self.config.stereo_output && slot > 0 { - value.mul(self.harmony_pan[slot - 1][channel]) - } else { - value - }; + *sum = *sum + panned[channel]; } } - if self.config.formant.enabled { + let steady_off = !self.config.formant.enabled + && self.formant_fade == Q14::ZERO + && self.filtered_ready_for(min_center, false); + let steady_on = self.config.formant.enabled + && self.formant_fade == Q14::ONE + && self.filtered_ready_for(min_center, true); + if steady_on { self.formant_position = (self.positions[0].to_bits() >> 14) - FORMANT_OFFSET_FRAMES; mix = self .formant @@ -1260,6 +1493,61 @@ impl Resynthesis { )); self.previous_output[channel] = *value; } + } else if !steady_off { + let raw_shift = position_of(OVERLAP_FRAMES as i32); + let mut raw_mix = [Q14::ZERO; 2]; + for slot in 0..5 { + let (mut value, _) = + history::interpolation(&self.raw, slot_positions[slot] - raw_shift); + let fade = slot_fades[slot]; + if fade < Q14::ONE { + let (old, _) = + history::interpolation(&self.raw, self.old_positions[slot] - raw_shift); + value = value.mul(fade) + old.mul(Q14::ONE - fade); + } + if slot > 0 { + value = value.mul(self.harmony_gains[slot - 1]); + } + let panned = if slot > 0 { + apply_pan(value, self.harmony_pan[slot - 1], stereo_fade) + } else { + [value, value] + }; + for (channel, sum) in raw_mix.iter_mut().enumerate() { + *sum = *sum + panned[channel]; + } + } + let lpc_ready = self.filtered_ready_for(min_center, true); + if self.config.formant.enabled { + if lpc_ready { + self.formant_fade = (self.formant_fade + STAGE_RAMP_STEP).min(Q14::ONE); + } else { + self.formant_fade = Q14::ZERO; + } + } else if lpc_ready && self.formant_fade > Q14::ZERO { + self.formant_fade = (self.formant_fade - STAGE_RAMP_STEP).max(Q14::ZERO); + } else { + self.formant_fade = Q14::ZERO; + } + if lpc_ready && self.formant_fade > Q14::ZERO { + self.formant_position = + (self.positions[0].to_bits() >> 14) - FORMANT_OFFSET_FRAMES; + let mut lpc_mix = self + .formant + .forward_stereo(mix.map(Q14::to_bits), self.formant_position, numeric) + .map(Q14::from_bits); + for (channel, value) in lpc_mix.iter_mut().enumerate() { + *value = Q14::from_bits(self.formant.model_glottal( + value.to_bits(), + self.previous_output[channel].to_bits(), + )); + self.previous_output[channel] = *value; + mix[channel] = raw_mix[channel].mul(Q14::ONE - self.formant_fade) + + (*value).mul(self.formant_fade); + } + } else { + mix = raw_mix; + } } } if self.modulation != 0 { From 6856a990fced51ca0d6b50babb7fb34e29f870b8 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 09:35:39 +0000 Subject: [PATCH 2/7] fix(formant): filter transition audio and ramp aspiration During formant transitions, the raw fallback path bypassed the anti-alias filters, and `Formant::add_noise` stopped aspiration on frame zero of disable. - Apply the `post` anti-alias filters to delayed `raw` taps during formant transitions. - Wait for settled `post` filter states before a reader returns to `filtered`. - Keep aspiration active until `formant_fade` decreases to zero. --- src/formant.rs | 2 +- src/resynthesis.rs | 131 +++++++++++++++++++++++++++++++-------------- 2 files changed, 91 insertions(+), 42 deletions(-) diff --git a/src/formant.rs b/src/formant.rs index a895090..973649c 100644 --- a/src/formant.rs +++ b/src/formant.rs @@ -742,7 +742,7 @@ impl Formant { /// 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.enabled || self.config.aspiration_mix <= 0.01 { + if self.config.aspiration_mix <= 0.01 { return sample; } let random = context.random.next_u31() >> 17; diff --git a/src/resynthesis.rs b/src/resynthesis.rs index b6801d5..65bed68 100644 --- a/src/resynthesis.rs +++ b/src/resynthesis.rs @@ -346,6 +346,12 @@ const DRIFT_LIMIT: Q14 = Q14::from_bits(3276); const FADE_STEP: Q14 = Q14::from_bits(0x333); /// The step for each frame of a 256-frame stage ramp (`16384 / 256`). const STAGE_RAMP_STEP: Q14 = Q14::from_bits(64); +/// The number of input frames that warm the anti-alias filters during a +/// formant transition. +const POST_WARMUP_FRAMES: i32 = 128; +/// The `filtered_valid` count when all ring entries and anti-alias filter +/// states are settled. +const FILTERED_SETTLED: u16 = HISTORY as u16 + POST_WARMUP_FRAMES as u16; /// Returns the stereo pair for one voice sample and its Q14 pan weights. #[inline] @@ -595,7 +601,7 @@ impl Resynthesis { overlap_pending: 0, overlap_mixed: false, filtered_lpc: config.formant.enabled, - filtered_valid: HISTORY as u16, + filtered_valid: FILTERED_SETTLED, formant_fade: if config.formant.enabled { Q14::ONE } else { @@ -833,7 +839,7 @@ impl Resynthesis { self.overlap_pending = 0; self.overlap_mixed = false; self.filtered_lpc = self.config.formant.enabled; - self.filtered_valid = HISTORY as u16; + self.filtered_valid = FILTERED_SETTLED; self.formant_fade = if self.config.formant.enabled { Q14::ONE } else { @@ -1146,18 +1152,66 @@ impl Resynthesis { } } - /// Returns `true` if all taps at and after `min_center` in `filtered` match - /// `want_lpc`. + /// Returns `true` if the three interpolation taps around `center` in + /// `filtered` match `want_lpc` with settled anti-alias filter state. #[inline] - fn filtered_ready_for(&self, min_center: i32, want_lpc: bool) -> bool { + fn filtered_tap_ready(&self, center: i32, want_lpc: bool) -> bool { if self.filtered_lpc != want_lpc { return false; } - if self.filtered_valid as usize >= HISTORY { + let warmup = if self.config.pitch_ratio > 1.0 { + POST_WARMUP_FRAMES as usize + } else { + 0 + }; + let valid = usize::from(self.filtered_valid).saturating_sub(warmup); + if valid >= HISTORY { return true; } - let needed = self.write as i32 - min_center + 2; - needed <= i32::from(self.filtered_valid) + let age_minus = (self.write + HISTORY - ring(center.wrapping_sub(1))) % HISTORY; + let age_plus = (self.write + HISTORY - ring(center.wrapping_add(1))) % HISTORY; + age_minus < valid && age_plus < valid + } + + /// Interpolates the delayed raw history at `position` with the anti-alias + /// filter rules of `filtered`. + fn interpolate_raw_filtered(&self, position: Q14) -> Q14 { + let bits = position.to_bits(); + let center = history::center(position); + let fraction = Q14::from_bits(bits.wrapping_sub(center.wrapping_shl(14))); + let raw_center = center.wrapping_sub(OVERLAP_FRAMES as i32); + if self.config.pitch_ratio > 1.0 { + let mut filters = self.post.clone(); + for filter in &mut filters { + filter.reset(); + } + let mut left = Q14::ZERO; + let mut middle = Q14::ZERO; + let mut right = Q14::ZERO; + for offset in -POST_WARMUP_FRAMES..=1 { + let mut sample = self.raw[ring(raw_center.wrapping_add(offset))]; + for filter in &mut filters { + sample = filter.process_sample(sample); + } + match offset { + -1 => left = sample, + 0 => middle = sample, + 1 => right = sample, + _ => {} + } + } + quadratic(left, middle, right, fraction) + } else { + let bypass = |sample: Q14| { + let mut filters = [Biquad::new(), Biquad::new()]; + let first = filters[0].bypass_sample(sample); + filters[1].bypass_sample(first) + }; + let left = bypass(self.raw[ring(raw_center.wrapping_sub(1))]); + let middle = bypass(self.raw[ring(raw_center)]); + let right = bypass(self.raw[ring(raw_center.wrapping_add(1))]); + quadratic(left, middle, right, fraction) + } } /// Reads a sample from `lead` and outputs zero until fresh frames from @@ -1211,18 +1265,16 @@ impl Resynthesis { self.fades[0] = (reader_fade + FADE_STEP).min(Q14::ONE); } let (mut value, center) = history::interpolation(&self.filtered, position); - let mut min_center = center; + let mut raw_ready = self.filtered_tap_ready(center, false); + let mut lpc_ready = self.filtered_tap_ready(center, true); if reader_fade < Q14::ONE { let (old, old_center) = history::interpolation(&self.filtered, self.old_positions[0]); value = value.mul(reader_fade) + old.mul(Q14::ONE - reader_fade); - min_center = min_center.min(old_center); + raw_ready &= self.filtered_tap_ready(old_center, false); + lpc_ready &= self.filtered_tap_ready(old_center, true); } - let steady_off = !self.config.formant.enabled - && self.formant_fade == Q14::ZERO - && self.filtered_ready_for(min_center, false); - let steady_on = self.config.formant.enabled - && self.formant_fade == Q14::ONE - && self.filtered_ready_for(min_center, true); + let steady_off = self.formant_fade == Q14::ZERO && raw_ready; + let steady_on = self.config.formant.enabled && self.formant_fade == Q14::ONE && lpc_ready; if steady_on { self.formant_position = center - FORMANT_OFFSET_FRAMES; value = Q14::from_bits(self.formant.forward( @@ -1236,14 +1288,11 @@ impl Resynthesis { ); self.previous_output[0] = value; } else if !steady_off { - let raw_shift = position_of(OVERLAP_FRAMES as i32); - let (mut raw_value, _) = history::interpolation(&self.raw, position - raw_shift); + let mut raw_value = self.interpolate_raw_filtered(position); if reader_fade < Q14::ONE { - let (old_raw, _) = - history::interpolation(&self.raw, self.old_positions[0] - raw_shift); + let old_raw = self.interpolate_raw_filtered(self.old_positions[0]); raw_value = raw_value.mul(reader_fade) + old_raw.mul(Q14::ONE - reader_fade); } - let lpc_ready = self.filtered_ready_for(min_center, true); if self.config.formant.enabled { if lpc_ready { self.formant_fade = (self.formant_fade + STAGE_RAMP_STEP).min(Q14::ONE); @@ -1412,10 +1461,10 @@ impl Resynthesis { self.filtered_lpc = self.config.formant.enabled; self.filtered_valid = 1; } else { - self.filtered_valid = self.filtered_valid.saturating_add(1).min(HISTORY as u16); + self.filtered_valid = self.filtered_valid.saturating_add(1).min(FILTERED_SETTLED); } } else if !self.overlap_mixed { - self.filtered_valid = self.filtered_valid.saturating_add(1).min(HISTORY as u16); + self.filtered_valid = self.filtered_valid.saturating_add(1).min(FILTERED_SETTLED); } if self.config.stereo_output && self.stereo_fade < Q14::ONE { self.stereo_fade = (self.stereo_fade + STAGE_RAMP_STEP).min(Q14::ONE); @@ -1528,7 +1577,8 @@ impl Resynthesis { let bounds = self.reader_bounds(period, 0); let mut slot_positions = [Q14::ZERO; 5]; let mut slot_fades = [Q14::ONE; 5]; - let mut min_center = i32::MAX; + let mut raw_ready = true; + let mut lpc_ready = true; for slot in 0..5 { let mut current: Q14 = if slot == 0 { ratio @@ -1552,21 +1602,27 @@ impl Resynthesis { // If the voice adds zero to the two channels, do not read the // audio history. if slot > 0 && self.is_harmony_voice_silent(slot - 1, stereo_fade) { - if (self.filtered_valid as usize) < HISTORY { - min_center = min_center.min(history::center(position)); + if self.filtered_valid < FILTERED_SETTLED { + let center = history::center(position); + raw_ready &= self.filtered_tap_ready(center, false); + lpc_ready &= self.filtered_tap_ready(center, true); if fade < Q14::ONE { - min_center = min_center.min(history::center(self.old_positions[slot])); + let old_center = history::center(self.old_positions[slot]); + raw_ready &= self.filtered_tap_ready(old_center, false); + lpc_ready &= self.filtered_tap_ready(old_center, true); } } continue; } let (mut value, center) = history::interpolation(&self.filtered, position); - min_center = min_center.min(center); + raw_ready &= self.filtered_tap_ready(center, false); + lpc_ready &= self.filtered_tap_ready(center, true); if fade < Q14::ONE { let (old, old_center) = history::interpolation(&self.filtered, self.old_positions[slot]); value = value.mul(fade) + old.mul(Q14::ONE - fade); - min_center = min_center.min(old_center); + raw_ready &= self.filtered_tap_ready(old_center, false); + lpc_ready &= self.filtered_tap_ready(old_center, true); } let panned = if slot > 0 { value = value.mul(self.harmony_gains[slot - 1]); @@ -1583,12 +1639,9 @@ impl Resynthesis { *sum = *sum + panned[channel]; } } - let steady_off = !self.config.formant.enabled - && self.formant_fade == Q14::ZERO - && self.filtered_ready_for(min_center, false); - let steady_on = self.config.formant.enabled - && self.formant_fade == Q14::ONE - && self.filtered_ready_for(min_center, true); + let steady_off = self.formant_fade == Q14::ZERO && raw_ready; + let steady_on = + self.config.formant.enabled && self.formant_fade == Q14::ONE && lpc_ready; if steady_on { self.formant_position = (self.positions[0].to_bits() >> 14) - FORMANT_OFFSET_FRAMES; mix = self @@ -1604,18 +1657,15 @@ impl Resynthesis { self.previous_output[channel] = *value; } } else if !steady_off { - let raw_shift = position_of(OVERLAP_FRAMES as i32); let mut raw_mix = [Q14::ZERO; 2]; for slot in 0..5 { if slot > 0 && self.is_harmony_voice_silent(slot - 1, stereo_fade) { continue; } - let (mut value, _) = - history::interpolation(&self.raw, slot_positions[slot] - raw_shift); + let mut value = self.interpolate_raw_filtered(slot_positions[slot]); let fade = slot_fades[slot]; if fade < Q14::ONE { - let (old, _) = - history::interpolation(&self.raw, self.old_positions[slot] - raw_shift); + let old = self.interpolate_raw_filtered(self.old_positions[slot]); value = value.mul(fade) + old.mul(Q14::ONE - fade); } let panned = if slot > 0 { @@ -1633,7 +1683,6 @@ impl Resynthesis { *sum = *sum + panned[channel]; } } - let lpc_ready = self.filtered_ready_for(min_center, true); if self.config.formant.enabled { if lpc_ready { self.formant_fade = (self.formant_fade + STAGE_RAMP_STEP).min(Q14::ONE); From fa9c4b4dc3b2fa3a58b9d7ac054bcef2263ea718 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:17:24 +0000 Subject: [PATCH 3/7] perf(resynthesis): keep persistent filtered raw history - Filter delayed raw input through persistent biquads - Read raw transition taps without per-lookup warmups - Pause the raw filter path when formants settle off --- src/resynthesis.rs | 141 ++++++++++++++++++++++++++----------- src/resynthesis/history.rs | 2 +- 2 files changed, 102 insertions(+), 41 deletions(-) diff --git a/src/resynthesis.rs b/src/resynthesis.rs index b543c87..82857ae 100644 --- a/src/resynthesis.rs +++ b/src/resynthesis.rs @@ -429,6 +429,8 @@ pub(crate) struct Resynthesis { /// The delayed source audio after the two prepared shift filters. If /// formants are enabled, the source is inverse-filtered. filtered: Box<[Q14; HISTORY]>, + /// The delayed raw audio after `raw_post`, for formant transitions. + raw_filtered: Box<[Q14; HISTORY]>, /// The history of the rendered choir lead. All secondary choir voices /// read this history. lead: Box<[Q14; HISTORY]>, @@ -481,6 +483,8 @@ pub(crate) struct Resynthesis { /// Two cascaded anti-alias filter sections. If the shift is not upward, /// they have coefficients of 1.0 and zero. post: [Biquad; 2], + /// Two anti-alias filter sections that track the delayed raw audio. + raw_post: [Biquad; 2], /// The current smoothed Q14 correction ratio. It does not include the /// global shift or the voice ratios. correction: Q14, @@ -526,6 +530,12 @@ pub(crate) struct Resynthesis { filtered_lpc: bool, /// The number of recent contiguous frames in `filtered` of `filtered_lpc`. filtered_valid: u16, + /// The number of recent contiguous frames in `raw_filtered`. + raw_filtered_valid: u16, + /// `true` while `raw_filtered` advances each frame. + raw_filtered_active: bool, + /// `true` if `raw_filtered` holds data since construction or reset. + raw_filtered_dirty: bool, /// The Q14 crossfade weight of LPC synthesis, in 0..=1. formant_fade: Q14, /// The Q14 ramp weight of the stereo pan, in 0..=1. @@ -568,6 +578,7 @@ impl Resynthesis { harmony: HarmonyState::new(rate, config.harmony), scale: CorrectionTable::new(rate, config.correction.notes), filtered: prepare_history(Q14::ZERO), + raw_filtered: prepare_history(Q14::ZERO), lead: prepare_history(Q14::ZERO), periods: prepare_history(Q6::ZERO), previous_periods: prepare_history(Q6::ZERO), @@ -586,6 +597,7 @@ impl Resynthesis { voice_ratios: [Q14::ONE; HARMONY_VOICES + 1], formant_position: 0, post: [Biquad::new(), Biquad::new()], + raw_post: [Biquad::new(), Biquad::new()], correction: Q14::ONE, correction_decay: Q14::ZERO, scale_initialized: false, @@ -604,6 +616,13 @@ impl Resynthesis { overlap_mixed: false, filtered_lpc: config.formant.enabled, filtered_valid: FILTERED_SETTLED, + raw_filtered_valid: if config.formant.enabled { + HISTORY as u16 + } else { + 0 + }, + raw_filtered_active: config.formant.enabled, + raw_filtered_dirty: false, formant_fade: if config.formant.enabled { Q14::ONE } else { @@ -686,12 +705,21 @@ impl Resynthesis { /// truncates the numerator of the cutoff before it divides by the pitch /// ratio. fn configure_shift_filters(&mut self) { - for filter in &mut self.post { - if self.config.pitch_ratio > 1.0 { - let numerator = (self.rate.hz() as f64 * 0.49) as i32; - let cutoff = numerator as f32 / self.config.pitch_ratio; - filter.set_design(Design::low_pass(self.rate.hz(), cutoff, 0.707)); - } else { + if self.config.pitch_ratio > 1.0 { + let numerator = (self.rate.hz() as f64 * 0.49) as i32; + let cutoff = numerator as f32 / self.config.pitch_ratio; + let design = Design::low_pass(self.rate.hz(), cutoff, 0.707); + for filter in &mut self.post { + filter.set_design(design); + } + for filter in &mut self.raw_post { + filter.set_design(design); + } + } else { + for filter in &mut self.post { + filter.bypass(); + } + for filter in &mut self.raw_post { filter.bypass(); } } @@ -793,6 +821,10 @@ impl Resynthesis { self.pitch.reset(); clear_dirty_ring(self.raw.as_mut_slice(), written, Q14::ZERO); clear_dirty_ring(self.filtered.as_mut_slice(), written, Q14::ZERO); + if self.raw_filtered_dirty { + clear_dirty_ring(self.raw_filtered.as_mut_slice(), written, Q14::ZERO); + self.raw_filtered_dirty = false; + } clear_dirty_ring(self.lead.as_mut_slice(), written, Q14::ZERO); if written > 0 { let lead_start = HISTORY - OVERLAP_FRAMES + 1; @@ -817,6 +849,9 @@ impl Resynthesis { for filter in &mut self.post { filter.reset(); } + for filter in &mut self.raw_post { + filter.reset(); + } self.create_delays(); self.drift_ratio.fill(Q14::ONE); self.old_positions = self.positions; @@ -831,6 +866,12 @@ impl Resynthesis { self.overlap_mixed = false; self.filtered_lpc = self.config.formant.enabled; self.filtered_valid = FILTERED_SETTLED; + self.raw_filtered_valid = if self.config.formant.enabled { + HISTORY as u16 + } else { + 0 + }; + self.raw_filtered_active = self.config.formant.enabled; self.formant_fade = if self.config.formant.enabled { Q14::ONE } else { @@ -1179,44 +1220,33 @@ impl Resynthesis { } /// Interpolates the delayed raw history at `position` with the anti-alias - /// filter rules of `filtered`. + /// filter state of `raw_filtered`. + #[inline] fn interpolate_raw_filtered(&self, position: Q14) -> Q14 { + let valid = usize::from(self.raw_filtered_valid); + if valid >= HISTORY { + return history::interpolation(&self.raw_filtered, position).0; + } + if !self.raw_filtered_active { + return history::interpolation(&self.filtered, position).0; + } let bits = position.to_bits(); let center = history::center(position); let fraction = Q14::from_bits(bits.wrapping_sub(center.wrapping_shl(14))); - let raw_center = center.wrapping_sub(OVERLAP_FRAMES as i32); - if self.config.pitch_ratio > 1.0 { - let mut filters = self.post.clone(); - for filter in &mut filters { - filter.reset(); - } - let mut left = Q14::ZERO; - let mut middle = Q14::ZERO; - let mut right = Q14::ZERO; - for offset in -POST_WARMUP_FRAMES..=1 { - let mut sample = self.raw[ring(raw_center.wrapping_add(offset))]; - for filter in &mut filters { - sample = filter.process_sample(sample); - } - match offset { - -1 => left = sample, - 0 => middle = sample, - 1 => right = sample, - _ => {} - } - } - quadratic(left, middle, right, fraction) - } else { - let bypass = |sample: Q14| { - let mut filters = [Biquad::new(), Biquad::new()]; - let first = filters[0].bypass_sample(sample); - filters[1].bypass_sample(first) + let [left_idx, middle_idx, right_idx] = history::interpolation_indices(center); + let tap = |index: usize| { + let age = if self.write >= index { + self.write - index + } else { + self.write + HISTORY - index }; - let left = bypass(self.raw[ring(raw_center.wrapping_sub(1))]); - let middle = bypass(self.raw[ring(raw_center)]); - let right = bypass(self.raw[ring(raw_center.wrapping_add(1))]); - quadratic(left, middle, right, fraction) - } + if age < valid { + self.raw_filtered[index] + } else { + self.filtered[index] + } + }; + quadratic(tap(left_idx), tap(middle_idx), tap(right_idx), fraction) } /// Reads a sample from `lead` and outputs zero until fresh frames from @@ -1437,6 +1467,27 @@ impl Resynthesis { } else { self.raw[ring(write as i32 - ANALYSIS_FRAMES as i32)] }; + if self.config.formant.enabled && !self.raw_filtered_active { + self.raw_post = self.post.clone(); + self.raw_filtered_active = true; + self.raw_filtered_valid = 0; + } + let delayed = ring(write as i32 - OVERLAP_FRAMES as i32); + if self.raw_filtered_active { + let mut raw_sample = self.raw[delayed]; + if self.config.pitch_ratio > 1.0 { + for filter in &mut self.raw_post { + raw_sample = filter.process_sample(raw_sample); + } + } else { + for filter in &mut self.raw_post { + raw_sample = filter.bypass_sample(raw_sample); + } + } + self.raw_filtered[write] = raw_sample; + self.raw_filtered_dirty = true; + self.raw_filtered_valid = (self.raw_filtered_valid + 1).min(HISTORY as u16); + } // The inverse analysis adds a delay of ANALYSIS_FRAMES. Read ahead by // the same number of frames in the overlap ring. Then the total delay // of the source is OVERLAP_FRAMES in the two formant modes. @@ -1469,7 +1520,6 @@ impl Resynthesis { self.stereo_fade = (self.stereo_fade - STAGE_RAMP_STEP).max(Q14::ZERO); } let stereo_fade = self.stereo_fade; - let delayed = ring(write as i32 - OVERLAP_FRAMES as i32); let dry = self.raw[ring(write as i32 - LATENCY_FRAMES as i32)]; let mut mix = [Q14::ZERO; 2]; let mut mono = stereo_fade == Q14::ZERO; @@ -1789,6 +1839,17 @@ impl Resynthesis { } } } + if self.raw_filtered_active + && !self.config.formant.enabled + && self.formant_fade == Q14::ZERO + && self.overlap_pending == 0 + && !self.overlap_mixed + && !self.filtered_lpc + && self.filtered_valid == FILTERED_SETTLED + { + self.raw_filtered_active = false; + self.raw_filtered_valid = 0; + } if self.modulation != 0 { if self.current_output_period != Q6::ZERO { // The phase advances by depth x 4 x ratio / period, in Q14 diff --git a/src/resynthesis/history.rs b/src/resynthesis/history.rs index cb65ee7..a2259bf 100644 --- a/src/resynthesis/history.rs +++ b/src/resynthesis/history.rs @@ -60,7 +60,7 @@ pub(crate) fn clear_dirty_ring(buffer: &mut [T], written: usize, value: /// /// The center can be negative or more than one full history length. #[inline] -fn interpolation_indices(center: i32) -> [usize; 3] { +pub(super) fn interpolation_indices(center: i32) -> [usize; 3] { let middle = ring(center); let left = if middle == 0 { HISTORY - 1 } else { middle - 1 }; let right = if middle + 1 == HISTORY { 0 } else { middle + 1 }; From 4903538e549c6475fb764d349744ec4e8366475d 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:25:35 +0000 Subject: [PATCH 4/7] fix(formant): ramp rapid formant toggles without jumps - Track per-slot LPC state and raw lookahead in the overlap ring - Step the formant fade smoothly without single-frame resets - Keep active model banks intact when formants turn on again --- src/formant.rs | 24 ++--- src/resynthesis.rs | 259 +++++++++++++++++++++++++++++++++------------ 2 files changed, 199 insertions(+), 84 deletions(-) diff --git a/src/formant.rs b/src/formant.rs index 32a330d..8380b90 100644 --- a/src/formant.rs +++ b/src/formant.rs @@ -346,19 +346,23 @@ impl Formant { self.input.fill(0_i32); self.stamps.fill(Stamp::default()); - self.history = [[0; MAX_ORDER * 2]; 2]; - self.histories_match = true; - self.history_index = 0; + self.reset_synthesis(); self.current = BANKS - 1; self.next_filter(); self.next_filter(); self.design_counter = 0; - self.noise_filter.reset(); self.smooth_reset = true; self.snap_blend = false; } - /// Prepares the stage when the formant stage becomes active and fills the - /// pre-emphasized input history from `raw`. + /// Clears the synthesis feedback history and the aspiration filter memory. + pub(crate) fn reset_synthesis(&mut self) { + self.history = [[0; MAX_ORDER * 2]; 2]; + self.histories_match = true; + self.history_index = 0; + self.noise_filter.reset(); + } + /// Prepares the analysis history from `raw` when the formant stage becomes + /// active, and keeps active synthesis banks intact. pub(crate) fn prepare_enable(&mut self, raw: &[Q14; HISTORY_FRAMES], write: usize) { self.dirty = true; let max_period = (self.rate.as_u32() as usize / 40).max(1); @@ -380,15 +384,7 @@ impl Formant { self.input[reverse_index + HISTORY_FRAMES] = filtered; } } - self.history = [[0; MAX_ORDER * 2]; 2]; - self.histories_match = true; - self.history_index = 0; - self.orders = [0; BANKS]; - self.current = BANKS - 1; - self.next_filter(); - self.next_filter(); self.design_counter = 0; - self.noise_filter.reset(); self.smooth_reset = true; self.snap_blend = true; } diff --git a/src/resynthesis.rs b/src/resynthesis.rs index 82857ae..8a4c54d 100644 --- a/src/resynthesis.rs +++ b/src/resynthesis.rs @@ -346,8 +346,12 @@ const CONTROL_DUE: i32 = 100; const DRIFT_LIMIT: Q14 = Q14::from_bits(3276); /// The step for each frame of the crossfade after a reader jump. const FADE_STEP: Q14 = Q14::from_bits(0x333); +/// The number of frames in a full Q14 stage ramp (`16384 / 64`). +const FORMANT_RAMP_FRAMES: usize = 256; /// The step for each frame of a 256-frame stage ramp (`16384 / 256`). const STAGE_RAMP_STEP: Q14 = Q14::from_bits(64); +/// The number of `u64` words that store one bit for each `overlap` slot. +const OVERLAP_WORDS: usize = OVERLAP_FRAMES.div_ceil(64); /// The number of input frames that warm the anti-alias filters during a /// formant transition. const POST_WARMUP_FRAMES: i32 = 128; @@ -355,6 +359,17 @@ const POST_WARMUP_FRAMES: i32 = 128; /// states are settled. const FILTERED_SETTLED: u16 = HISTORY as u16 + POST_WARMUP_FRAMES as u16; +/// Returns a bitset where all `OVERLAP_FRAMES` slots are `true`. +#[inline] +fn full_overlap_lpc() -> [u64; OVERLAP_WORDS] { + let mut bits = [!0_u64; OVERLAP_WORDS]; + let tail = OVERLAP_FRAMES & 63; + if tail != 0 { + bits[OVERLAP_WORDS - 1] = (1_u64 << tail) - 1; + } + bits +} + /// Returns the stereo pair for one voice sample and its Q14 pan weights. #[inline] fn apply_pan(value: Q14, pan: [Q14; 2], stereo_fade: Q14) -> [Q14; 2] { @@ -522,10 +537,10 @@ pub(crate) struct Resynthesis { lead_valid: usize, /// The state of `formant.enabled` from the previous frame. was_formant_enabled: bool, - /// The frames that are left before a formant switch reaches `filtered`. - overlap_pending: u16, - /// `true` if `overlap` holds both raw and formant-analyzed frames. - overlap_mixed: bool, + /// A bitset of `overlap` slots that hold formant-analyzed samples. + overlap_lpc: [u64; OVERLAP_WORDS], + /// The count of raw slots in the next `FORMANT_RAMP_FRAMES` of `overlap`. + lookahead_raw: u16, /// `true` if the frames that enter `filtered` come from formant analysis. filtered_lpc: bool, /// The number of recent contiguous frames in `filtered` of `filtered_lpc`. @@ -612,8 +627,16 @@ impl Resynthesis { fades: [Q14::ONE; 16], lead_valid: HISTORY, was_formant_enabled: config.formant.enabled, - overlap_pending: 0, - overlap_mixed: false, + overlap_lpc: if config.formant.enabled { + full_overlap_lpc() + } else { + [0; OVERLAP_WORDS] + }, + lookahead_raw: if config.formant.enabled { + 0 + } else { + FORMANT_RAMP_FRAMES as u16 + }, filtered_lpc: config.formant.enabled, filtered_valid: FILTERED_SETTLED, raw_filtered_valid: if config.formant.enabled { @@ -862,8 +885,16 @@ impl Resynthesis { 0 }; self.was_formant_enabled = self.config.formant.enabled; - self.overlap_pending = 0; - self.overlap_mixed = false; + self.overlap_lpc = if self.config.formant.enabled { + full_overlap_lpc() + } else { + [0; OVERLAP_WORDS] + }; + self.lookahead_raw = if self.config.formant.enabled { + 0 + } else { + FORMANT_RAMP_FRAMES as u16 + }; self.filtered_lpc = self.config.formant.enabled; self.filtered_valid = FILTERED_SETTLED; self.raw_filtered_valid = if self.config.formant.enabled { @@ -1219,6 +1250,44 @@ impl Resynthesis { age_minus < valid && age_plus < valid } + /// Returns `true` if `overlap[slot]` holds a formant-analyzed sample. + #[inline] + fn overlap_is_lpc(&self, slot: usize) -> bool { + ((self.overlap_lpc[slot >> 6] >> (slot & 63)) & 1) != 0 + } + + /// Records whether `overlap[slot]` holds a formant-analyzed sample. + #[inline] + fn set_overlap_lpc(&mut self, slot: usize, is_lpc: bool) { + let mask = 1_u64 << (slot & 63); + if is_lpc { + self.overlap_lpc[slot >> 6] |= mask; + } else { + self.overlap_lpc[slot >> 6] &= !mask; + } + } + + /// Advances `formant_fade` by one ramp step and resets synthesis at the + /// start of a new fade-in. + fn step_formant_fade(&mut self, lpc_ready: bool, lower: Q14) -> Q14 { + let prev = self.formant_fade; + let min_lower = position_of((self.write as i32).wrapping_sub(FORMANT_RAMP_FRAMES as i32)); + let lower_ready = prev > Q14::ZERO + || self.filtered_tap_ready(history::center(lower.min(min_lower)), true); + let next = + if self.config.formant.enabled && self.lookahead_raw == 0 && lpc_ready && lower_ready { + (prev + STAGE_RAMP_STEP).min(Q14::ONE) + } else { + (prev - STAGE_RAMP_STEP).max(Q14::ZERO) + }; + if prev == Q14::ZERO && next > Q14::ZERO { + self.formant.reset_synthesis(); + self.previous_output = [Q14::ZERO; 2]; + } + self.formant_fade = next; + next + } + /// Interpolates the delayed raw history at `position` with the anti-alias /// filter state of `raw_filtered`. #[inline] @@ -1294,22 +1363,32 @@ impl Resynthesis { self.periods[delay] = period.div(ratio); } self.old_positions[0] = self.old_positions[0] + ratio; - let position = self.move_reader(0, ratio, period, self.delays[0]); + let bounds = self.reader_bounds(period, self.delays[0]); + let position = self.step_reader(0, ratio, bounds); let reader_fade = self.fades[0]; if reader_fade < Q14::ONE { self.fades[0] = (reader_fade + FADE_STEP).min(Q14::ONE); } - let (mut value, center) = history::interpolation(&self.filtered, position); + let (new_value, center) = history::interpolation(&self.filtered, position); + let mut value = new_value; let mut raw_ready = self.filtered_tap_ready(center, false); - let mut lpc_ready = self.filtered_tap_ready(center, true); + let new_lpc = self.filtered_tap_ready(center, true); + let mut lpc_ready = new_lpc; + let mut old_value = Q14::ZERO; + let mut old_lpc = true; if reader_fade < Q14::ONE { let (old, old_center) = history::interpolation(&self.filtered, self.old_positions[0]); + old_value = old; value = value.mul(reader_fade) + old.mul(Q14::ONE - reader_fade); raw_ready &= self.filtered_tap_ready(old_center, false); - lpc_ready &= self.filtered_tap_ready(old_center, true); + old_lpc = self.filtered_tap_ready(old_center, true); + lpc_ready &= old_lpc; } let steady_off = self.formant_fade == Q14::ZERO && raw_ready; - let steady_on = self.config.formant.enabled && self.formant_fade == Q14::ONE && lpc_ready; + let steady_on = self.config.formant.enabled + && self.lookahead_raw == 0 + && self.formant_fade == Q14::ONE + && lpc_ready; if steady_on { self.formant_position = center - FORMANT_OFFSET_FRAMES; value = Q14::from_bits(self.formant.forward( @@ -1328,21 +1407,25 @@ impl Resynthesis { let old_raw = self.interpolate_raw_filtered(self.old_positions[0]); raw_value = raw_value.mul(reader_fade) + old_raw.mul(Q14::ONE - reader_fade); } - if self.config.formant.enabled { - if lpc_ready { - self.formant_fade = (self.formant_fade + STAGE_RAMP_STEP).min(Q14::ONE); + let fade = self.step_formant_fade(lpc_ready, bounds.1); + if fade > Q14::ZERO { + let lpc_in = if lpc_ready { + self.formant_position = center - FORMANT_OFFSET_FRAMES; + value } else { - self.formant_fade = Q14::ZERO; - } - } else if lpc_ready && self.formant_fade > Q14::ZERO { - self.formant_fade = (self.formant_fade - STAGE_RAMP_STEP).max(Q14::ZERO); - } else { - self.formant_fade = Q14::ZERO; - } - if lpc_ready && self.formant_fade > Q14::ZERO { - self.formant_position = center - FORMANT_OFFSET_FRAMES; + if new_lpc { + self.formant_position = center - FORMANT_OFFSET_FRAMES; + } + let new_part = if new_lpc { new_value } else { Q14::ZERO }; + if reader_fade < Q14::ONE { + let old_part = if old_lpc { old_value } else { Q14::ZERO }; + new_part.mul(reader_fade) + old_part.mul(Q14::ONE - reader_fade) + } else { + new_part + } + }; let mut lpc_value = Q14::from_bits(self.formant.forward( - value.to_bits(), + lpc_in.to_bits(), self.formant_position, numeric, )); @@ -1351,8 +1434,7 @@ impl Resynthesis { .model_glottal(lpc_value.to_bits(), self.previous_output[0].to_bits()), ); self.previous_output[0] = lpc_value; - value = - raw_value.mul(Q14::ONE - self.formant_fade) + lpc_value.mul(self.formant_fade); + value = raw_value.mul(Q14::ONE - fade) + lpc_value.mul(fade); } else { value = raw_value; } @@ -1431,30 +1513,18 @@ impl Resynthesis { self.periods[write] = step.period; self.previous_periods[write] = step.previous_period; self.ratios[write] = self.correction; + let prev_read = (self.overlap_index + ANALYSIS_FRAMES) % OVERLAP_FRAMES; self.overlap_index += 1; if self.overlap_index == OVERLAP_FRAMES { self.overlap_index = 0; } - let mut pending_finished = false; - if self.overlap_pending > 0 { - self.overlap_pending -= 1; - if self.overlap_pending == 0 { - pending_finished = true; - } - } if self.config.formant.enabled != self.was_formant_enabled { self.was_formant_enabled = self.config.formant.enabled; - if self.overlap_pending > 0 || pending_finished { - self.overlap_mixed = true; - self.filtered_valid = 0; - } - pending_finished = false; - self.overlap_pending = (OVERLAP_FRAMES - ANALYSIS_FRAMES) as u16; if self.config.formant.enabled { self.formant.prepare_enable(&self.raw, write); - self.previous_output = [Q14::ZERO; 2]; } } + self.set_overlap_lpc(self.overlap_index, self.config.formant.enabled); self.overlap[self.overlap_index] = if self.config.formant.enabled { let previous = self.raw[ring(write as i32 - 1)]; Q14::from_bits(self.formant.process_analysis( @@ -1492,6 +1562,14 @@ impl Resynthesis { // the same number of frames in the overlap ring. Then the total delay // of the source is OVERLAP_FRAMES in the two formant modes. let overlap_read = (self.overlap_index + ANALYSIS_FRAMES) % OVERLAP_FRAMES; + if !self.overlap_is_lpc(prev_read) { + self.lookahead_raw -= 1; + } + let lookahead_tail = (prev_read + FORMANT_RAMP_FRAMES) % OVERLAP_FRAMES; + if !self.overlap_is_lpc(lookahead_tail) { + self.lookahead_raw += 1; + } + let slot_lpc = self.overlap_is_lpc(overlap_read); let mut filtered = self.overlap[overlap_read]; if self.config.pitch_ratio > 1.0 { for filter in &mut self.post { @@ -1503,16 +1581,11 @@ impl Resynthesis { } } self.filtered[write] = filtered; - if pending_finished { - self.overlap_mixed = false; - if self.filtered_lpc != self.config.formant.enabled { - self.filtered_lpc = self.config.formant.enabled; - self.filtered_valid = 1; - } else { - self.filtered_valid = self.filtered_valid.saturating_add(1).min(FILTERED_SETTLED); - } - } else if !self.overlap_mixed { + if self.filtered_lpc == slot_lpc { self.filtered_valid = self.filtered_valid.saturating_add(1).min(FILTERED_SETTLED); + } else { + self.filtered_lpc = slot_lpc; + self.filtered_valid = 1; } if self.config.stereo_output && self.stereo_fade < Q14::ONE { self.stereo_fade = (self.stereo_fade + STAGE_RAMP_STEP).min(Q14::ONE); @@ -1710,8 +1783,10 @@ impl Resynthesis { } } let steady_off = self.formant_fade == Q14::ZERO && raw_ready; - let steady_on = - self.config.formant.enabled && self.formant_fade == Q14::ONE && lpc_ready; + let steady_on = self.config.formant.enabled + && self.lookahead_raw == 0 + && self.formant_fade == Q14::ONE + && lpc_ready; if steady_on { self.formant_position = (self.positions[0].to_bits() >> 14) - FORMANT_OFFSET_FRAMES; // If Choir changed only channel zero before a switch to @@ -1784,20 +1859,66 @@ impl Resynthesis { } } } - if self.config.formant.enabled { + let fade = self.step_formant_fade(lpc_ready, bounds.1); + if fade > Q14::ZERO { + let lead_center = self.positions[0].to_bits() >> 14; if lpc_ready { - self.formant_fade = (self.formant_fade + STAGE_RAMP_STEP).min(Q14::ONE); + self.formant_position = lead_center - FORMANT_OFFSET_FRAMES; } else { - self.formant_fade = Q14::ZERO; + if self.filtered_tap_ready(history::center(self.positions[0]), true) { + self.formant_position = lead_center - FORMANT_OFFSET_FRAMES; + } + mix = [Q14::ZERO; 2]; + for slot in 0..5 { + if slot > 0 && self.is_harmony_voice_silent(slot - 1, stereo_fade) { + continue; + } + let (new_val, new_c) = + history::interpolation(&self.filtered, slot_positions[slot]); + let new_part = if self.filtered_tap_ready(new_c, true) { + new_val + } else { + Q14::ZERO + }; + let vfade = slot_fades[slot]; + let mut value = if vfade < Q14::ONE { + let (old_val, old_c) = history::interpolation( + &self.filtered, + self.old_positions[slot], + ); + let old_part = if self.filtered_tap_ready(old_c, true) { + old_val + } else { + Q14::ZERO + }; + new_part.mul(vfade) + old_part.mul(Q14::ONE - vfade) + } else { + new_part + }; + if mono { + if slot > 0 { + value = value.mul(self.harmony_gains[slot - 1]); + value = value.mul(self.harmony_gain); + } + mix[0] = mix[0] + value; + } else { + let panned = if slot > 0 { + value = value.mul(self.harmony_gains[slot - 1]); + apply_harmony_pan( + value, + self.harmony_gain, + self.harmony_pan[slot - 1], + stereo_fade, + ) + } else { + [value, value] + }; + for (channel, sum) in mix.iter_mut().enumerate() { + *sum = *sum + panned[channel]; + } + } + } } - } else if lpc_ready && self.formant_fade > Q14::ZERO { - self.formant_fade = (self.formant_fade - STAGE_RAMP_STEP).max(Q14::ZERO); - } else { - self.formant_fade = Q14::ZERO; - } - if lpc_ready && self.formant_fade > Q14::ZERO { - self.formant_position = - (self.positions[0].to_bits() >> 14) - FORMANT_OFFSET_FRAMES; if mono && self.formant.histories_match() && self.previous_output[0] == self.previous_output[1] @@ -1812,8 +1933,7 @@ impl Resynthesis { .model_glottal(value.to_bits(), self.previous_output[0].to_bits()), ); self.previous_output = [value; 2]; - mix[0] = raw_mix[0].mul(Q14::ONE - self.formant_fade) - + value.mul(self.formant_fade); + mix[0] = raw_mix[0].mul(Q14::ONE - fade) + value.mul(fade); } else { if mono { mix[1] = mix[0]; @@ -1829,8 +1949,8 @@ impl Resynthesis { self.previous_output[channel].to_bits(), )); self.previous_output[channel] = *value; - mix[channel] = raw_mix[channel].mul(Q14::ONE - self.formant_fade) - + (*value).mul(self.formant_fade); + mix[channel] = + raw_mix[channel].mul(Q14::ONE - fade) + (*value).mul(fade); } mono = mono && mix[0] == mix[1]; } @@ -1842,8 +1962,7 @@ impl Resynthesis { if self.raw_filtered_active && !self.config.formant.enabled && self.formant_fade == Q14::ZERO - && self.overlap_pending == 0 - && !self.overlap_mixed + && self.overlap_lpc == [0; OVERLAP_WORDS] && !self.filtered_lpc && self.filtered_valid == FILTERED_SETTLED { From 7b7741feefcadf689a895dd5b52718222b373731 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:31:48 +0000 Subject: [PATCH 5/7] docs: describe active transition budgets in tail_frames - Document transition ramps and bypass tails in tail_frames - Update the Wasm tailFrames documentation and README table --- README.md | 2 +- src/lib.rs | 5 +++-- src/processor.rs | 11 ++++++----- src/wasm.rs | 7 +++++-- 4 files changed, 15 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 4b96625..9ceb4b9 100644 --- a/README.md +++ b/README.md @@ -440,7 +440,7 @@ page that opens the JavaScript. | Telemetry | `telemetry()`, `takeTelemetry()` | | Formant envelopes | `formantEnvelope(maxFrequencyHz, input, output)` | | Finite tail | `beginDrain()`, `drain(left, right)`, `drainMono(audio)` | -| Configured tail budget | `tailFrames()` | +| Tail budget | `tailFrames()` | | Reset or release memory | `reset()`, `free()` | ### Audio buffers diff --git a/src/lib.rs b/src/lib.rs index 34a4ba9..2514e8e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -68,8 +68,9 @@ //! //! After the last input block, call [`Processor::begin_drain`] one time. Then //! render drain blocks until a call returns zero. Each call fills the unused -//! output with zeros. The drain uses a finite configured budget and mutes -//! aspiration. It is not a silence detector. +//! output with zeros. The drain uses the finite budget from +//! [`Processor::tail_frames`] and mutes aspiration. It is not a silence +//! detector. //! //! The call that uses all of the budget does the same reset as //! [`Processor::reset`]. This occurs also if that call returns audio. A diff --git a/src/processor.rs b/src/processor.rs index 39d2d52..ec98c8e 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -311,12 +311,13 @@ impl Processor { Ok(count) } - /// Returns the finite tail budget for the current configuration. + /// Returns the finite tail budget for the current configuration and active + /// stage transitions. /// - /// This value is a configured limit. It is not the number of drain frames - /// that are left, and it is not a measured decay time. It can include - /// silence. It can also stop filter output that continues for a long - /// time. + /// The budget includes active Alien ramps, reverb mode fades and reverb + /// bypass tails. It is not the number of drain frames that are left. It is + /// not a measured decay time. It can include silence. It can also stop + /// filter output that continues for a long time. pub fn tail_frames(&self) -> usize { self.resynthesis .tail_frames() diff --git a/src/wasm.rs b/src/wasm.rs index 4b7abee..9c52f80 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -324,8 +324,11 @@ impl WasmProcessor { self.processor.begin_drain() } - /// Returns the tail budget of the current configuration, not the remaining - /// drain count. + /// Returns the finite tail budget for the current configuration and active + /// stage transitions. + /// + /// This value includes active Alien ramps, reverb mode fades and reverb + /// bypass tails. It is not the number of drain frames that are left. #[wasm_bindgen(js_name = tailFrames)] pub fn tail_frames(&self) -> usize { self.processor.tail_frames() From 6c01ae2adc13ae560bae113877b3600294df62b8 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:02:55 +0000 Subject: [PATCH 6/7] fix(alien): keep active loop length across wet fade-out - Hold active_loop_len constant while wet_frames is above zero. - Ramp active wet playback to zero before a new loop length applies. - Count post-enable input during loop-length fades without stale reads. - Update AlienConfig and Telemetry loop documentation. --- src/effects/alien.rs | 130 ++++++++++++++++++++++--------------------- src/processor.rs | 6 +- 2 files changed, 72 insertions(+), 64 deletions(-) diff --git a/src/effects/alien.rs b/src/effects/alien.rs index fd6369b..01b0975 100644 --- a/src/effects/alien.rs +++ b/src/effects/alien.rs @@ -24,10 +24,12 @@ fn boundary_fade_frames(loop_frames: usize) -> usize { /// Alien comes after resynthesis. When you enable Alien, it captures one loop /// of fresh input while it holds the dry signal. Then it ramps the wet mix to /// full level over 200 frames. When you disable Alien, it ramps the wet mix to -/// zero over 200 frames. A change of the loop length keeps the captured history -/// and clamps the current phase into the new loop. The boundary fade length is -/// zero at a loop length of one frame, and `min(200, loop_frames / 2)` at -/// longer loop lengths. +/// zero over 200 frames. +/// +/// If the loop length changes during wet playback, Alien ramps the active loop +/// to zero over 200 frames. Then it resets the phase and captures any extra +/// frames that the new loop needs. The boundary fade length is zero at a loop +/// length of one frame, and `min(200, loop_frames / 2)` at longer loop lengths. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] #[cfg_attr( @@ -80,19 +82,21 @@ pub(crate) struct Alien { /// The current write position. The position of the reverse reader comes /// from this cursor. read: usize, - /// The current frame in the loop. It is always less than `loop_len`. + /// The current frame in the loop. It is always less than + /// `active_loop_len`. phase: usize, - /// The validated loop length. It is not more than half of the history - /// capacity. - loop_len: usize, + /// The active loop length. It stays constant until `wet_frames` is zero. + active_loop_len: usize, /// The number of frames in `buffer` since construction or the last reset. written: usize, /// The number of frames that Alien captured since it became active. captured: usize, /// The current frame in the 200-frame wet mix ramp, in 0..=200. wet_frames: usize, - /// If `true`, the wet mix ramps to zero before a new capture starts. - restart_pending: bool, + /// If `true`, the wet mix ramps to zero before the next loop state starts. + fading_out: bool, + /// If `true`, `captured` resets to zero when `wet_frames` reaches zero. + reset_capture: bool, } impl Alien { /// Allocates a silent stereo ring from validated loop settings. @@ -107,50 +111,57 @@ impl Alien { buffer: vec![[Q14::default(); 2]; HISTORY_FRAMES], read: 0, phase: 0, - loop_len: config.loop_frames as usize, + active_loop_len: config.loop_frames as usize, written: 0, captured, wet_frames, - restart_pending: false, + fading_out: false, + reset_capture: false, } } /// Applies a validated configuration and does not clear the buffer. /// - /// If you enable Alien, this method resets the loop phase and the captured - /// frame count. It also clamps the phase into the new loop, which is not - /// empty. + /// While `wet_frames` is above zero, `active_loop_len` stays unchanged + /// until the wet ramp reaches zero. pub(crate) fn set_config(&mut self, config: AlienConfig) { let was_enabled = self.config.enabled; self.config = config; - self.loop_len = config.loop_frames as usize; - self.phase = self.phase.min(self.loop_len - 1); - if !was_enabled && config.enabled { + if !config.enabled || !was_enabled { if self.wet_frames == 0 { + self.active_loop_len = config.loop_frames as usize; self.phase = 0; self.captured = 0; - self.restart_pending = false; + self.fading_out = false; + self.reset_capture = false; } else { - self.restart_pending = true; - } - } else if was_enabled && config.enabled { - if self.captured < self.loop_len && self.wet_frames > 0 { - self.restart_pending = true; + self.fading_out = true; + self.reset_capture = true; } - } else if !config.enabled { - self.restart_pending = false; + } else if self.wet_frames == 0 { + self.active_loop_len = config.loop_frames as usize; + self.phase = 0; + self.fading_out = false; + } else { + self.fading_out = + self.reset_capture || config.loop_frames as usize != self.active_loop_len; } } - /// Returns the loop length and the current frame in the loop. + /// Returns the active loop length and the current frame in the loop. /// /// The frame is always less than the length. The stage state does not /// change. pub(crate) fn loop_state(&self) -> (usize, usize) { - (self.loop_len, self.phase) + (self.active_loop_len, self.phase) } /// Returns the finite tail budget for the active state or an active ramp. pub(crate) fn tail_frames(&self) -> usize { if self.config.enabled { - 2 * self.config.loop_frames as usize + FADE_FRAMES + let base = 2 * self.config.loop_frames as usize + FADE_FRAMES; + if self.fading_out { + base.saturating_add(self.wet_frames) + } else { + base + } } else { self.wet_frames } @@ -162,6 +173,7 @@ impl Alien { self.written = 0; self.read = 0; self.phase = 0; + self.active_loop_len = self.config.loop_frames as usize; if self.config.enabled { self.captured = HISTORY_FRAMES; self.wet_frames = FADE_FRAMES; @@ -169,7 +181,8 @@ impl Alien { self.captured = 0; self.wet_frames = 0; } - self.restart_pending = false; + self.fading_out = false; + self.reset_capture = false; } /// Reads the current reverse frame and applies the loop boundary fade. #[inline] @@ -180,8 +193,8 @@ impl Alien { } else { read }; - let distance = self.phase.min(self.loop_len - self.phase); - let fade_frames = boundary_fade_frames(self.loop_len); + let distance = self.phase.min(self.active_loop_len - self.phase); + let fade_frames = boundary_fade_frames(self.active_loop_len); let mut result = self.buffer[read]; if distance < fade_frames { let gain: Q14 = Fixed::<0>::from_bits(distance as i32) @@ -215,16 +228,16 @@ impl Alien { self.read = 0; } } - /// Advances the loop phase by one frame and wraps at `loop_len`. + /// Advances the loop phase by one frame and wraps at `active_loop_len`. #[inline] fn advance_phase(&mut self) { self.phase += 1; - if self.phase == self.loop_len { + if self.phase == self.active_loop_len { self.phase = 0; } } /// Captures input, holds the dry signal until the loop fills, and ramps - /// the Q14 wet mix over 200 frames on each toggle. + /// the Q14 wet mix over 200 frames on each transition. pub(crate) fn process_sample(&mut self, input: [Q14; 2]) -> [Q14; 2] { if !self.config.enabled && self.wet_frames == 0 { return input; @@ -233,44 +246,37 @@ impl Alien { if self.written < HISTORY_FRAMES { self.written += 1; } - if self.restart_pending { + if self.config.enabled && !self.reset_capture { + self.captured = (self.captured + 1).min(HISTORY_FRAMES); + } + if self.fading_out || !self.config.enabled { let reverse = self.reverse_sample(); self.wet_frames -= 1; let result = self.mix_wet(input, reverse); self.advance_read(); self.advance_phase(); if self.wet_frames == 0 { + self.active_loop_len = self.config.loop_frames as usize; self.phase = 0; - self.captured = 0; - self.restart_pending = false; + self.fading_out = false; + if self.reset_capture || !self.config.enabled { + self.captured = 0; + self.reset_capture = false; + } } return result; } - if self.config.enabled { - self.captured = (self.captured + 1).min(HISTORY_FRAMES); - if self.captured < self.loop_len { - self.advance_read(); - return input; - } - let reverse = self.reverse_sample(); - if self.wet_frames < FADE_FRAMES { - self.wet_frames += 1; - } - let result = self.mix_wet(input, reverse); + if self.captured < self.active_loop_len { self.advance_read(); - self.advance_phase(); - result - } else { - let reverse = self.reverse_sample(); - self.wet_frames -= 1; - let result = self.mix_wet(input, reverse); - self.advance_read(); - self.advance_phase(); - if self.wet_frames == 0 { - self.phase = 0; - self.captured = 0; - } - result + return input; + } + let reverse = self.reverse_sample(); + if self.wet_frames < FADE_FRAMES { + self.wet_frames += 1; } + let result = self.mix_wet(input, reverse); + self.advance_read(); + self.advance_phase(); + result } } diff --git a/src/processor.rs b/src/processor.rs index 08f462b..9a24089 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -1286,8 +1286,10 @@ pub struct Telemetry { /// it during release and updates it on each enabled frame. The value is 1 /// while Warm is disabled. pub warm_gain: f32, - /// The length of the Alien loop in frames, as - /// [`crate::AlienConfig::loop_frames`] gives. + /// The active length of the Alien loop in frames. + /// + /// It equals [`crate::AlienConfig::loop_frames`] after any active wet fade + /// to zero finishes. pub alien_loop_frames: u32, /// The current frame in the Alien loop. It is less than /// [`alien_loop_frames`](Self::alien_loop_frames). From 942d298518411878ed178e2d23499c9e3f43463a Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:08:59 +0000 Subject: [PATCH 7/7] fix(reverb): measure bypass wet peaks and ramp disable input - Update reverb_wet_peak while an active bypass tail renders audio. - Ramp network input to zero over 256 frames when reverb disables. - Include the input ramp in bypass_remaining before zero-input decay. - Update ReverbConfig, Processor and Telemetry documentation. --- src/effects/reverb.rs | 117 ++++++++++++++++++++++++++---------------- src/processor.rs | 23 +++++---- 2 files changed, 87 insertions(+), 53 deletions(-) diff --git a/src/effects/reverb.rs b/src/effects/reverb.rs index dea8c5b..d20fe9b 100644 --- a/src/effects/reverb.rs +++ b/src/effects/reverb.rs @@ -9,6 +9,12 @@ use crate::{Error, SampleRate}; /// The step for a 256-frame Q14 gain ramp (`16384 / 256`). const RAMP_STEP: Q14 = Q14::from_bits(64); +/// Returns the frames that remain for a 256-frame Q14 ramp to reach zero. +#[inline] +fn ramp_frames(fade: Q14) -> usize { + (fade.to_bits().max(0) as usize).div_ceil(64) +} + /// The echo or reverberation network. The default is [`Self::Echo`]. /// /// All modes share one delay buffer. If the mode changes while the reverb is @@ -41,12 +47,13 @@ pub enum ReverbMode { /// decay. /// /// The reverb is disabled by default. If you disable an active reverb, the -/// stage feeds zero input into the network until the decay tail finishes, then -/// clears the delay buffer and the damping filters. If the stage is enabled -/// and the mix is zero, the network still operates. A reset clears the delay -/// buffer and keeps the memories of the damping filters. The mix, diffusion -/// and decay controls are quantized to Q14. The function of each control -/// changes with the network. +/// stage ramps the network input to zero over 256 frames. Then the decay tail +/// finishes before the stage clears the delay buffer and the damping filters. +/// If the stage is enabled and the mix is zero, the network still operates. +/// +/// A reset clears the delay buffer and keeps the memories of the damping +/// filters. The mix, diffusion and decay controls are quantized to Q14. The +/// function of each control changes with the network. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] #[cfg_attr( @@ -56,7 +63,8 @@ pub enum ReverbMode { )] pub struct ReverbConfig { /// Enables the selected network. The default is `false`. If you set this - /// field to `false`, an active tail decays with zero input before a clear. + /// field to `false`, the network input ramps to zero over 256 frames and + /// any active tail decays before a clear. pub enabled: bool, /// The topology of the delay network. The default is /// [`ReverbMode::Echo`]. @@ -171,7 +179,7 @@ pub(crate) struct Reverb { /// The Q14 allpass coefficients of MediumHall and LargeHall, scaled by /// `diffuse`. hall_diffuse: [Q14; 6], - /// The Q14 ramp between bypass dry and enabled dry, in 0..=1. + /// The Q14 ramp for the network input and the dry blend, in 0..=1. enable_fade: Q14, /// The Q14 wet gain scale for mode switches, in 0..=1. mode_fade: Q14, @@ -340,13 +348,23 @@ impl Reverb { return; } if config.mode != self.active_config.mode { - self.fading_out_mode = true; if prev_enabled && !config.enabled { let mut active = self.active_config; active.enabled = true; - self.bypass_remaining = tail_frames(self.rate, active); + let tail = tail_frames(self.rate, active); self.bypass_quiet_frames = 0; + if tail == 0 { + self.bypass_remaining = 0; + self.enable_fade = Q14::ZERO; + self.mode_fade = Q14::ONE; + self.fading_out_mode = false; + self.clear_all(); + self.apply_active_config(config); + return; + } + self.bypass_remaining = tail.saturating_add(ramp_frames(self.enable_fade)); } + self.fading_out_mode = true; return; } self.fading_out_mode = false; @@ -357,11 +375,16 @@ impl Reverb { } else if prev_enabled { let mut active = self.active_config; active.enabled = true; - self.bypass_remaining = tail_frames(self.rate, active); + let tail = tail_frames(self.rate, active); self.bypass_quiet_frames = 0; - if self.bypass_remaining == 0 { + if tail == 0 { + self.bypass_remaining = 0; + self.enable_fade = Q14::ZERO; + self.mode_fade = Q14::ONE; self.clear_all(); self.apply_active_config(config); + } else { + self.bypass_remaining = tail.saturating_add(ramp_frames(self.enable_fade)); } } } @@ -422,18 +445,17 @@ impl Reverb { } /// Returns the finite tail budget, with active bypass tails included. pub(crate) fn tail_frames(&self) -> usize { - let fade_frames = |fade: Q14| (fade.to_bits().max(0) as usize).div_ceil(64); if self.config.enabled { let base = tail_frames(self.rate, self.config); if self.fading_out_mode { - base.saturating_add(fade_frames(self.mode_fade)) + base.saturating_add(ramp_frames(self.mode_fade)) } else { base } } else if self.fading_out_mode { - fade_frames(self.mode_fade).max(fade_frames(self.enable_fade)) + ramp_frames(self.mode_fade).max(ramp_frames(self.enable_fade)) } else { - self.bypass_remaining.max(fade_frames(self.enable_fade)) + self.bypass_remaining.max(ramp_frames(self.enable_fade)) } } /// Returns the largest absolute Q14 wet contribution since the last @@ -612,11 +634,8 @@ impl Reverb { let wet_terms = self.step_network(left, right, self.mix); ([mul(left, dry), mul(right, dry)], wet_terms) } else { - let (net_left, net_right) = if self.config.enabled { - (mul(left, self.enable_fade), mul(right, self.enable_fade)) - } else { - (Q14::ZERO, Q14::ZERO) - }; + let net_left = mul(left, self.enable_fade); + let net_right = mul(right, self.enable_fade); let enabled_dry = if self.fading_out_mode && self.config.enabled { mul(dry, self.mode_fade) + mul(Q14::ONE - self.target_mix, Q14::ONE - self.mode_fade) @@ -635,38 +654,40 @@ impl Reverb { let result = [dry_terms[0] + wet_terms[0], dry_terms[1] + wet_terms[1]]; // Telemetry only. The wet contribution is the output minus the dry // term. Mono calls measure the wet signal after the downmix. - if self.config.enabled { - let left_wet = result[0] - dry_terms[0]; - let right_wet = result[1] - dry_terms[1]; - match layout { - OutputLayout::Stereo => { - for wet in [left_wet, right_wet] { - self.wet_peak = self.wet_peak.max(wet.abs().to_bits()); - } - } - OutputLayout::Mono => { - let wet = Q14::from_bits( - ((i64::from(left_wet.to_bits()) + i64::from(right_wet.to_bits())) >> 1) - as i32, - ) - .abs() - .to_bits(); - self.wet_peak = self.wet_peak.max(wet); + let left_wet = result[0] - dry_terms[0]; + let right_wet = result[1] - dry_terms[1]; + match layout { + OutputLayout::Stereo => { + for wet in [left_wet, right_wet] { + self.wet_peak = self.wet_peak.max(wet.abs().to_bits()); } } + OutputLayout::Mono => { + let wet = Q14::from_bits( + ((i64::from(left_wet.to_bits()) + i64::from(right_wet.to_bits())) >> 1) as i32, + ) + .abs() + .to_bits(); + self.wet_peak = self.wet_peak.max(wet); + } } if self.fading_out_mode && self.mode_fade == Q14::ZERO { - self.clear_all(); - self.fading_out_mode = false; - self.apply_active_config(self.config); if self.config.enabled { + self.clear_all(); + self.fading_out_mode = false; + self.apply_active_config(self.config); self.bypass_remaining = 0; - } else { + } else if self.enable_fade == Q14::ZERO { + self.clear_all(); + self.fading_out_mode = false; + self.apply_active_config(self.config); self.bypass_remaining = 0; self.mode_fade = Q14::ONE; } } else if !self.config.enabled && self.bypass_remaining > 0 { - let quiet = wet_terms[0].abs().to_bits() <= 2 && wet_terms[1].abs().to_bits() <= 2; + let quiet = self.enable_fade == Q14::ZERO + && wet_terms[0].abs().to_bits() <= 2 + && wet_terms[1].abs().to_bits() <= 2; if quiet { self.bypass_quiet_frames += 1; } else { @@ -675,9 +696,19 @@ impl Reverb { self.bypass_remaining -= 1; if self.bypass_remaining == 0 || self.bypass_quiet_frames >= CAPACITY { self.bypass_remaining = 0; + self.enable_fade = Q14::ZERO; + self.mode_fade = Q14::ONE; self.clear_all(); self.apply_active_config(self.config); } + } else if !self.config.enabled + && !self.fading_out_mode + && self.bypass_remaining == 0 + && self.enable_fade == Q14::ZERO + { + self.mode_fade = Q14::ONE; + self.clear_all(); + self.apply_active_config(self.config); } result } diff --git a/src/processor.rs b/src/processor.rs index 9a24089..7d8962f 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -69,8 +69,8 @@ pub struct Processor { alien: Alien, /// The delay network and the damping filters. /// - /// When you disable reverb, an active tail decays with zero input before a - /// clear. + /// When you disable reverb, the network input ramps to zero over 256 + /// frames and an active tail decays before a clear. reverb: Reverb, /// The random sequence of this instance and the cached arctangent position. numeric: NumericContext, @@ -688,12 +688,14 @@ impl Processor { /// Each successful call cancels a drain, also for an identical /// configuration. If the reverb mode changes, the stage ramps the wet gain /// to zero over 256 frames. Then it clears the delay buffer and the - /// damping filters, and ramps the new mode over 256 frames. If you disable - /// Punch or Warm, the history of that stage stops. If you disable reverb, - /// its active tail decays with zero input before a clear. When you enable - /// Alien, it captures a fresh loop and ramps the wet mix over 200 frames. - /// A change in either half of the `u64` seed starts the stream again, but - /// the new sequence uses only the low 32 bits. + /// damping filters, and ramps the new mode over 256 frames. + /// + /// If you disable Punch or Warm, the history of that stage stops. If you + /// disable reverb, its input ramps to zero over 256 frames and its active + /// tail decays before a clear. When you enable Alien, it captures a fresh + /// loop and ramps the wet mix over 200 frames. A change in either half of + /// the `u64` seed starts the stream again, but the new sequence uses only + /// the low 32 bits. /// /// # Errors /// @@ -1187,8 +1189,9 @@ pub struct Telemetry { /// /// The contribution is the wet signal times the mix, before the output /// gain. Stereo calls measure the larger of the two channels. Mono calls - /// measure the wet signal after the downmix. While the reverb is disabled, - /// the window gets no new values. + /// measure the wet signal after the downmix. Active bypass tails also + /// update this peak. While the reverb is idle in bypass, the window gets no + /// new values. pub reverb_wet_peak: f32, /// The pitch-correction ratio from the last processed frame, where 1 is /// unity, as [`Feedback::resample_ratio`] gives.