From feb26fec778b2cc65a816f988008b6280fff1351 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Sat, 21 Nov 2026 01:51:23 +0000 Subject: [PATCH] fix: crossfade live voice, formant, stereo and effect switches - Preallocate active and shadow 16-reader voice banks. - Crossfade pitch-period jumps across all 16 reader slots. - Write the rendered lead history on every frame. - Separate the delayed raw and LPC filtered source buffers. - Run the LPC inverse analysis continuously on the input. - Remove the audio and effect resets on stereo output changes. - Crossfade the mono and panned voice buses over 256 frames. - Pair reverse cursors in Alien with 200-frame wet ramps. - Preallocate dual reverb banks and decay tails on bypass. - Update the documentation and the README reset section. --- README.md | 4 +- src/effects.rs | 4 +- src/effects/alien.rs | 208 ++++++-- src/effects/reverb.rs | 565 ++++++++++++++------ src/formant.rs | 107 ++-- src/processor.rs | 60 +-- src/resynthesis.rs | 1160 +++++++++++++++++++++++++++++------------ 7 files changed, 1482 insertions(+), 626 deletions(-) diff --git a/README.md b/README.md index d2993dc..53c71b9 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, which include `stereo_output`, crossfade +the audio state and do not reset histories. 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..2af38a4 100644 --- a/src/effects.rs +++ b/src/effects.rs @@ -3,8 +3,8 @@ //! 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. +//! behavior. Alien continues to record during bypass. Reverb decays active +//! tails with zero input and then clears them. //! //! 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..3fd3959 100644 --- a/src/effects/alien.rs +++ b/src/effects/alien.rs @@ -12,10 +12,12 @@ const FADE_FRAMES: usize = 200; /// 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. +/// also when Alien is disabled. If you enable Alien, it starts a new capture +/// epoch and ramps the wet mix over 200 frames. Thus, audio from bypass does +/// not play. If you disable Alien, it ramps the wet mix to zero over 200 +/// frames. A change of the loop length clamps the phase into the new loop and +/// crossfades from the previous cursor over 200 frames. The boundary fade +/// length is `min(200, loop_frames / 2)`, which is zero at `loop_frames` of 1. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] #[cfg_attr( @@ -25,13 +27,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`. A change ramps the wet mix over 200 frames. If you enable + /// Alien, it starts a new capture epoch. 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. At 1, the boundary fade is zero. pub loop_frames: u32, } impl Default for AlienConfig { @@ -57,8 +58,78 @@ impl AlienConfig { } } -/// A stereo ring recorder with a reverse reader and an independent loop -/// phase. +/// Returns the boundary fade length for `loop_frames`: zero at 1, and at most +/// 200 frames. +#[inline] +fn loop_fade_frames(loop_frames: usize) -> usize { + if loop_frames <= 1 { + 0 + } else { + FADE_FRAMES.min(loop_frames / 2) + } +} + +/// One reverse cursor and the count of frames recorded in its capture epoch. +#[derive(Clone, Copy, Debug)] +struct ReverseCursor { + /// The current frame in the loop, always less than `loop_len`. + phase: usize, + /// The validated loop length, not more than half of the history capacity. + loop_len: usize, + /// The number of frames recorded in this epoch before the current frame. + captured: usize, +} + +impl ReverseCursor { + /// Creates a cursor at phase zero for `loop_len` and `captured` frames. + fn new(loop_len: usize, captured: usize) -> Self { + Self { + phase: 0, + loop_len, + captured, + } + } + + /// Reads the reversed stereo sample for this cursor, or zero before its + /// capture epoch. + fn sample(self, buffer: &[[Q14; 2]], write: usize) -> [Q14; 2] { + let offset = self.phase * 2; + if offset > self.captured { + return [Q14::ZERO; 2]; + } + let read = write + HISTORY_FRAMES - offset; + let read = if read >= HISTORY_FRAMES { + read - HISTORY_FRAMES + } else { + read + }; + let mut result = buffer[read]; + let fade_frames = loop_fade_frames(self.loop_len); + let distance = self + .phase + .min(self.loop_len - self.phase) + .min(self.captured - offset); + 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 + } + + /// Advances the loop phase and the epoch frame count by one frame. + fn step(&mut self) { + self.phase += 1; + if self.phase == self.loop_len { + self.phase = 0; + } + if self.captured < HISTORY_FRAMES { + self.captured += 1; + } + } +} + +/// A stereo ring recorder with paired reverse cursors and wet-mix ramps. #[derive(Debug)] pub(crate) struct Alien { /// The validated controls, which include the selection of the wet output. @@ -66,80 +137,121 @@ 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 recording position in the ring buffer. 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 active reverse cursor, which telemetry also reports. + active: ReverseCursor, + /// The previous reverse cursor for crossfades across loop changes. + shadow: ReverseCursor, + /// The crossfade progress toward `active`, in `0..=FADE_FRAMES`. + cursor_fade_frames: usize, + /// The wet mix ramp position, in `0..=FADE_FRAMES`. + wet_frames: usize, } impl Alien { /// Allocates a silent stereo ring from validated loop settings. pub(crate) fn new(config: AlienConfig) -> Self { + let cursor = ReverseCursor::new(config.loop_frames as usize, 0); Self { config, buffer: vec![[Q14::default(); 2]; HISTORY_FRAMES], read: 0, - phase: 0, - loop_len: config.loop_frames as usize, + active: cursor, + shadow: cursor, + cursor_fade_frames: FADE_FRAMES, + wet_frames: if config.enabled { FADE_FRAMES } else { 0 }, } } - /// Applies a validated configuration, keeps the recorded audio and clamps - /// the phase into the new loop, which is not empty. + /// Applies a validated configuration. If Alien becomes enabled, starts a + /// new capture epoch. If the loop length changes, crossfades the cursors. pub(crate) fn set_config(&mut self, config: AlienConfig) { + let was_enabled = self.config.enabled; + let new_loop_len = config.loop_frames as usize; 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.cursor_fade_frames >= FADE_FRAMES / 2 { + self.shadow = self.active; + self.cursor_fade_frames = 0; + } + self.active = ReverseCursor::new(new_loop_len, 0); + } else if new_loop_len != self.active.loop_len { + if (was_enabled || self.wet_frames > 0) && self.cursor_fade_frames >= FADE_FRAMES / 2 { + self.shadow = self.active; + self.cursor_fade_frames = 0; + } + self.active.loop_len = new_loop_len; + self.active.phase = self.active.phase.min(new_loop_len - 1); + } } /// Returns the 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.active.phase) } - /// Clears the recorded audio and sets both cursors to zero, but keeps the - /// configured loop. + /// Clears the recorded audio and resets the cursors and ramps, but keeps + /// the configured loop. pub(crate) fn reset(&mut self) { self.buffer.fill([Q14::default(); 2]); self.read = 0; - self.phase = 0; + let cursor = ReverseCursor::new(self.active.loop_len, 0); + self.active = cursor; + self.shadow = cursor; + self.cursor_fade_frames = FADE_FRAMES; + self.wet_frames = if self.config.enabled { FADE_FRAMES } else { 0 }; } - /// Records a frame, selects the direct or reverse output, then advances - /// both cursors. - /// The recording cursor moves forward by one and the reverse offset + /// Records a frame, blends the reverse cursors and Q14 wet mix, then + /// advances the cursors. + /// + /// The recording cursor moves forward by one and each 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 + if self.config.enabled { + if self.wet_frames < FADE_FRAMES { + self.wet_frames += 1; + } + } else if self.wet_frames > 0 { + self.wet_frames -= 1; + } + let result = if self.wet_frames == 0 { + self.cursor_fade_frames = FADE_FRAMES; + input + } else { + let mut wet = self.active.sample(&self.buffer, self.read); + if self.cursor_fade_frames < FADE_FRAMES { + self.cursor_fade_frames += 1; + if self.cursor_fade_frames < FADE_FRAMES { + let old = self.shadow.sample(&self.buffer, self.read); + let fade: Q14 = Fixed::<0>::from_bits(self.cursor_fade_frames as i32) + .div(Fixed::<0>::from_bits(FADE_FRAMES as i32)); + let inv = Q14::ONE - fade; + wet = [ + (old[0].mul::<14, 28>(inv) + wet[0].mul::<14, 28>(fade)).rescale(), + (old[1].mul::<14, 28>(inv) + wet[1].mul::<14, 28>(fade)).rescale(), + ]; + } + self.shadow.step(); + } + if self.wet_frames == FADE_FRAMES { + wet } 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) + let mix: Q14 = Fixed::<0>::from_bits(self.wet_frames as i32) .div(Fixed::<0>::from_bits(FADE_FRAMES as i32)); - result = result.map(|sample| sample.mul::<14, 14>(gain)); + let dry = Q14::ONE - mix; + [ + (input[0].mul::<14, 28>(dry) + wet[0].mul::<14, 28>(mix)).rescale(), + (input[1].mul::<14, 28>(dry) + wet[1].mul::<14, 28>(mix)).rescale(), + ] } - result - } else { - input }; self.read += 1; if self.read == HISTORY_FRAMES { self.read = 0; } - self.phase += 1; - if self.phase == self.loop_len { - self.phase = 0; - } + self.active.step(); result } } diff --git a/src/effects/reverb.rs b/src/effects/reverb.rs index fe60cd4..608cdd1 100644 --- a/src/effects/reverb.rs +++ b/src/effects/reverb.rs @@ -1,17 +1,19 @@ -//! Echo and room networks that share one circular delay buffer. +//! Echo and room networks with active and shadow circular delay buffers. use crate::error::check_range; use crate::filter::{Biquad, Design}; use crate::numeric::fixed::{Fixed, Q14}; use crate::{Error, SampleRate}; +/// The step for 256-frame Q14 dry transitions across mode and bypass switches. +const DRY_FADE_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. +/// Two preallocated delay banks let a new mode start cleanly while the +/// previous network decays in parallel. If a third mode switch occurs before a +/// decay completes, the quieter bank starts the new mode. 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 +38,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 the reverb, active banks +/// get zero input across their tail budget and then clear their delay and +/// filter memories. If all banks are clear in bypass, the stage returns the +/// input directly. If the stage is enabled and the mix is zero, the active +/// network still operates. A reset clears the delay buffers and keeps the +/// memories of the active damping filters. The mix, diffusion and decay +/// controls are quantized to Q14. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] #[cfg_attr( @@ -50,8 +53,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 disabled, + /// active tails decay with zero input and then clear. pub enabled: bool, /// The topology of the delay network. The default is /// [`ReverbMode::Echo`]. @@ -115,131 +118,110 @@ impl ReverbConfig { } } -/// The shared Q14 delay network with two low-pass damping filters that keep -/// state. +/// One preallocated 17,000-sample delay network with its own damping filters. #[derive(Debug)] -pub(crate) struct Reverb { - /// The prepared sample rate for the cutoff and tap calculations. - rate: SampleRate, - /// The validated controls and the selected network. +struct ReverbBank { + /// The configuration snapshot that drives this bank. config: ReverbConfig, - /// The shared circular storage for all network topologies. + /// The circular storage for this bank. delay: DelayLine, - /// The first damping filter. A delay reset or a mode change does not - /// clear its memories. + /// The first damping filter of this bank. lpf1: Biquad, - /// The second damping filter. It keeps its memories in the same way as - /// the first filter. + /// The second damping filter of this bank. lpf2: Biquad, - /// 67 prepared frame offsets into the shared ring. - taps: [usize; 67], - /// The Q14 wet contribution. + /// The Q14 wet contribution of this bank. mix: Q14, - /// The Q14 control for the diffusion or the echo distance. + /// The Q14 control for diffusion or echo distance. diffuse: Q14, /// The Q14 feedback coefficient, scaled by 100/105. decay: Q14, - /// 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, - /// The reserved last ring offset. The output sums go to this slot, and - /// the next ring step clears it. - scratch: usize, - /// The largest absolute Q14 wet contribution in the telemetry window. No - /// audio calculation reads it. - wet_peak: i32, -} - -/// The divisor for a division by two that truncates toward zero, also for -/// negative values. -const TWO: Fixed<0> = Fixed::from_bits(2); - -/// Quantizes a fixed network coefficient to Q14. -#[inline] -fn q14(coefficient: f64) -> Q14 { - Q14::from_f64(coefficient) -} - -/// Multiplies two Q14 values with a wrapping 32-bit product before the shift. -#[inline] -fn mul(left: Q14, right: Q14) -> Q14 { - left.mul(right) + /// True while this bank receives input or decays a tail. + active: bool, + /// The zero-input tail frames that are left, or zero for live input. + decay_remaining: usize, + /// The smoothed absolute Q14 wet level, which selects the quieter bank. + level: i32, } -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 mut result = Self { - rate, +impl ReverbBank { + /// Allocates one silent bank of `capacity` frames. + fn new(capacity: usize, config: ReverbConfig) -> Self { + Self { config, - delay: DelayLine::new(layout.capacity), + delay: DelayLine::new(capacity), lpf1: Biquad::new(), lpf2: Biquad::new(), - taps: layout.taps, mix: Q14::default(), diffuse: Q14::default(), decay: Q14::default(), - binaural_offset: layout.binaural_offset, - scratch: layout.capacity - 1, - wet_peak: 0, - }; - result.set_config(config); - result + active: false, + decay_remaining: 0, + level: 0, + } } - /// Updates the coefficients and does not clear the delay or filter state. - /// The f32 multiplication by 100 occurs before the f64 division and the - /// quantization. If you combine these expressions, the quantized - /// coefficients can change. - pub(crate) fn set_config(&mut self, config: ReverbConfig) { + + /// Quantizes the coefficients and filter design of `config`, and keeps the + /// filter memories. + fn apply_coefficients(&mut self, rate: SampleRate, config: ReverbConfig) { self.config = config; self.mix = Q14::from_f64((config.mix * 100.0) as f64 / 100.0); self.diffuse = Q14::from_f64((config.diffusion * 100.0) as f64 / 100.0); self.decay = Q14::from_f64((config.decay * 100.0) as f64 / 105.0); - let brightness = config - .brightness_hz - .min((self.rate.hz() as f64 * 0.49) as f32); - let design = Design::low_pass_one_pole(self.rate.hz(), brightness); + let brightness = config.brightness_hz.min((rate.hz() as f64 * 0.49) as f32); + let design = Design::low_pass_one_pole(rate.hz(), brightness); self.lpf1.set_design(design); self.lpf2.set_design(design); } - /// Clears only the delay contents, and keeps the write cursor and the - /// damping memories. - pub(crate) fn reset(&mut self) { + + /// Clears the delay buffer, the two damping filters and the level state. + fn clear(&mut self) { self.delay.reset(); + self.lpf1.reset(); + self.lpf2.reset(); + self.active = false; + self.decay_remaining = 0; + self.level = 0; } - /// Returns the largest absolute Q14 wet contribution since the last - /// clear, as f32. - pub(crate) fn wet_peak(&self) -> f32 { - (self.wet_peak as f64 / 16384.0) as f32 - } - /// Starts a new window for the wet peak. The audio state does not change. - pub(crate) fn clear_wet_peak(&mut self) { - self.wet_peak = 0; + + /// Starts zero-input decay across the tail budget, or clears immediately + /// if the budget is zero. + fn start_decay(&mut self, rate: SampleRate) { + if !self.active { + return; + } + if self.decay_remaining > 0 { + return; + } + let mut enabled_config = self.config; + enabled_config.enabled = true; + let budget = tail_frames(rate, enabled_config); + if budget == 0 { + self.clear(); + } else { + self.decay_remaining = budget; + } } - /// 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. - pub(crate) fn process_sample(&mut self, frame: [Q14; 2]) -> [Q14; 2] { + + /// Advances this bank by one frame and returns its stereo Q14 wet signal. + fn process_wet( + &mut self, + frame: [Q14; 2], + taps: &[usize; 67], + binaural_offset: usize, + scratch: usize, + ) -> [Q14; 2] { let [left, right] = frame; let mono = (left + right).div::<0, 14>(TWO); - let t = self.taps; - let dry = Q14::ONE - self.mix; + let t = *taps; let d = &mut self.delay; - if !self.config.enabled { - return frame; - } - let mut result = match self.config.mode { + let wet = match self.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])), + mul(self.mix, d.get(t[25]) - d.get(t[32])), + -mul(self.mix, d.get(t[26]) - d.get(t[31])), ] } ReverbMode::Schroeder => { @@ -260,7 +242,7 @@ 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])); + let value = mul(self.mix, d.get(t[45])); [value, value] } ReverbMode::SmallRoom => { @@ -274,21 +256,20 @@ 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 raw_left = d.fir( + scratch, + &[(t[16], q14(0.2)), (t[32], q14(0.2)), (t[51], q14(0.2))], + ); + let raw_right = d.fir( + scratch, + &[(t[49], q14(0.2)), (t[65], q14(0.2)), (t[17], q14(0.2))], + ); + [mul(self.mix, raw_left), mul(self.mix, raw_right)] } ReverbMode::Binaural => { let seed = t[10]; let tap = t[25]; - let filter = tap + self.binaural_offset; + let filter = tap + binaural_offset; d.put(left, t[0]); d.put(right, t[40]); let a = mul( @@ -297,14 +278,15 @@ impl Reverb { ); 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_left = 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)] + let wet_right = mul(self.mix, d.get(filter) + b); + [wet_left, wet_right] } ReverbMode::MediumHall => { d.put(mono.div::<0, 14>(TWO), t[0]); @@ -317,26 +299,25 @@ 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 raw_left = d.fir( + scratch, + &[ + (t[16], q14(-0.25)), + (t[33], q14(0.25)), + (t[51], q14(-0.25)), + (t[55], q14(0.25)), + ], + ); + let raw_right = d.fir( + scratch, + &[ + (t[16], q14(0.25)), + (t[32], q14(0.25)), + (t[52], q14(0.25)), + (t[56], q14(0.2)), + ], + ); + [mul(self.mix, raw_left), mul(self.mix, raw_right)] } ReverbMode::LargeHall => { d.put(mono, t[0]); @@ -349,41 +330,295 @@ 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 raw_left = d.fir( + scratch, + &[(t[10], q14(0.6)), (t[36], q14(0.3)), (t[61], q14(0.3))], + ); + let raw_right = d.fir( + scratch, + &[(t[10], q14(0.6)), (t[37], q14(0.3)), (t[60], q14(0.3))], + ); + [mul(self.mix, raw_left), mul(self.mix, raw_right)] } }; - 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] + let peak = wet[0] + .to_bits() + .wrapping_abs() + .max(wet[1].to_bits().wrapping_abs()); + self.level = (self.level - (self.level >> 8)).max(peak); + wet + } +} + +/// Dual Q14 delay networks with independent damping filter pairs. +#[derive(Debug)] +pub(crate) struct Reverb { + /// The prepared sample rate for the cutoff and tap calculations. + rate: SampleRate, + /// The validated controls and the selected network. + config: ReverbConfig, + /// Two preallocated 17,000-sample delay and filter banks. + banks: [ReverbBank; 2], + /// The index (`0` or `1`) of the bank for the active mode. + active_bank: usize, + /// 67 prepared frame offsets into each ring. + taps: [usize; 67], + /// 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, + /// The reserved last ring offset. The output sums go to this slot, and + /// the next ring step clears it. + scratch: usize, + /// The current Q14 dry gain, which ramps over 256 frames across switches. + dry_gain: Q14, + /// The current Q14 weight of the mono dry input (`Schroeder` and + /// `Binaural`). + mono_dry_mix: Q14, + /// The largest absolute Q14 wet contribution in the telemetry window. No + /// audio calculation reads it. + wet_peak: i32, +} + +/// The divisor for a division by two that truncates toward zero, also for +/// negative values. +const TWO: Fixed<0> = Fixed::from_bits(2); + +/// Quantizes a fixed network coefficient to Q14. +#[inline] +fn q14(coefficient: f64) -> Q14 { + Q14::from_f64(coefficient) +} + +/// 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 `true` if `mode` uses a mono dry signal. +#[inline] +fn uses_mono_dry(mode: ReverbMode) -> bool { + matches!(mode, ReverbMode::Schroeder | ReverbMode::Binaural) +} + +impl Reverb { + /// Allocates both 17,000-sample delay banks and prepares the filters from + /// validated controls. + pub(crate) fn new(rate: SampleRate, config: ReverbConfig) -> Self { + let layout = reverb_layout(rate.hz()); + let mut banks = [ + ReverbBank::new(layout.capacity, config), + ReverbBank::new(layout.capacity, config), + ]; + banks[0].apply_coefficients(rate, config); + banks[1].apply_coefficients(rate, config); + banks[0].active = config.enabled; + let dry_gain = if config.enabled { + Q14::ONE - banks[0].mix + } else { + Q14::ONE + }; + let mono_dry_mix = if config.enabled && uses_mono_dry(config.mode) { + Q14::ONE } else { + Q14::ZERO + }; + Self { + rate, + config, + banks, + active_bank: 0, + taps: layout.taps, + binaural_offset: layout.binaural_offset, + scratch: layout.capacity - 1, + dry_gain, + mono_dry_mix, + wet_peak: 0, + } + } + /// Applies `config`, starts tail decay on old banks, and prepares the idle + /// or quieter bank. + /// + /// The f32 multiplication by 100 occurs before the f64 division and the + /// quantization. If you combine these expressions, the quantized + /// coefficients can change. + pub(crate) fn set_config(&mut self, config: ReverbConfig) { + let was_enabled = self.config.enabled; + let old_mode = self.config.mode; + self.config = config; + if !config.enabled { + if was_enabled { + for bank in &mut self.banks { + bank.start_decay(self.rate); + } + } + return; + } + if !was_enabled { + let current = self.active_bank; + if !self.banks[current].active { + self.banks[current].clear(); + self.banks[current].apply_coefficients(self.rate, config); + self.banks[current].active = true; + } else { + self.banks[current].start_decay(self.rate); + let other = 1 - current; + let target = if !self.banks[other].active + || self.banks[other].level <= self.banks[current].level + { + other + } else { + current + }; + self.banks[target].clear(); + self.banks[target].apply_coefficients(self.rate, config); + self.banks[target].active = true; + self.active_bank = target; + } + } else if config.mode != old_mode { + let current = self.active_bank; + self.banks[current].start_decay(self.rate); + let other = 1 - current; + let target = if !self.banks[other].active + || self.banks[other].level <= self.banks[current].level + { + other + } else { + current + }; + self.banks[target].clear(); + self.banks[target].apply_coefficients(self.rate, config); + self.banks[target].active = true; + self.active_bank = target; + } else { + let current = self.active_bank; + self.banks[current].apply_coefficients(self.rate, config); + self.banks[current].active = true; + self.banks[current].decay_remaining = 0; + } + } + /// Clears the delay contents of both banks and keeps the write cursor and + /// damping memories of the active bank. + pub(crate) fn reset(&mut self) { + let current = self.active_bank; + let other = 1 - current; + self.banks[other].clear(); + self.banks[current].delay.reset(); + self.banks[current].decay_remaining = 0; + self.banks[current].level = 0; + self.banks[current].active = self.config.enabled; + self.dry_gain = if self.config.enabled { + Q14::ONE - self.banks[current].mix + } else { + Q14::ONE + }; + self.mono_dry_mix = if self.config.enabled && uses_mono_dry(self.config.mode) { + Q14::ONE + } else { + Q14::ZERO + }; + } + /// Returns the largest absolute Q14 wet contribution since the last + /// clear, as f32. + pub(crate) fn wet_peak(&self) -> f32 { + (self.wet_peak as f64 / 16384.0) as f32 + } + /// Starts a new window for the wet peak. The audio state does not change. + pub(crate) fn clear_wet_peak(&mut self) { + self.wet_peak = 0; + } + /// Advances the active reverb banks by one frame. + /// + /// If the reverb is disabled and all tails are clear, no delay or filter + /// history advances. The internal mono averages use integer division + /// toward zero. + pub(crate) fn process_sample(&mut self, frame: [Q14; 2]) -> [Q14; 2] { + let target_dry = if self.config.enabled { + Q14::ONE - self.banks[self.active_bank].mix + } else { + Q14::ONE + }; + if self.dry_gain < target_dry { + self.dry_gain = (self.dry_gain + DRY_FADE_STEP).min(target_dry); + } else if self.dry_gain > target_dry { + self.dry_gain = (self.dry_gain - DRY_FADE_STEP).max(target_dry); + } + let target_mono = if self.config.enabled && uses_mono_dry(self.config.mode) { + Q14::ONE + } else { + Q14::ZERO + }; + if self.mono_dry_mix < target_mono { + self.mono_dry_mix = (self.mono_dry_mix + DRY_FADE_STEP).min(target_mono); + } else if self.mono_dry_mix > target_mono { + self.mono_dry_mix = (self.mono_dry_mix - DRY_FADE_STEP).max(target_mono); + } + if !self.config.enabled + && !self.banks[0].active + && !self.banks[1].active + && self.dry_gain == Q14::ONE + && self.mono_dry_mix == Q14::ZERO + { + return frame; + } + let [left, right] = frame; + let mono = (left + right).div::<0, 14>(TWO); + let dry_input = if self.mono_dry_mix == Q14::ZERO { [left, right] + } else if self.mono_dry_mix == Q14::ONE { + [mono, mono] + } else { + let stereo_weight = Q14::ONE - self.mono_dry_mix; + [ + (left.mul::<14, 28>(stereo_weight) + mono.mul::<14, 28>(self.mono_dry_mix)) + .rescale(), + (right.mul::<14, 28>(stereo_weight) + mono.mul::<14, 28>(self.mono_dry_mix)) + .rescale(), + ] + }; + let dry_part = if self.dry_gain == Q14::ONE { + dry_input + } else { + [ + mul(dry_input[0], self.dry_gain), + mul(dry_input[1], self.dry_gain), + ] }; - 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 mut wet_sum = [Q14::ZERO; 2]; + for index in 0..2 { + if !self.banks[index].active { + continue; + } + let bank_input = if self.config.enabled + && index == self.active_bank + && self.banks[index].decay_remaining == 0 + { + frame + } else { + [Q14::ZERO; 2] + }; + let wet = self.banks[index].process_wet( + bank_input, + &self.taps, + self.binaural_offset, + self.scratch, + ); + wet_sum[0] = wet_sum[0] + wet[0]; + wet_sum[1] = wet_sum[1] + wet[1]; + if self.banks[index].decay_remaining > 0 { + self.banks[index].decay_remaining -= 1; + if self.banks[index].decay_remaining == 0 { + self.banks[index].clear(); + } + } + } + if self.config.enabled || self.banks[0].active || self.banks[1].active { + for sample in wet_sum { + self.wet_peak = self.wet_peak.max(sample.to_bits().wrapping_abs()); + } } - result + [dry_part[0] + wet_sum[0], dry_part[1] + wet_sum[1]] } } diff --git a/src/formant.rs b/src/formant.rs index 5072ee1..0b0bf49 100644 --- a/src/formant.rs +++ b/src/formant.rs @@ -28,13 +28,15 @@ use crate::{Error, SampleRate}; /// The controls for vocal-tract changes and synthesized aspiration during /// resynthesis. /// -/// This stage is disabled by default. If it is enabled, it does these steps: +/// This stage is disabled by default. The LPC analysis runs continuously on +/// the input audio. If the stage is enabled, it does these steps: /// 1. It estimates an LPC model. /// 2. It removes the spectral envelope of the input. /// 3. It applies a changed model to the resampled audio. /// -/// If width and stretch are 1, the model dimensions do not change. But the -/// fixed-point analysis and synthesis path does not give a bit-identical +/// A change to `enabled` crossfades the dry and formant voice paths over 256 +/// frames. If width and stretch are 1, the model dimensions do not change. But +/// the fixed-point analysis and synthesis path does not give a bit-identical /// copy of the input. Aspiration occurs only if the formant path is enabled. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] @@ -182,12 +184,17 @@ pub(crate) struct Formant { /// A counter that increases from a negative value to zero. At zero, the /// stage tries to make a model. design_counter: i32, - /// The separate Q14 feedback histories of the synthesis, for the left and - /// right channels. Mono synthesis uses channel zero. - history: [[i32; MAX_ORDER]; 2], - /// The next slot in the synthesis history. The two channels use the same - /// slot. - history_index: usize, + /// The separate Q14 feedback histories of mono lead synthesis, for the + /// active and shadow voice banks. + lead_history: [[i32; MAX_ORDER]; 2], + /// The next slot in each mono lead synthesis history. + lead_history_index: [usize; 2], + /// The separate Q14 feedback histories of stereo synthesis, for the active + /// and shadow voice banks and the left and right channels. + history: [[[i32; MAX_ORDER]; 2]; 2], + /// The next slot in each stereo synthesis history. The two channels of a + /// bank use the same slot. + history_index: [usize; 2], /// The two previous normalized autocorrelation vectors for the moving /// average. correlation_history: [[i32; 111]; 2], @@ -258,8 +265,10 @@ impl Formant { previous: 0, blend: 0, design_counter: 0, - history: [[0; MAX_ORDER]; 2], - history_index: 0, + lead_history: [[0; MAX_ORDER]; 2], + lead_history_index: [0; 2], + history: [[[0; MAX_ORDER]; 2]; 2], + history_index: [0; 2], correlation_history: [[0; 111]; 2], correlation_sum: [0; 111], smooth_index: 0, @@ -318,15 +327,30 @@ impl Formant { self.input.fill(0_i32); self.stamps.fill(Stamp::default()); - self.history = [[0; MAX_ORDER]; 2]; - 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; } + /// Clears all synthesis feedback memories and the aspiration filter. + /// + /// The analysis input, the stamps and the coefficient banks do not change. + pub(crate) fn reset_synthesis(&mut self) { + self.lead_history = [[0; MAX_ORDER]; 2]; + self.lead_history_index = [0; 2]; + self.history = [[[0; MAX_ORDER]; 2]; 2]; + self.history_index = [0; 2]; + self.noise_filter.reset(); + } + /// Clears the mono and stereo synthesis memories of one voice bank slot. + pub(crate) fn reset_slot(&mut self, slot: usize) { + self.lead_history[slot] = [0; MAX_ORDER]; + self.lead_history_index[slot] = 0; + self.history[slot] = [[0; MAX_ORDER]; 2]; + self.history_index[slot] = 0; + } /// Starts a new model and a new correlation window when pitch acquisition /// locks. /// @@ -781,69 +805,78 @@ impl Formant { /// Applies the optional aspiration and the stamped synthesis model to one /// Q14 excitation, then scales the result by the width. /// - /// The function uses the feedback history of channel zero. `position` is - /// an integer frame of the input history. Resynthesis aligns this frame. + /// `slot` selects the feedback history of the voice bank. If `allow_noise` + /// is `false`, the random stream and the noise filter do not advance. + /// `position` is an integer frame of the input history. pub(crate) fn forward( &mut self, + slot: usize, sample: i32, position: i32, + allow_noise: bool, context: &mut NumericContext, ) -> i32 { - let sample = self.add_noise(sample, context); + let sample = if allow_noise { + self.add_noise(sample, context) + } else { + sample + }; let mut coefficients = [0; MAX_ORDER]; let order = self.coefficients(position, &mut coefficients); let mut sum = 0_i32; - let mut cursor = self.history_index; + let mut cursor = self.lead_history_index[slot]; for &coefficient in &coefficients[..order] { cursor = if cursor == 0 { MAX_ORDER - 1 } else { cursor - 1 }; - sum = sum.wrapping_add(self.history[0][cursor].wrapping_mul(coefficient)); + sum = sum.wrapping_add(self.lead_history[slot][cursor].wrapping_mul(coefficient)); } let sample = sample.wrapping_add(round_q14(sum)); - self.history[0][self.history_index] = sample; - self.history_index += 1; - if self.history_index == MAX_ORDER { - self.history_index = 0; - } + let index = self.lead_history_index[slot]; + self.lead_history[slot][index] = sample; + self.lead_history_index[slot] = if index + 1 == MAX_ORDER { 0 } else { index + 1 }; round_q14(sample.wrapping_mul(self.width)) } /// Synthesizes two Q14 channels with one stamped model for the two - /// channels. Each channel has its own feedback history. + /// channels. Each bank slot and channel has its own feedback history. /// - /// The function applies the aspiration mix one time to the stereo - /// midpoint. Then it adds the change of the midpoint to the two channels. - /// If aspiration is active, the function reads one random value for each - /// frame. The history cursor is the same for the two channels. It - /// advances only after the two channels. + /// If `allow_noise` is `true`, the function applies the aspiration mix one + /// time to the stereo midpoint and adds the change to the two channels. + /// Then, if aspiration is active, the function reads one random value for + /// each frame. The history cursor advances after the two channels. pub(crate) fn forward_stereo( &mut self, + slot: usize, mut samples: [i32; 2], position: i32, + allow_noise: bool, context: &mut NumericContext, ) -> [i32; 2] { - let mid = samples[0].wrapping_add(samples[1]).wrapping_shr(1); - let noise = self.add_noise(mid, context).wrapping_sub(mid); - for sample in &mut samples { - *sample = sample.wrapping_add(noise); + if allow_noise { + let mid = samples[0].wrapping_add(samples[1]).wrapping_shr(1); + let noise = self.add_noise(mid, context).wrapping_sub(mid); + for sample in &mut samples { + *sample = sample.wrapping_add(noise); + } } let mut coefficients = [0; MAX_ORDER]; let order = self.coefficients(position, &mut coefficients); + let index = self.history_index[slot]; for (channel, sample) in samples.iter_mut().enumerate() { let mut sum = 0_i32; for (i, &coefficient) in coefficients[..order].iter().enumerate() { sum = sum.wrapping_add( - self.history[channel][(self.history_index + MAX_ORDER - i - 1) % MAX_ORDER] + self.history[slot][channel][(index + MAX_ORDER - i - 1) % MAX_ORDER] .wrapping_mul(coefficient), ); } *sample = sample.wrapping_add(round_q14(sum)); - self.history[channel][self.history_index] = *sample; + self.history[slot][channel][index] = *sample; *sample = round_q14(sample.wrapping_mul(self.width)); } - self.history_index = (self.history_index + 1) % MAX_ORDER; + self.history_index[slot] = (index + 1) % MAX_ORDER; samples } } diff --git a/src/processor.rs b/src/processor.rs index cc910f4..89e9ca3 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -41,9 +41,9 @@ pub struct Processor { /// The reverse-loop history, which records also while its wet output is /// disabled. alien: Alien, - /// The delay network and the damping filters. + /// Dual delay networks and damping filters. /// - /// In bypass, their histories do not change. + /// If disabled, active tails decay with zero input and then 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 and after a reset. last_resample_ratio: f32, /// The count of rendered frames since reset, with drain frames included. /// @@ -457,18 +456,19 @@ impl Processor { /// Validates all configuration fields and applies them. /// /// 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. + /// that does not change keeps its state. Live changes to voice mode, choir + /// delay, formant enable, stereo output, Alien and reverb mode crossfade + /// smoothly without audio resets. 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. A change of reverb mode decays the previous bank while a + /// cleared bank starts the new mode. If you disable Punch or Warm, the + /// history of that stage stops. If you disable reverb, active tails decay + /// with zero input and then clear. Alien continues to record. If you + /// enable Alien, it starts a new capture epoch. 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 +491,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 +707,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 and after a + /// reset. pub resample_ratio: f32, /// The reported input pitch period in samples, with fractional samples. /// @@ -755,10 +747,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 +775,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"), @@ -811,8 +802,8 @@ pub struct Telemetry { /// where 1 is full scale. /// /// The contribution is the wet signal times the mix, before the output - /// gain. It is the larger of the two channels. While the reverb is - /// disabled, the window gets no new values. + /// gain. It is the larger of the two channels. While all reverb banks are + /// idle, the window gets no new values. pub reverb_wet_peak: f32, /// How periodic the tracked input is, in 0..=1. /// @@ -874,8 +865,7 @@ pub struct Telemetry { pub alien_phase_frames: u32, /// The wrapping count of formant analyses since construction. /// - /// The count increases every 441 frames while the formant stage is - /// enabled. Compare two values to find if + /// The count increases every 441 frames. Compare two values to find if /// [`Processor::formant_envelope`] can give a new result. pub formant_generation: u32, } diff --git a/src/resynthesis.rs b/src/resynthesis.rs index 34e98fa..9e36f06 100644 --- a/src/resynthesis.rs +++ b/src/resynthesis.rs @@ -4,20 +4,17 @@ //! the correction and control steps that are due. The raw input, the tracked //! periods and the correction ratios use the same history cursor. //! -//! The source comes from a fixed overlap buffer. If formants are enabled, -//! this buffer holds the output of the formant inverse analysis. If not, -//! it holds the raw input. Voice readers read this source at fractional -//! positions. If the shift is upward, prepared low-pass filters also -//! change the source. +//! The source comes from two aligned 11,568-frame buffers. One buffer holds +//! the delayed raw input. The other buffer holds the continuous output of the +//! formant inverse analysis. Voice readers read these buffers at fractional +//! positions. If the shift is upward, prepared low-pass filters also change +//! both sources. //! -//! Choir renders the lead voice first. Then it makes delayed secondary voices -//! with drift from the lead history. Harmony renders the lead voice and four -//! readers with independent controls. It applies formant synthesis after the -//! 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. +//! Active and shadow 16-reader banks crossfade across mode and choir-delay +//! switches. Every reader slot uses a crossfade across pitch-period jumps. +//! Choir and Harmony both write the rendered lead history on every frame. +//! Harmonic modulation applies to the wet mix. Then the code blends in 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 +211,8 @@ 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 crossfades the mono and panned voice buses over + /// 256 frames and does not reset audio histories or feedback. pub stereo_output: bool, /// The controls for the four harmony voices. The default is MIDI-channel /// allocation. @@ -345,6 +342,185 @@ 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 Q14 step for 256-frame bank, formant and stereo crossfades. +const SWITCH_FADE_STEP: Q14 = Q14::from_bits(64); +/// Half of `Q14::ONE`, used to keep the louder bank on rapid switches. +const HALF_FADE: Q14 = Q14::from_bits(8192); + +/// Blends `mono` and `panned` stereo buses with `stereo_mix` in Q14. +#[inline] +fn blend_stereo_bus(mono: [Q14; 2], panned: [Q14; 2], stereo_mix: Q14) -> [Q14; 2] { + if stereo_mix == Q14::ZERO { + mono + } else if stereo_mix == Q14::ONE { + panned + } else { + let mono_weight = Q14::ONE - stereo_mix; + [ + (mono[0].mul::<14, 28>(mono_weight) + panned[0].mul::<14, 28>(stereo_mix)).rescale(), + (mono[1].mul::<14, 28>(mono_weight) + panned[1].mul::<14, 28>(stereo_mix)).rescale(), + ] + } +} + +/// Blends two stereo Q14 frames with `weight` for `right`. +#[inline] +fn blend_frames(left: [Q14; 2], right: [Q14; 2], weight: Q14) -> [Q14; 2] { + let inv = Q14::ONE - weight; + [ + (left[0].mul::<14, 28>(inv) + right[0].mul::<14, 28>(weight)).rescale(), + (left[1].mul::<14, 28>(inv) + right[1].mul::<14, 28>(weight)).rescale(), + ] +} + +/// One preallocated 16-reader bank with per-voice period-jump crossfades. +#[derive(Clone, Copy, Debug)] +struct VoiceBank { + /// The voice mode that this bank renders. + mode: MultiVoiceMode, + /// The number of choir voices in this bank, in `1..=16`. + choir_voices: u8, + /// The formant synthesis slot (`0` or `1`) that this bank owns. + slot: usize, + /// The configured integer frame offset of each voice. Harmony uses zero. + delays: [i32; 16], + /// The Q14 fractional reader positions. + positions: [Q14; 16], + /// The previous Q14 reader positions for crossfades after period jumps. + old_positions: [Q14; 16], + /// The Q14 weights of the new reader positions, toward `1.0`. + fades: [Q14; 16], + /// The Q14 left and right gains of the choir voices in this bank. + pan: [[Q14; 2]; 16], + /// The Q14 pan gains of the harmony voices in this bank. + harmony_pan: [[Q14; 2]; HARMONY_VOICES], +} + +impl VoiceBank { + /// Creates an initialized 16-reader bank for `slot`. + fn new(slot: usize, mode: MultiVoiceMode, choir_voices: u8) -> Self { + let initial = position_of(-READER_LAG_FRAMES); + Self { + mode, + choir_voices, + slot, + delays: [0; 16], + positions: [initial; 16], + old_positions: [initial; 16], + fades: [Q14::ONE; 16], + pan: [[Q14::ONE; 2]; 16], + harmony_pan: [[Q14::ZERO; 2]; HARMONY_VOICES], + } + } + + /// Scales the fixed choir frame offsets and puts all 16 readers behind + /// `write`. + fn configure_delays( + &mut self, + write: usize, + mode: MultiVoiceMode, + choir_voices: u8, + choir_delay: f32, + ) { + self.mode = mode; + self.choir_voices = choir_voices; + let parameter = if mode == MultiVoiceMode::Choir { + choir_delay + } else { + 0.0 + }; + for (voice, seed) in SEEDS.iter().enumerate() { + self.delays[voice] = (*seed as f64 * (parameter as f64 * 0.005)) as i32; + let position = position_of(write as i32 - READER_LAG_FRAMES - self.delays[voice]); + self.positions[voice] = position; + self.old_positions[voice] = position; + self.fades[voice] = Q14::ONE; + } + } + + /// Updates the choir and harmony stereo pan gains of this bank. + fn configure_pan(&mut self, choir_voices: u8, choir_spread_percent: f32, harmony_gain: f32) { + self.choir_voices = choir_voices; + for voice in 0..choir_voices as usize { + if choir_voices > 1 { + let normalized = (voice as f64 + voice as f64) / (choir_voices as f64 - 1.0) - 1.0; + let angle = 0.785398163565 + - (choir_spread_percent as f64 * 0.785398163565 * 0.01) * normalized; + self.pan[voice] = [Q14::from_f64(angle.cos()), Q14::from_f64(angle.sin())]; + } else { + self.pan[voice] = [Q14::ONE; 2]; + } + } + for (voice, fraction) in [0.3333333333333333, 0.6666666666666666, 0.0, 1.0] + .into_iter() + .enumerate() + { + let angle: f64 = 1.57079632713 * fraction; + let gain = harmony_gain as f64; + self.harmony_pan[voice] = [ + Q14::from_f64(gain * angle.cos()), + Q14::from_f64(gain * angle.sin()), + ]; + } + } + + /// Moves all 16 reader coordinates back by `HISTORY` when `write` wraps. + fn wrap_origin(&mut self) { + let shift = position_of(HISTORY as i32); + for voice in 0..16 { + self.positions[voice] = self.positions[voice] - shift; + self.old_positions[voice] = self.old_positions[voice] - shift; + } + } + + /// Advances one Q14 reader by `ratio` and starts a period crossfade if it + /// jumps at a boundary. + fn move_reader(&mut self, write: usize, voice: usize, ratio: Q14, period: Q6) -> Q14 { + let offset = self.delays[voice]; + self.old_positions[voice] = self.old_positions[voice] + ratio; + let mut position = self.positions[voice] + ratio; + let write = write as i32; + let upper = position_of(write - 40 - offset); + let span = (period.to_bits() >> 6).wrapping_mul(12).wrapping_div(10); + let lower = position_of( + write + .wrapping_sub(span) + .wrapping_sub(40) + .wrapping_sub(offset), + ); + if position >= upper { + self.old_positions[voice] = position; + self.fades[voice] = Q14::ZERO; + position = position - period.rescale(); + } else if position <= lower { + self.old_positions[voice] = position; + self.fades[voice] = Q14::ZERO; + position = position + period.rescale(); + } + self.positions[voice] = position; + position + } + + /// Interpolates `buffer` at `voice` and blends `old_positions` if a jump + /// crossfade is active. + fn sample_voice(&self, buffer: &[Q14; HISTORY], voice: usize) -> (Q14, i32) { + let (mut value, center) = history::interpolation(buffer, self.positions[voice]); + let fade = self.fades[voice]; + if fade < Q14::ONE { + let (old, _) = history::interpolation(buffer, self.old_positions[voice]); + value = value.mul(fade) + old.mul(Q14::ONE - fade); + } + (value, center) + } + + /// Advances the period-jump crossfade of `voice` by one frame. + fn step_fade(&mut self, voice: usize) { + let fade = self.fades[voice]; + if fade < Q14::ONE { + self.fades[voice] = (fade + FADE_STEP).min(Q14::ONE); + } + } +} /// Returns the reader position at the start of the history frame `frame`. #[inline] @@ -384,15 +560,15 @@ pub(crate) struct Resynthesis { /// The active correction targets and an independent MIDI keyboard for /// correction. scale: CorrectionTable, - /// The delayed source audio after the two prepared shift filters. If - /// formants are enabled, the source is inverse-filtered. + /// The delayed raw source audio after the two prepared shift filters. filtered: Box<[Q14; HISTORY]>, - /// The history of the rendered choir lead. All secondary choir voices - /// read this history. + /// The delayed inverse-filtered LPC residual after its two shift filters. + lpc_filtered: Box<[Q14; HISTORY]>, + /// The history of the rendered lead voice. Secondary choir voices read + /// this history, and every frame writes it. lead: Box<[Q14; HISTORY]>, - /// The Q6 tracked periods, aligned to the audio. The lead voice can - /// replace a delayed entry with its resampled output period. This aligns - /// the secondary voices. + /// The Q6 tracked periods, aligned to the audio. The lead voice replaces + /// the delayed entry with its resampled output period on every frame. periods: Box<[Q6; HISTORY]>, /// The last usable Q6 tracker periods. The code keeps them through /// unvoiced gaps. @@ -400,28 +576,20 @@ pub(crate) struct Resynthesis { /// The Q14 ratios of the correction only, aligned to each recorded input /// frame. ratios: Box<[Q14; HISTORY]>, - /// The fixed memory for the analysis overlap. It gives the source a delay - /// of 1,543 frames. + /// The fixed memory for the LPC analysis overlap, for a total delay of + /// 1,543 frames. overlap: [Q14; OVERLAP_FRAMES], /// The current slot in the overlap ring. overlap_index: usize, - /// The configured integer frame offset of each voice. Harmony uses - /// offsets of zero. - delays: [i32; 16], - /// The Q14 fractional reader positions. When the writer wraps, the code - /// moves them back by HISTORY. - positions: [Q14; 16], + /// The active 16-reader voice bank. + active: VoiceBank, + /// The shadow 16-reader voice bank for mode and choir-delay crossfades. + shadow: VoiceBank, /// The Q14 random choir drift offsets of the secondary voices. drift: [Q14; 16], /// The Q14 multipliers, each equal to 1.0 plus the drift. An audio reset /// sets them to 1.0, but it keeps the drift state. drift_ratio: [Q14; 16], - /// The Q14 left and right gains of the choir voices. The code reads them - /// only if the stereo pan is enabled. - pan: [[Q14; 2]; 16], - /// The Q14 pan gains of the harmony voices. They include the configured - /// harmony level. - harmony_pan: [[Q14; 2]; HARMONY_VOICES], /// The last Q14 target ratios from the harmony controller. harmony_ratios: [Q14; HARMONY_VOICES], /// The last Q12 gain envelopes from the harmony controller. An audio @@ -434,9 +602,10 @@ pub(crate) struct Resynthesis { /// The signed history frame that the formant model used for the last /// frame. The audio path sets it, and only the formant envelope reads it. formant_position: i32, - /// Two cascaded anti-alias filter sections. If the shift is not upward, - /// they have coefficients of 1.0 and zero. + /// Two cascaded anti-alias filter sections for the raw source. post: [Biquad; 2], + /// Two cascaded anti-alias filter sections for the LPC source. + lpc_post: [Biquad; 2], /// The current smoothed Q14 correction ratio. It does not include the /// global shift or the voice ratios. correction: Q14, @@ -461,12 +630,12 @@ 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 Q14 crossfade weight toward `active` across mode and delay switches. + bank_fade: Q14, + /// The Q14 crossfade weight of the formant path, ramped over 256 frames. + formant_mix: Q14, + /// The Q14 crossfade weight of the panned bus, ramped over 256 frames. + stereo_mix: Q14, /// The Q6 period that the code selected last for a voice. The modulation /// uses it. current_output_period: Q6, @@ -479,9 +648,11 @@ pub(crate) struct Resynthesis { /// The Q14 weight of new drift, from the choir detune and the drift /// decay. drift_amount: Q14, - /// The previous Q14 synthesized output for each channel. The glottal - /// envelope uses it. - previous_output: [Q14; 2], + /// The previous Q14 output of mono lead formants for each bank slot. + lead_previous_output: [Q14; 2], + /// The previous Q14 stereo output of formants for each bank slot and + /// channel. + previous_output: [[Q14; 2]; 2], } impl Resynthesis { @@ -515,23 +686,23 @@ impl Resynthesis { scale }, filtered: prepare_history(Q14::ZERO), + lpc_filtered: prepare_history(Q14::ZERO), lead: prepare_history(Q14::ZERO), periods: prepare_history(Q6::ZERO), previous_periods: prepare_history(Q6::ZERO), ratios: prepare_history(Q14::ONE), overlap: [Q14::ZERO; OVERLAP_FRAMES], overlap_index: 0, - delays: [0; 16], - positions: [Q14::ZERO; 16], + active: VoiceBank::new(0, config.mode, config.choir_voices), + shadow: VoiceBank::new(1, config.mode, config.choir_voices), drift: [Q14::ZERO; 16], drift_ratio: [Q14::ONE; 16], - pan: [[Q14::ONE; 2]; 16], - harmony_pan: [[Q14::ZERO; 2]; HARMONY_VOICES], harmony_ratios: [Q14::ONE; HARMONY_VOICES], harmony_gains: [Q12::ZERO; HARMONY_VOICES], voice_ratios: [Q14::ONE; HARMONY_VOICES + 1], formant_position: 0, post: [Biquad::new(), Biquad::new()], + lpc_post: [Biquad::new(), Biquad::new()], correction: Q14::ONE, correction_decay: Q14::ZERO, scale_initialized: false, @@ -541,13 +712,23 @@ impl Resynthesis { modulation: 0, modulation_phase: Q14::ZERO, dry_mix: Q8::ZERO, - old_position: position_of(-READER_LAG_FRAMES), - fade: Q14::ONE, + bank_fade: Q14::ONE, + formant_mix: if config.formant.enabled { + Q14::ONE + } else { + Q14::ZERO + }, + stereo_mix: if config.stereo_output { + Q14::ONE + } else { + Q14::ZERO + }, current_output_period: Q6::ZERO, control_counter: CONTROL_DUE, drift_decay: Q14::ZERO, drift_amount: Q14::ZERO, - previous_output: [Q14::ZERO; 2], + lead_previous_output: [Q14::ZERO; 2], + previous_output: [[Q14::ZERO; 2]; 2], }; result.configure_coefficients(); result.configure_shift_filters(); @@ -576,65 +757,53 @@ impl Resynthesis { let decay = (-std::f64::consts::LN_2 / base).exp(); self.drift_decay = Q14::from_f64(decay); self.drift_amount = Q14::from_f64((1.0 - decay) * 0.008 * self.config.choir_detune as f64); - for voice in 0..self.config.choir_voices as usize { - if self.config.choir_voices > 1 { - let normalized = - (voice as f64 + voice as f64) / (self.config.choir_voices as f64 - 1.0) - 1.0; - let angle = 0.785398163565 - - (self.config.choir_spread_percent as f64 * 0.785398163565 * 0.01) - * normalized; - self.pan[voice] = [Q14::from_f64(angle.cos()), Q14::from_f64(angle.sin())]; - } else { - self.pan[voice] = [Q14::ONE; 2]; - } - } - for (voice, fraction) in [0.3333333333333333, 0.6666666666666666, 0.0, 1.0] - .into_iter() - .enumerate() - { - let angle: f64 = 1.57079632713 * fraction; - let gain = self.config.harmony_gain as f64; - self.harmony_pan[voice] = [ - Q14::from_f64(gain * angle.cos()), - Q14::from_f64(gain * angle.sin()), - ]; - } + self.active.configure_pan( + self.config.choir_voices, + self.config.choir_spread_percent, + self.config.harmony_gain, + ); } - /// Prepares two low-pass sections if the global shift is upward. If not, - /// sets coefficients of 1.0 and zero. + /// Prepares two low-pass sections for both sources if the global shift is + /// upward. If not, sets coefficients of 1.0 and zero. /// /// A change of the coefficients keeps the filter histories. The code /// 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.lpc_post { + filter.set_design(design); + } + } else { + for filter in &mut self.post { + filter.bypass(); + } + for filter in &mut self.lpc_post { filter.bypass(); } } } - /// Scales the fixed choir frame offsets and puts all readers behind the - /// writer. - /// - /// Harmony uses offsets of zero. This function moves the readers. It does - /// not clear the audio histories, the drift or the overlap buffer. + /// Scales the fixed choir frame offsets of both banks and puts all readers + /// behind the writer. fn create_delays(&mut self) { - let parameter = if self.config.mode == MultiVoiceMode::Choir { - self.config.choir_delay - } else { - 0.0 - }; - for (voice, seed) in SEEDS.iter().enumerate() { - self.delays[voice] = (*seed as f64 * (parameter as f64 * 0.005)) as i32; - self.positions[voice] = - position_of(self.write as i32 - READER_LAG_FRAMES - self.delays[voice]); - } + self.active.slot = 0; + self.active.configure_delays( + self.write, + self.config.mode, + self.config.choir_voices, + self.config.choir_delay, + ); + self.shadow = self.active; + self.shadow.slot = 1; + self.bank_fade = Q14::ONE; } /// Applies a configuration that passed the full validation before. @@ -654,19 +823,40 @@ impl Resynthesis { self.configure_shift_filters(); } if old.mode != config.mode || old.choir_delay != config.choir_delay { - self.create_delays(); - } - if old.choir_voices < config.choir_voices { + if self.bank_fade >= HALF_FADE { + self.shadow = self.active; + } + let next_slot = 1 - self.shadow.slot; + let preserve_lead = + self.shadow.mode == MultiVoiceMode::Choir && config.mode == MultiVoiceMode::Choir; + self.active.slot = if preserve_lead { + self.shadow.slot + } else { + self.formant.reset_slot(next_slot); + self.lead_previous_output[next_slot] = Q14::ZERO; + self.previous_output[next_slot] = [Q14::ZERO; 2]; + next_slot + }; + self.active.configure_delays( + self.write, + config.mode, + config.choir_voices, + config.choir_delay, + ); + if preserve_lead { + self.active.positions[0] = self.shadow.positions[0]; + self.active.old_positions[0] = self.shadow.old_positions[0]; + self.active.fades[0] = self.shadow.fades[0]; + } + self.bank_fade = Q14::ZERO; + } 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]; + self.active.positions[voice] = self.active.positions[0]; + self.active.old_positions[voice] = self.active.positions[0]; + self.active.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(); - } } /// Releases the correction keys 0..=126 and resets the audio state. @@ -697,20 +887,34 @@ impl Resynthesis { self.formant.reset(); self.harmony.reset(); self.filtered.fill(Q14::ZERO); + self.lpc_filtered.fill(Q14::ZERO); self.lead.fill(Q14::ZERO); self.periods.fill(Q6::ZERO); self.previous_periods.fill(Q6::ZERO); self.ratios.fill(Q14::ONE); self.overlap.fill(Q14::ZERO); self.overlap_index = 0; - self.previous_output = [Q14::ZERO; 2]; + self.lead_previous_output = [Q14::ZERO; 2]; + self.previous_output = [[Q14::ZERO; 2]; 2]; for filter in &mut self.post { filter.reset(); } + for filter in &mut self.lpc_post { + filter.reset(); + } self.create_delays(); + self.configure_coefficients(); self.drift_ratio.fill(Q14::ONE); - self.old_position = self.positions[0]; - self.fade = Q14::ONE; + self.formant_mix = if self.config.formant.enabled { + Q14::ONE + } else { + Q14::ZERO + }; + self.stereo_mix = 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; @@ -935,109 +1139,395 @@ 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( + /// Synthesizes one mono Q14 excitation sample through `slot` and its + /// glottal filter. + fn synthesize_lead_formant( &mut self, - voice: usize, - ratio: Q14, - period: Q6, - offset: i32, - fade: bool, + slot: usize, + lpc_sample: Q14, + center: i32, + is_active: bool, + allow_noise: bool, + numeric: &mut NumericContext, ) -> Q14 { - let mut position = self.positions[voice] + ratio; - let write = self.write as i32; - let upper = position_of(write - 40 - offset); - let span = (period.to_bits() >> 6).wrapping_mul(12).wrapping_div(10); - let lower = position_of( - write - .wrapping_sub(span) - .wrapping_sub(40) - .wrapping_sub(offset), - ); - if position >= upper { - if fade { - self.old_position = position; - self.fade = Q14::ZERO; - } - position = position - period.rescale(); - } else if position <= lower { - if fade { - self.old_position = position; - self.fade = Q14::ZERO; - } - position = position + period.rescale(); + let formant_position = center - FORMANT_OFFSET_FRAMES; + if is_active { + self.formant_position = formant_position; } - self.positions[voice] = position; - position + let filtered = Q14::from_bits(self.formant.forward( + slot, + lpc_sample.to_bits(), + formant_position, + allow_noise, + numeric, + )); + let output = Q14::from_bits(self.formant.model_glottal( + filtered.to_bits(), + self.lead_previous_output[slot].to_bits(), + )); + self.lead_previous_output[slot] = output; + output } - /// 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. - /// 4. It stores the Q14 result in the lead history. - /// - /// Returns the lead sample and its effective ratio, for the modulation - /// state that follows. - fn render_lead(&mut self, delayed: usize, numeric: &mut NumericContext) -> (Q14, Q14) { + /// Renders the choir lead voice for the selected bank and stores it in + /// `self.lead`. + fn render_choir_lead( + &mut self, + is_active: bool, + delayed: usize, + delayed_period_ratio: (Q6, Q14), + allow_noise: bool, + numeric: &mut NumericContext, + ) -> (Q14, Q14, Q6) { let write = self.write; - let delay = ring(delayed as i32 - self.delays[0]); - let (period, mut ratio) = self.period_for(delay, write); - self.current_output_period = period; + let (period, mut ratio) = delayed_period_ratio; ratio = ratio.mul::<14, 14>(self.drift_ratio[0]).mul(self.shift); if period == Q6::ZERO { ratio = Q14::ONE; } if ratio != Q14::ZERO { - self.periods[delay] = period.div(ratio); + self.periods[delayed] = period.div(ratio); } - self.old_position = self.old_position + ratio; - let position = self.move_reader(0, ratio, period, self.delays[0], true); - 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 slot = if is_active { + self.active.move_reader(write, 0, ratio, period); + self.active.slot + } else { + self.shadow.move_reader(write, 0, ratio, period); + self.shadow.slot + }; + let value = if self.formant_mix == Q14::ZERO { + let (raw, _) = if is_active { + let sample = self.active.sample_voice(&self.filtered, 0); + self.active.step_fade(0); + sample + } else { + let sample = self.shadow.sample_voice(&self.filtered, 0); + self.shadow.step_fade(0); + sample + }; + raw + } else if self.formant_mix == Q14::ONE { + let (lpc, center) = if is_active { + let sample = self.active.sample_voice(&self.lpc_filtered, 0); + self.active.step_fade(0); + sample + } else { + let sample = self.shadow.sample_voice(&self.lpc_filtered, 0); + self.shadow.step_fade(0); + sample + }; + self.synthesize_lead_formant(slot, lpc, center, is_active, allow_noise, numeric) + } else { + let ((raw, _), (lpc, center)) = if is_active { + let raw = self.active.sample_voice(&self.filtered, 0); + let lpc = self.active.sample_voice(&self.lpc_filtered, 0); + self.active.step_fade(0); + (raw, lpc) + } else { + let raw = self.shadow.sample_voice(&self.filtered, 0); + let lpc = self.shadow.sample_voice(&self.lpc_filtered, 0); + self.shadow.step_fade(0); + (raw, lpc) + }; + let fmt = + self.synthesize_lead_formant(slot, lpc, center, is_active, allow_noise, numeric); + let raw_weight = Q14::ONE - self.formant_mix; + (raw.mul::<14, 28>(raw_weight) + fmt.mul::<14, 28>(self.formant_mix)).rescale() + }; + self.lead[write] = value; + (value, ratio, period) + } + + /// Renders the secondary choir voices of the selected bank from `self.lead` + /// and mixes them with `lead_value`. + fn render_choir_voices( + &mut self, + is_active: bool, + delayed: usize, + lead_value: Q14, + lead_ratio: Q14, + lead_period: Q6, + ) -> ([Q14; 2], Q14, Q6) { + let write = self.write; + let voice_count = if is_active { + self.active.choir_voices as usize + } else { + self.shadow.choir_voices as usize + }; + let lead_pan = if is_active { + self.active.pan[0] + } else { + self.shadow.pan[0] + }; + let mut mono_sum = lead_value; + let mut panned_sum: [Q14; 2] = [lead_value.mul(lead_pan[0]), lead_value.mul(lead_pan[1])]; + let mut final_ratio = lead_ratio; + let mut output_period = lead_period; + let mut voice = 1; + while voice + 4 <= voice_count { + let mut values = [Q14::ZERO; 4]; + for (lane, sample_out) in values.iter_mut().enumerate() { + let current_voice = voice + lane; + let offset = if is_active { + self.active.delays[current_voice] + } else { + self.shadow.delays[current_voice] + }; + let delay = ring(delayed as i32 - offset); + let (period, _) = self.period_for(delay, write); + output_period = period; + let ratio = self.drift_ratio[current_voice]; + final_ratio = ratio; + if is_active { + self.active.move_reader(write, current_voice, ratio, period); + *sample_out = self.active.sample_voice(&self.lead, current_voice).0; + self.active.step_fade(current_voice); + } else { + self.shadow.move_reader(write, current_voice, ratio, period); + *sample_out = self.shadow.sample_voice(&self.lead, current_voice).0; + self.shadow.step_fade(current_voice); + } + } + for (lane, value) in values.into_iter().enumerate() { + let current_voice = voice + lane; + let pan = if is_active { + self.active.pan[current_voice] + } else { + self.shadow.pan[current_voice] + }; + mono_sum = mono_sum + value; + panned_sum[0] = panned_sum[0] + value.mul(pan[0]); + panned_sum[1] = panned_sum[1] + value.mul(pan[1]); + } + voice += 4; } - if self.config.formant.enabled { - self.formant_position = center - FORMANT_OFFSET_FRAMES; - value = Q14::from_bits(self.formant.forward( - value.to_bits(), - self.formant_position, - numeric, - )); - value = Q14::from_bits( - self.formant - .model_glottal(value.to_bits(), self.previous_output[0].to_bits()), - ); - self.previous_output[0] = value; + for current_voice in voice..voice_count { + let offset = if is_active { + self.active.delays[current_voice] + } else { + self.shadow.delays[current_voice] + }; + let delay = ring(delayed as i32 - offset); + let (period, _) = self.period_for(delay, write); + output_period = period; + let ratio = self.drift_ratio[current_voice]; + final_ratio = ratio; + let (value, pan) = if is_active { + self.active.move_reader(write, current_voice, ratio, period); + let value = self.active.sample_voice(&self.lead, current_voice).0; + self.active.step_fade(current_voice); + (value, self.active.pan[current_voice]) + } else { + self.shadow.move_reader(write, current_voice, ratio, period); + let value = self.shadow.sample_voice(&self.lead, current_voice).0; + self.shadow.step_fade(current_voice); + (value, self.shadow.pan[current_voice]) + }; + mono_sum = mono_sum + value; + panned_sum[0] = panned_sum[0] + value.mul(pan[0]); + panned_sum[1] = panned_sum[1] + value.mul(pan[1]); } - self.lead[write] = value; - (value, ratio) + let mono_bus = Q14::ONE.mul(mono_sum); + let panned_bus = [Q14::ONE.mul(panned_sum[0]), Q14::ONE.mul(panned_sum[1])]; + ( + blend_stereo_bus([mono_bus, mono_bus], panned_bus, self.stereo_mix), + final_ratio, + output_period, + ) + } + + /// Renders a Harmony voice bank and optionally writes `self.lead` for + /// seamless switches to Choir. + fn render_harmony_bank( + &mut self, + is_active: bool, + delayed: usize, + delayed_period_ratio: (Q6, Q14), + write_lead: bool, + allow_noise: bool, + numeric: &mut NumericContext, + ) -> ([Q14; 2], Q14, Q6) { + let write = self.write; + let (period, ratio) = delayed_period_ratio; + let mut raw_mono = Q14::ZERO; + let mut raw_panned = [Q14::ZERO; 2]; + let mut lpc_mono = Q14::ZERO; + let mut lpc_panned = [Q14::ZERO; 2]; + let mut raw_lead = Q14::ZERO; + let mut lpc_lead = Q14::ZERO; + let mut lead_center = 0_i32; + let mut lead_ratio = Q14::ONE; + let mut final_ratio = Q14::ONE; + for voice_slot in 0..5 { + let mut current: Q14 = if voice_slot == 0 { + ratio + } else { + self.harmony_ratios[voice_slot - 1].mul(ratio) + }; + current = self.shift.mul(current); + if period == Q6::ZERO { + current = Q14::ONE; + } + if voice_slot == 0 { + lead_ratio = current; + } + final_ratio = current; + if is_active { + self.voice_ratios[voice_slot] = current; + self.active.move_reader(write, voice_slot, current, period); + } else { + self.shadow.move_reader(write, voice_slot, current, period); + } + let pan = if voice_slot > 0 { + if is_active { + self.active.harmony_pan[voice_slot - 1] + } else { + self.shadow.harmony_pan[voice_slot - 1] + } + } else { + [Q14::ONE; 2] + }; + if self.formant_mix < Q14::ONE { + let (mut value, _) = if is_active { + self.active.sample_voice(&self.filtered, voice_slot) + } else { + self.shadow.sample_voice(&self.filtered, voice_slot) + }; + if voice_slot == 0 { + raw_lead = value; + } else { + value = value.mul(self.harmony_gains[voice_slot - 1]); + } + raw_mono = raw_mono + value; + if voice_slot > 0 { + raw_panned[0] = raw_panned[0] + value.mul(pan[0]); + raw_panned[1] = raw_panned[1] + value.mul(pan[1]); + } else { + raw_panned[0] = raw_panned[0] + value; + raw_panned[1] = raw_panned[1] + value; + } + } + if self.formant_mix > Q14::ZERO { + let (mut value, center) = if is_active { + self.active.sample_voice(&self.lpc_filtered, voice_slot) + } else { + self.shadow.sample_voice(&self.lpc_filtered, voice_slot) + }; + if voice_slot == 0 { + lpc_lead = value; + lead_center = center; + } else { + value = value.mul(self.harmony_gains[voice_slot - 1]); + } + lpc_mono = lpc_mono + value; + if voice_slot > 0 { + lpc_panned[0] = lpc_panned[0] + value.mul(pan[0]); + lpc_panned[1] = lpc_panned[1] + value.mul(pan[1]); + } else { + lpc_panned[0] = lpc_panned[0] + value; + lpc_panned[1] = lpc_panned[1] + value; + } + } + if is_active { + self.active.step_fade(voice_slot); + } else { + self.shadow.step_fade(voice_slot); + } + } + let bank_slot = if is_active { + self.active.slot + } else { + self.shadow.slot + }; + let pos0 = if is_active { + self.active.positions[0] + } else { + self.shadow.positions[0] + }; + let raw_bus = if self.formant_mix < Q14::ONE { + blend_stereo_bus([raw_mono, raw_mono], raw_panned, self.stereo_mix) + } else { + [Q14::ZERO; 2] + }; + let fmt_bus = if self.formant_mix > Q14::ZERO { + let bus = blend_stereo_bus([lpc_mono, lpc_mono], lpc_panned, self.stereo_mix); + let formant_position = (pos0.to_bits() >> 14) - FORMANT_OFFSET_FRAMES; + if is_active { + self.formant_position = formant_position; + } + let mut synthesized = self + .formant + .forward_stereo( + bank_slot, + bus.map(Q14::to_bits), + formant_position, + allow_noise, + numeric, + ) + .map(Q14::from_bits); + for (channel, value) in synthesized.iter_mut().enumerate() { + *value = Q14::from_bits(self.formant.model_glottal( + value.to_bits(), + self.previous_output[bank_slot][channel].to_bits(), + )); + self.previous_output[bank_slot][channel] = *value; + } + synthesized + } else { + [Q14::ZERO; 2] + }; + if write_lead { + if lead_ratio != Q14::ZERO { + self.periods[delayed] = period.div(lead_ratio); + } + let lead_value = if self.formant_mix == Q14::ZERO { + raw_lead + } else if self.formant_mix == Q14::ONE { + self.synthesize_lead_formant( + bank_slot, + lpc_lead, + lead_center, + false, + false, + numeric, + ) + } else { + let fmt = self.synthesize_lead_formant( + bank_slot, + lpc_lead, + lead_center, + false, + false, + numeric, + ); + let raw_weight = Q14::ONE - self.formant_mix; + (raw_lead.mul::<14, 28>(raw_weight) + fmt.mul::<14, 28>(self.formant_mix)).rescale() + }; + self.lead[write] = lead_value; + } + let result = if self.formant_mix == Q14::ZERO { + raw_bus + } else if self.formant_mix == Q14::ONE { + fmt_bus + } else { + blend_frames(raw_bus, fmt_bus, self.formant_mix) + }; + (result, final_ratio, period) } /// Renders one mono PCM input frame into stereo Q14 samples. /// /// The order of calls follows the module pipeline: /// 1. Analysis and control. - /// 2. The delayed source. - /// 3. The voice readers. - /// 4. Formant synthesis. + /// 2. The raw and LPC delayed sources. + /// 3. The active and shadow voice banks. + /// 4. Formant synthesis and bus crossfades. /// 5. Modulation. /// 6. The dry and wet mix. /// - /// When the writer wraps, the code changes the coordinates of the active - /// readers. Their relative positions do not change. MIDI can make a - /// harmony control step occur. The choir control advances only if - /// tracking was active before this frame. + /// When the writer wraps, the code shifts the coordinates of all reader + /// slots in active banks. MIDI can make a harmony control step occur. The + /// choir control advances only if tracking was active before this frame. pub(crate) fn process_sample(&mut self, input: i16, numeric: &mut NumericContext) -> [Q14; 2] { let sample = Q14::from_bits(i32::from(input) >> 1); self.write += 1; @@ -1053,15 +1543,10 @@ impl Resynthesis { // to each fractional position. This keeps the distances that the jump // detection uses. if write == 0 { - let voices = if self.config.mode == MultiVoiceMode::Choir { - self.config.choir_voices as usize - } else { - 5 - }; - for voice in 0..voices { - self.positions[voice] = self.positions[voice] - position_of(HISTORY as i32); + self.active.wrap_origin(); + if self.bank_fade < Q14::ONE { + self.shadow.wrap_origin(); } - self.old_position = self.old_position - position_of(HISTORY as i32); } if step.restarted { self.correction = Q14::ONE; @@ -1099,112 +1584,54 @@ impl Resynthesis { if self.overlap_index == OVERLAP_FRAMES { self.overlap_index = 0; } - 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( - sample.to_bits(), - previous.to_bits(), - self.periods.as_slice(), - write, - step.previous_period.to_bits(), - )) - } else { - self.raw[ring(write as i32 - ANALYSIS_FRAMES as i32)] - }; - // 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. + let previous = self.raw[ring(write as i32 - 1)]; + self.overlap[self.overlap_index] = Q14::from_bits(self.formant.process_analysis( + sample.to_bits(), + previous.to_bits(), + self.periods.as_slice(), + write, + step.previous_period.to_bits(), + )); let overlap_read = (self.overlap_index + ANALYSIS_FRAMES) % OVERLAP_FRAMES; - let mut filtered = self.overlap[overlap_read]; - for filter in &mut self.post { - filtered = filter.process_sample(filtered); + let mut lpc_filtered = self.overlap[overlap_read]; + for filter in &mut self.lpc_post { + lpc_filtered = filter.process_sample(lpc_filtered); } - self.filtered[write] = filtered; + self.lpc_filtered[write] = lpc_filtered; let delayed = ring(write as i32 - OVERLAP_FRAMES as i32); let dry = self.raw[delayed]; - let mut mix = [Q14::ZERO; 2]; - let mut final_ratio = Q14::ONE; - if self.config.mode == MultiVoiceMode::Choir { - let voice_count = self.config.choir_voices as usize; - // Secondary voices read the lead history written by voice zero. - { - let (value, ratio) = self.render_lead(delayed, numeric); - final_ratio = ratio; - self.voice_ratios[0] = ratio; - for (channel, sum) in mix.iter_mut().enumerate() { - *sum = *sum - + if self.config.stereo_output { - value.mul(self.pan[0][channel]) - } else { - value - }; - } + let mut raw_filtered = dry; + for filter in &mut self.post { + raw_filtered = filter.process_sample(raw_filtered); + } + self.filtered[write] = raw_filtered; + + if self.config.formant.enabled { + if self.formant_mix < Q14::ONE { + self.formant_mix = (self.formant_mix + SWITCH_FADE_STEP).min(Q14::ONE); } - { - let mut voice = 1; - while voice + 4 <= voice_count { - let mut positions = [Q14::ZERO; 4]; - // After the lead update, set the reader positions in - // voice order. - for (lane, position) in positions.iter_mut().enumerate() { - let current_voice = voice + lane; - let delay = ring(delayed as i32 - self.delays[current_voice]); - let (period, _) = self.period_for(delay, write); - self.current_output_period = period; - let ratio = self.drift_ratio[current_voice]; - final_ratio = 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); - // Keep the voice and channel order of each wrapping sum. - for (lane, value) in values.into_iter().enumerate() { - let current_voice = voice + lane; - for (channel, sum) in mix.iter_mut().enumerate() { - *sum = *sum - + if self.config.stereo_output { - value.mul(self.pan[current_voice][channel]) - } else { - value - }; - } - } - voice += 4; - } - // The zero to three secondary readers that are left use - // scalar code. - for voice in voice..voice_count { - let delay = ring(delayed as i32 - self.delays[voice]); - let (period, _) = self.period_for(delay, write); - self.current_output_period = period; - let ratio = self.drift_ratio[voice]; - final_ratio = ratio; - let position = - self.move_reader(voice, ratio, period, self.delays[voice], false); - let (value, _) = history::interpolation(&self.lead, position); - for (channel, sum) in mix.iter_mut().enumerate() { - *sum = *sum - + if self.config.stereo_output { - value.mul(self.pan[voice][channel]) - } else { - value - }; - } - } + } else if self.formant_mix > Q14::ZERO { + self.formant_mix = (self.formant_mix - SWITCH_FADE_STEP).max(Q14::ZERO); + if self.formant_mix == Q14::ZERO { + self.formant.reset_synthesis(); + self.lead_previous_output = [Q14::ZERO; 2]; + self.previous_output = [[Q14::ZERO; 2]; 2]; } - // The multiplication by 1.0 keeps the wrap of the product. - for sum in &mut mix { - *sum = Q14::ONE.mul(*sum); + } + if self.config.stereo_output { + if self.stereo_mix < Q14::ONE { + self.stereo_mix = (self.stereo_mix + SWITCH_FADE_STEP).min(Q14::ONE); } - } else { - let (period, ratio) = self.period_for(delayed, write); - self.current_output_period = period; + } else if self.stereo_mix > Q14::ZERO { + self.stereo_mix = (self.stereo_mix - SWITCH_FADE_STEP).max(Q14::ZERO); + } + if self.bank_fade < Q14::ONE { + self.bank_fade = (self.bank_fade + SWITCH_FADE_STEP).min(Q14::ONE); + } + + let delayed_period_ratio = self.period_for(delayed, write); + if self.config.mode == MultiVoiceMode::Harmony { + let (period, ratio) = delayed_period_ratio; let counter = self.control_counter; self.control_counter += 1; if counter == CONTROL_DUE { @@ -1215,53 +1642,110 @@ impl Resynthesis { } else { period.div(ratio) }; - let (ratio, gain) = self.harmony.advance_voice(corrected_period, voice); - self.harmony_ratios[voice] = ratio; + let (voice_ratio, gain) = self.harmony.advance_voice(corrected_period, voice); + self.harmony_ratios[voice] = voice_ratio; self.harmony_gains[voice] = gain; } } - for slot in 0..5 { - let mut current: Q14 = if slot == 0 { - ratio - } else { - self.harmony_ratios[slot - 1].mul(ratio) - }; - current = self.shift.mul(current); - if period == Q6::ZERO { - current = Q14::ONE; - } - 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); - if slot > 0 { - value = value.mul(self.harmony_gains[slot - 1]); + } + + let (mut mix, final_ratio) = if self.bank_fade == Q14::ONE { + match self.active.mode { + MultiVoiceMode::Choir => { + let (lead_val, lead_ratio, lead_period) = + self.render_choir_lead(true, delayed, delayed_period_ratio, true, numeric); + self.voice_ratios[0] = lead_ratio; + let (bus, ratio, out_period) = + self.render_choir_voices(true, delayed, lead_val, lead_ratio, lead_period); + self.current_output_period = out_period; + (bus, ratio) } - 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 - }; + MultiVoiceMode::Harmony => { + let (bus, ratio, out_period) = self.render_harmony_bank( + true, + delayed, + delayed_period_ratio, + true, + true, + numeric, + ); + self.current_output_period = out_period; + (bus, ratio) } } - if self.config.formant.enabled { - self.formant_position = (self.positions[0].to_bits() >> 14) - FORMANT_OFFSET_FRAMES; - mix = self - .formant - .forward_stereo(mix.map(Q14::to_bits), self.formant_position, numeric) - .map(Q14::from_bits); - for (channel, value) in 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; + } else { + match (self.shadow.mode, self.active.mode) { + (MultiVoiceMode::Choir, MultiVoiceMode::Choir) => { + let (lead_val, lead_ratio, lead_period) = + self.render_choir_lead(true, delayed, delayed_period_ratio, true, numeric); + self.voice_ratios[0] = lead_ratio; + let (shadow_bus, _, _) = + self.render_choir_voices(false, delayed, lead_val, lead_ratio, lead_period); + let (active_bus, ratio, out_period) = + self.render_choir_voices(true, delayed, lead_val, lead_ratio, lead_period); + self.current_output_period = out_period; + (blend_frames(shadow_bus, active_bus, self.bank_fade), ratio) + } + (MultiVoiceMode::Choir, MultiVoiceMode::Harmony) => { + let (lead_val, lead_ratio, lead_period) = self.render_choir_lead( + false, + delayed, + delayed_period_ratio, + false, + numeric, + ); + let (shadow_bus, _, _) = + self.render_choir_voices(false, delayed, lead_val, lead_ratio, lead_period); + let (active_bus, ratio, out_period) = self.render_harmony_bank( + true, + delayed, + delayed_period_ratio, + false, + true, + numeric, + ); + self.current_output_period = out_period; + (blend_frames(shadow_bus, active_bus, self.bank_fade), ratio) + } + (MultiVoiceMode::Harmony, MultiVoiceMode::Choir) => { + let (shadow_bus, _, _) = self.render_harmony_bank( + false, + delayed, + delayed_period_ratio, + false, + false, + numeric, + ); + let (lead_val, lead_ratio, lead_period) = + self.render_choir_lead(true, delayed, delayed_period_ratio, true, numeric); + self.voice_ratios[0] = lead_ratio; + let (active_bus, ratio, out_period) = + self.render_choir_voices(true, delayed, lead_val, lead_ratio, lead_period); + self.current_output_period = out_period; + (blend_frames(shadow_bus, active_bus, self.bank_fade), ratio) + } + (MultiVoiceMode::Harmony, MultiVoiceMode::Harmony) => { + let (shadow_bus, _, _) = self.render_harmony_bank( + false, + delayed, + delayed_period_ratio, + false, + false, + numeric, + ); + let (active_bus, ratio, out_period) = self.render_harmony_bank( + true, + delayed, + delayed_period_ratio, + true, + true, + numeric, + ); + self.current_output_period = out_period; + (blend_frames(shadow_bus, active_bus, self.bank_fade), ratio) } } - } + }; if self.modulation != 0 { if self.current_output_period != Q6::ZERO { // The phase advances by depth x 4 x ratio / period, in Q14