diff --git a/README.md b/README.md index a06715f..b966970 100644 --- a/README.md +++ b/README.md @@ -347,7 +347,9 @@ sets the configuration cancels the drain. `reset()` also cancels the drain. ### Reset `reset()` keeps the configuration, the random stream and some controller and -filter state. If you need a fully new state, construct a new processor. +filter state. Configuration changes keep the audio histories, also when +`resynthesis.stereo_output` changes the voice pan. If you need a fully new +state, construct a new processor. ## Feedback and telemetry @@ -507,7 +509,7 @@ page that opens the JavaScript. | `Int16Array` finite tail | `beginDrain()`, `drain(left, right)`, `drainMono(audio)` | | `Float32Array` finite tail | `beginDrain()`, `drainF32(left, right)`, `drainMonoF32(audio)` | | Zero-copy `Float32` tail | `beginDrain()`, `drainF32InPlace(frames)`, `drainMonoF32InPlace(frames)` | -| Configured tail budget | `tailFrames()` | +| Tail budget | `tailFrames()` | | Reset or release memory | `reset()`, `free()`, `views.dispose()` | ### Audio buffers diff --git a/src/effects.rs b/src/effects.rs index eefeb20..c84d24d 100644 --- a/src/effects.rs +++ b/src/effects.rs @@ -3,8 +3,9 @@ //! Punch and Warm operate on mono PCM before resynthesis. The processor does //! not call their sample methods while they are disabled. Alien and reverb //! accept stereo Q14 frames after resynthesis. They have their own bypass -//! behavior. Alien continues to record during bypass. Reverb keeps its -//! current delay state during bypass. +//! transitions. Alien captures a fresh loop when you enable it, and ramps its +//! wet mix on each toggle. Reverb lets an active tail decay with zero input +//! during bypass, then clears its histories. //! //! The configuration types validate the public controls. The prepared stage //! types assume that these checks were successful. diff --git a/src/effects/alien.rs b/src/effects/alien.rs index 271cae5..01b0975 100644 --- a/src/effects/alien.rs +++ b/src/effects/alien.rs @@ -1,4 +1,4 @@ -//! Reverse-loop playback with a continuous input history and boundary fades. +//! Reverse-loop playback with a captured input history and boundary fades. use crate::error::check_count; use crate::numeric::fixed::{Fixed, Q14}; @@ -6,16 +6,30 @@ use crate::Error; /// The number of history frames that the loop reads from. const HISTORY_FRAMES: usize = 192_000; -/// The number of frames for the boundary fade at each loop boundary. +/// The maximum number of frames for the boundary fade and the wet ramp. const FADE_FRAMES: usize = 200; +/// Returns the boundary fade length for a validated loop length. +#[inline] +fn boundary_fade_frames(loop_frames: usize) -> usize { + if loop_frames == 1 { + 0 + } else { + FADE_FRAMES.min(loop_frames / 2) + } +} + /// Reverse playback of recent stereo audio in repeated loops with fades. /// -/// Alien comes after resynthesis. Its input history and loop phase advance -/// also when Alien is disabled. Thus, when you enable Alien, it can play -/// audio that it recorded during bypass. A change of the loop length keeps -/// the history and clamps the current phase into the new loop. The boundary -/// fades are 200 frames long at all sample rates. +/// Alien comes after resynthesis. When you enable Alien, it captures one loop +/// of fresh input while it holds the dry signal. Then it ramps the wet mix to +/// full level over 200 frames. When you disable Alien, it ramps the wet mix to +/// zero over 200 frames. +/// +/// If the loop length changes during wet playback, Alien ramps the active loop +/// to zero over 200 frames. Then it resets the phase and captures any extra +/// frames that the new loop needs. The boundary fade length is zero at a loop +/// length of one frame, and `min(200, loop_frames / 2)` at longer loop lengths. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] #[cfg_attr( @@ -25,13 +39,12 @@ const FADE_FRAMES: usize = 200; )] pub struct AlienConfig { /// Selects reversed playback instead of the direct input. The default is - /// `false`. The recording and the phase continue to advance in both - /// states. + /// `false`. Each toggle ramps the wet mix over 200 frames. pub enabled: bool, /// The loop length in frames, 1..=96000. The default is 95,999. /// This value is a frame count at the two rates. Thus, its duration in - /// seconds changes with the sample rate. A short loop can be fully inside - /// the fades. + /// seconds changes with the sample rate. The boundary fade is shorter for + /// short loops and is zero when `loop_frames` is 1. pub loop_frames: u32, } impl Default for AlienConfig { @@ -66,100 +79,204 @@ pub(crate) struct Alien { /// 192,000 stereo Q14 frames, which are allocated one time at /// construction. buffer: Vec<[Q14; 2]>, - /// The current recording position. The position of the reverse reader - /// comes from this cursor. + /// The current write position. The position of the reverse reader comes + /// from this cursor. read: usize, - /// The current frame in the loop. It is always less than `loop_len`. + /// The current frame in the loop. It is always less than + /// `active_loop_len`. phase: usize, - /// The validated loop length. It is not more than half of the history - /// capacity. - loop_len: usize, + /// The active loop length. It stays constant until `wet_frames` is zero. + active_loop_len: usize, /// The number of frames in `buffer` since construction or the last reset. written: usize, + /// The number of frames that Alien captured since it became active. + captured: usize, + /// The current frame in the 200-frame wet mix ramp, in 0..=200. + wet_frames: usize, + /// If `true`, the wet mix ramps to zero before the next loop state starts. + fading_out: bool, + /// If `true`, `captured` resets to zero when `wet_frames` reaches zero. + reset_capture: bool, } impl Alien { /// Allocates a silent stereo ring from validated loop settings. pub(crate) fn new(config: AlienConfig) -> Self { + let (captured, wet_frames) = if config.enabled { + (HISTORY_FRAMES, FADE_FRAMES) + } else { + (0, 0) + }; Self { config, buffer: vec![[Q14::default(); 2]; HISTORY_FRAMES], read: 0, phase: 0, - loop_len: config.loop_frames as usize, + active_loop_len: config.loop_frames as usize, written: 0, + captured, + wet_frames, + fading_out: false, + reset_capture: false, } } - /// Applies a validated configuration, keeps the recorded audio and clamps - /// the phase into the new loop, which is not empty. + /// Applies a validated configuration and does not clear the buffer. + /// + /// While `wet_frames` is above zero, `active_loop_len` stays unchanged + /// until the wet ramp reaches zero. pub(crate) fn set_config(&mut self, config: AlienConfig) { + let was_enabled = self.config.enabled; self.config = config; - self.loop_len = config.loop_frames as usize; - self.phase = self.phase.min(self.loop_len - 1); + if !config.enabled || !was_enabled { + if self.wet_frames == 0 { + self.active_loop_len = config.loop_frames as usize; + self.phase = 0; + self.captured = 0; + self.fading_out = false; + self.reset_capture = false; + } else { + self.fading_out = true; + self.reset_capture = true; + } + } else if self.wet_frames == 0 { + self.active_loop_len = config.loop_frames as usize; + self.phase = 0; + self.fading_out = false; + } else { + self.fading_out = + self.reset_capture || config.loop_frames as usize != self.active_loop_len; + } } - /// Returns the loop length and the current frame in the loop. + /// Returns the active loop length and the current frame in the loop. /// /// The frame is always less than the length. The stage state does not /// change. pub(crate) fn loop_state(&self) -> (usize, usize) { - (self.loop_len, self.phase) + (self.active_loop_len, self.phase) } - /// Clears the recorded audio and sets both cursors to zero, but keeps the - /// configured loop. + /// Returns the finite tail budget for the active state or an active ramp. + pub(crate) fn tail_frames(&self) -> usize { + if self.config.enabled { + let base = 2 * self.config.loop_frames as usize + FADE_FRAMES; + if self.fading_out { + base.saturating_add(self.wet_frames) + } else { + base + } + } else { + self.wet_frames + } + } + /// Clears the recorded audio and resets the cursors and ramps, while it + /// keeps the configured loop. pub(crate) fn reset(&mut self) { self.buffer[..self.written].fill([Q14::default(); 2]); self.written = 0; self.read = 0; self.phase = 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 - /// 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; - if self.written < HISTORY_FRAMES { - self.written += 1; + self.active_loop_len = self.config.loop_frames as usize; + if self.config.enabled { + self.captured = HISTORY_FRAMES; + self.wet_frames = FADE_FRAMES; + } else { + self.captured = 0; + self.wet_frames = 0; } - let result = if self.config.enabled { - let read = self.read + HISTORY_FRAMES - self.phase * 2; - let read = if read >= HISTORY_FRAMES { - read - HISTORY_FRAMES - } else { - read - }; - let distance = self.phase.min(self.loop_len - self.phase); - let mut result = self.buffer[read]; - if distance < FADE_FRAMES { - let gain: Q14 = Fixed::<0>::from_bits(distance as i32) - .div(Fixed::<0>::from_bits(FADE_FRAMES as i32)); - result = result.map(|sample| sample.mul::<14, 14>(gain)); - } - result + self.fading_out = false; + self.reset_capture = false; + } + /// Reads the current reverse frame and applies the loop boundary fade. + #[inline] + fn reverse_sample(&self) -> [Q14; 2] { + let read = self.read + HISTORY_FRAMES - self.phase * 2; + let read = if read >= HISTORY_FRAMES { + read - HISTORY_FRAMES } else { - input + read }; + let distance = self.phase.min(self.active_loop_len - self.phase); + let fade_frames = boundary_fade_frames(self.active_loop_len); + let mut result = self.buffer[read]; + if distance < fade_frames { + let gain: Q14 = Fixed::<0>::from_bits(distance as i32) + .div(Fixed::<0>::from_bits(fade_frames as i32)); + result = result.map(|sample| sample.mul::<14, 14>(gain)); + } + result + } + /// Blends the direct input and the reverse sample with the Q14 wet ramp. + #[inline] + fn mix_wet(&self, input: [Q14; 2], reverse: [Q14; 2]) -> [Q14; 2] { + if self.wet_frames == 0 { + input + } else if self.wet_frames >= FADE_FRAMES { + reverse + } else { + let wet: Q14 = Fixed::<0>::from_bits(self.wet_frames as i32) + .div(Fixed::<0>::from_bits(FADE_FRAMES as i32)); + let dry = Q14::ONE - wet; + [ + input[0].mul::<14, 14>(dry) + reverse[0].mul::<14, 14>(wet), + input[1].mul::<14, 14>(dry) + reverse[1].mul::<14, 14>(wet), + ] + } + } + /// Advances the write cursor by one frame in the history ring. + #[inline] + fn advance_read(&mut self) { self.read += 1; if self.read == HISTORY_FRAMES { self.read = 0; } + } + /// Advances the loop phase by one frame and wraps at `active_loop_len`. + #[inline] + fn advance_phase(&mut self) { self.phase += 1; - if self.phase == self.loop_len { + if self.phase == self.active_loop_len { self.phase = 0; } - result } -} - -/// Returns the finite tail budget: two loop lengths plus the boundary -/// fade. -/// -/// The value is zero when Alien is disabled. It is a configured budget, -/// not a measured tail. -pub(crate) fn tail_frames(config: AlienConfig) -> usize { - if config.enabled { - 2 * config.loop_frames as usize + FADE_FRAMES - } else { - 0 + /// Captures input, holds the dry signal until the loop fills, and ramps + /// the Q14 wet mix over 200 frames on each transition. + pub(crate) fn process_sample(&mut self, input: [Q14; 2]) -> [Q14; 2] { + if !self.config.enabled && self.wet_frames == 0 { + return input; + } + self.buffer[self.read] = input; + if self.written < HISTORY_FRAMES { + self.written += 1; + } + if self.config.enabled && !self.reset_capture { + self.captured = (self.captured + 1).min(HISTORY_FRAMES); + } + if self.fading_out || !self.config.enabled { + let reverse = self.reverse_sample(); + self.wet_frames -= 1; + let result = self.mix_wet(input, reverse); + self.advance_read(); + self.advance_phase(); + if self.wet_frames == 0 { + self.active_loop_len = self.config.loop_frames as usize; + self.phase = 0; + self.fading_out = false; + if self.reset_capture || !self.config.enabled { + self.captured = 0; + self.reset_capture = false; + } + } + return result; + } + if self.captured < self.active_loop_len { + self.advance_read(); + return input; + } + let reverse = self.reverse_sample(); + if self.wet_frames < FADE_FRAMES { + self.wet_frames += 1; + } + let result = self.mix_wet(input, reverse); + self.advance_read(); + self.advance_phase(); + result } } diff --git a/src/effects/reverb.rs b/src/effects/reverb.rs index 335a9fa..d20fe9b 100644 --- a/src/effects/reverb.rs +++ b/src/effects/reverb.rs @@ -6,12 +6,22 @@ use crate::numeric::fixed::{Fixed, Q14}; use crate::processor::OutputLayout; use crate::{Error, SampleRate}; +/// The step for a 256-frame Q14 gain ramp (`16384 / 256`). +const RAMP_STEP: Q14 = Q14::from_bits(64); + +/// Returns the frames that remain for a 256-frame Q14 ramp to reach zero. +#[inline] +fn ramp_frames(fade: Q14) -> usize { + (fade.to_bits().max(0) as usize).div_ceil(64) +} + /// The echo or reverberation network. The default is [`Self::Echo`]. /// -/// All modes share one delay buffer. A mode change uses the same buffer -/// contents and damping filter memories. Thus a transition can play audio -/// from the previous network. All modes keep the stereo dry input. Schroeder -/// adds the same wet signal to the two channels. +/// All modes share one delay buffer. If the mode changes while the reverb is +/// active, the stage ramps the wet gain to zero over 256 frames. Then it +/// clears the delay buffer and the damping filters, and ramps the new mode +/// over 256 frames. All modes keep the stereo dry input. Schroeder adds the +/// same wet signal to the two channels. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), @@ -36,12 +46,14 @@ pub enum ReverbMode { /// The reverb after Alien, with controls for the network, the wet mix and the /// decay. /// -/// The reverb is disabled by default. In bypass, the stage returns the input -/// and does not advance the delay network or the damping filters. If the -/// stage is enabled and the mix is zero, the network still operates. A reset -/// clears the delay buffer but keeps the memories of the damping filters. The -/// mix, diffusion and decay controls are quantized to Q14. The function of -/// each control changes with the network. +/// The reverb is disabled by default. If you disable an active reverb, the +/// stage ramps the network input to zero over 256 frames. Then the decay tail +/// finishes before the stage clears the delay buffer and the damping filters. +/// If the stage is enabled and the mix is zero, the network still operates. +/// +/// A reset clears the delay buffer and keeps the memories of the damping +/// filters. The mix, diffusion and decay controls are quantized to Q14. The +/// function of each control changes with the network. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] #[cfg_attr( @@ -50,8 +62,9 @@ pub enum ReverbMode { serde(rename_all = "camelCase") )] pub struct ReverbConfig { - /// Enables the selected network. The default is `false`. In bypass, the - /// histories do not change. + /// Enables the selected network. The default is `false`. If you set this + /// field to `false`, the network input ramps to zero over 256 frames and + /// any active tail decays before a clear. pub enabled: bool, /// The topology of the delay network. The default is /// [`ReverbMode::Echo`]. @@ -141,20 +154,24 @@ pub(crate) fn validate_brightness_hz(brightness_hz: f32) -> Result<(), Error> { pub(crate) struct Reverb { /// The prepared sample rate for the cutoff and tap calculations. rate: SampleRate, - /// The validated controls and the selected network. + /// The validated controls that the host requested. config: ReverbConfig, + /// The controls that currently drive the delay topology. + active_config: ReverbConfig, /// The shared circular storage for all network topologies. delay: DelayLine, - /// The first damping filter. A delay reset or a mode change does not - /// clear its memories. + /// The first damping filter. A processor reset keeps its memories, while a + /// mode switch or a completed bypass tail clears them. lpf1: Biquad, - /// The second damping filter. It keeps its memories in the same way as - /// the first filter. + /// The second damping filter. It keeps and clears its memories in the same + /// way as the first filter. lpf2: Biquad, /// 67 prepared frame offsets into the shared ring. taps: [usize; 67], - /// The Q14 wet contribution. + /// The Q14 wet contribution of `active_config`. mix: Q14, + /// The Q14 wet contribution of `config`, for dry transitions across modes. + target_mix: Q14, /// The Q14 control for the diffusion or the echo distance. diffuse: Q14, /// The Q14 feedback coefficient, scaled by 100/105. @@ -162,6 +179,17 @@ pub(crate) struct Reverb { /// The Q14 allpass coefficients of MediumHall and LargeHall, scaled by /// `diffuse`. hall_diffuse: [Q14; 6], + /// The Q14 ramp for the network input and the dry blend, in 0..=1. + enable_fade: Q14, + /// The Q14 wet gain scale for mode switches, in 0..=1. + mode_fade: Q14, + /// If `true`, `mode_fade` moves to zero before the network clears. + fading_out_mode: bool, + /// The frames of silent-input decay that are left in bypass. + bypass_remaining: usize, + /// Consecutive bypass frames within the two-unit fixed-point limit-cycle + /// floor. + bypass_quiet_frames: usize, /// The Binaural delay of approximately 0.8 ms between the tap that gets /// the early sum and the filtered tap. Both channels use it. binaural_offset: usize, @@ -182,6 +210,12 @@ fn q14(coefficient: f64) -> Q14 { Q14::from_f64(coefficient) } +/// Quantizes a public mix control to Q14 after single-precision multiplication. +#[inline] +fn quantize_mix(mix: f32) -> Q14 { + Q14::from_f64((mix * 100.0) as f64 / 100.0) +} + /// Multiplies two Q14 values in `i64` and clamps the shifted result to `i32`. #[inline] fn mul(left: Q14, right: Q14) -> Q14 { @@ -200,17 +234,25 @@ impl Reverb { /// validated controls. pub(crate) fn new(rate: SampleRate, config: ReverbConfig) -> Self { let layout = reverb_layout(rate.hz()); + let enable_fade = if config.enabled { Q14::ONE } else { Q14::ZERO }; let mut result = Self { rate, config, + active_config: config, delay: DelayLine::new(), lpf1: Biquad::new(), lpf2: Biquad::new(), taps: layout.taps, mix: Q14::default(), + target_mix: quantize_mix(config.mix), diffuse: Q14::default(), decay: Q14::default(), hall_diffuse: [Q14::default(); 6], + enable_fade, + mode_fade: Q14::ONE, + fading_out_mode: false, + bypass_remaining: 0, + bypass_quiet_frames: 0, binaural_offset: layout.binaural_offset, wet_peak: 0, dirty: false, @@ -218,24 +260,24 @@ impl Reverb { result.configure_all(); result } - /// Quantizes the wet contribution unconditionally. + /// Quantizes the wet contribution of `active_config` unconditionally. fn configure_mix(&mut self) { - self.mix = Q14::from_f64((self.config.mix * 100.0) as f64 / 100.0); + self.mix = quantize_mix(self.active_config.mix); } /// Quantizes the diffusion control and the hall allpass coefficients /// unconditionally. fn configure_diffusion(&mut self) { - self.diffuse = Q14::from_f64((self.config.diffusion * 100.0) as f64 / 100.0); + self.diffuse = Q14::from_f64((self.active_config.diffusion * 100.0) as f64 / 100.0); self.hall_diffuse = [0.4, 0.5, 0.6, 0.8, 0.9, 0.95].map(|g| mul(self.diffuse, q14(g))); } /// Quantizes the feedback control unconditionally. fn configure_decay(&mut self) { - self.decay = Q14::from_f64((self.config.decay * 100.0) as f64 / 105.0); + self.decay = Q14::from_f64((self.active_config.decay * 100.0) as f64 / 105.0); } /// Updates the two low-pass filters unconditionally. fn configure_brightness_hz(&mut self) { let brightness = self - .config + .active_config .brightness_hz .min((self.rate.hz() as f64 * 0.49) as f32); let design = Design::low_pass_one_pole(self.rate.hz(), brightness); @@ -249,15 +291,14 @@ impl Reverb { self.configure_decay(); self.configure_brightness_hz(); } - /// Updates the changed coefficients and does not clear the delay or filter - /// state. + /// Updates `active_config` and quantizes only the controls that changed. /// /// The f32 multiplication by 100 occurs before the f64 division and the /// quantization. If you combine these expressions, the quantized /// coefficients can change. - pub(crate) fn set_config(&mut self, config: ReverbConfig) { - let old = self.config; - self.config = config; + fn apply_active_config(&mut self, config: ReverbConfig) { + let old = self.active_config; + self.active_config = config; if old.mix != config.mix { self.configure_mix(); } @@ -271,46 +312,151 @@ impl Reverb { self.configure_brightness_hz(); } } + /// Returns `true` while the reverb network or a transition fade is active. + fn is_running(&self) -> bool { + self.config.enabled + || self.bypass_remaining > 0 + || self.fading_out_mode + || self.enable_fade > Q14::ZERO + } + /// Returns `true` if scalar updates apply immediately to `active_config`. + fn can_update_active(&self) -> bool { + !self.fading_out_mode && (self.config.enabled || !self.is_running()) + } + /// Clears the delay buffer and both damping filters after a transition. + fn clear_all(&mut self) { + self.delay.reset(); + self.dirty = false; + self.lpf1.reset(); + self.lpf2.reset(); + self.bypass_quiet_frames = 0; + } + /// Applies validated controls and starts mode fades or bypass tails when + /// necessary. + pub(crate) fn set_config(&mut self, config: ReverbConfig) { + let was_running = self.is_running(); + let prev_enabled = self.config.enabled; + let old_mix = self.config.mix; + self.config = config; + if old_mix != config.mix { + self.target_mix = quantize_mix(config.mix); + } + if !was_running { + self.apply_active_config(config); + self.fading_out_mode = false; + self.mode_fade = Q14::ONE; + return; + } + if config.mode != self.active_config.mode { + if prev_enabled && !config.enabled { + let mut active = self.active_config; + active.enabled = true; + let tail = tail_frames(self.rate, active); + self.bypass_quiet_frames = 0; + if tail == 0 { + self.bypass_remaining = 0; + self.enable_fade = Q14::ZERO; + self.mode_fade = Q14::ONE; + self.fading_out_mode = false; + self.clear_all(); + self.apply_active_config(config); + return; + } + self.bypass_remaining = tail.saturating_add(ramp_frames(self.enable_fade)); + } + self.fading_out_mode = true; + return; + } + self.fading_out_mode = false; + if config.enabled { + self.apply_active_config(config); + self.bypass_remaining = 0; + self.bypass_quiet_frames = 0; + } else if prev_enabled { + let mut active = self.active_config; + active.enabled = true; + let tail = tail_frames(self.rate, active); + self.bypass_quiet_frames = 0; + if tail == 0 { + self.bypass_remaining = 0; + self.enable_fade = Q14::ZERO; + self.mode_fade = Q14::ONE; + self.clear_all(); + self.apply_active_config(config); + } else { + self.bypass_remaining = tail.saturating_add(ramp_frames(self.enable_fade)); + } + } + } /// Stores the wet contribution. If the value changed, quantizes it again. pub(crate) fn set_mix(&mut self, mix: f32) { let changed = self.config.mix != mix; self.config.mix = mix; if changed { + self.target_mix = quantize_mix(mix); + } + if self.can_update_active() && self.active_config.mix != mix { + self.active_config.mix = mix; self.configure_mix(); } } /// Stores the diffusion control. If the value changed, quantizes it again. pub(crate) fn set_diffusion(&mut self, diffusion: f32) { - let changed = self.config.diffusion != diffusion; self.config.diffusion = diffusion; - if changed { + if self.can_update_active() && self.active_config.diffusion != diffusion { + self.active_config.diffusion = diffusion; self.configure_diffusion(); } } /// Stores the feedback control. If the value changed, quantizes it again. pub(crate) fn set_decay(&mut self, decay: f32) { - let changed = self.config.decay != decay; self.config.decay = decay; - if changed { + if self.can_update_active() && self.active_config.decay != decay { + self.active_config.decay = decay; self.configure_decay(); } } /// Stores the low-pass cutoff. If the value changed, updates the filter /// designs. pub(crate) fn set_brightness_hz(&mut self, brightness_hz: f32) { - let changed = self.config.brightness_hz != brightness_hz; self.config.brightness_hz = brightness_hz; - if changed { + if self.can_update_active() && self.active_config.brightness_hz != brightness_hz { + self.active_config.brightness_hz = brightness_hz; self.configure_brightness_hz(); } } - /// Clears only the delay contents, and keeps the write cursor and the - /// damping memories. + /// Clears the delay contents and transition state, while it keeps the + /// write cursor and the damping memories. pub(crate) fn reset(&mut self) { if self.dirty { self.delay.reset(); self.dirty = false; } + self.apply_active_config(self.config); + self.enable_fade = if self.config.enabled { + Q14::ONE + } else { + Q14::ZERO + }; + self.mode_fade = Q14::ONE; + self.fading_out_mode = false; + self.bypass_remaining = 0; + self.bypass_quiet_frames = 0; + } + /// Returns the finite tail budget, with active bypass tails included. + pub(crate) fn tail_frames(&self) -> usize { + if self.config.enabled { + let base = tail_frames(self.rate, self.config); + if self.fading_out_mode { + base.saturating_add(ramp_frames(self.mode_fade)) + } else { + base + } + } else if self.fading_out_mode { + ramp_frames(self.mode_fade).max(ramp_frames(self.enable_fade)) + } else { + self.bypass_remaining.max(ramp_frames(self.enable_fade)) + } } /// Returns the largest absolute Q14 wet contribution since the last /// clear, as f32. @@ -321,30 +467,19 @@ impl Reverb { pub(crate) fn clear_wet_peak(&mut self) { self.wet_peak = 0; } - /// 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. `layout` selects the stereo - /// or mono wet peak measurement. The mono measurement uses a shift. - pub(crate) fn process_sample(&mut self, frame: [Q14; 2], layout: OutputLayout) -> [Q14; 2] { - if !self.config.enabled { - return frame; - } - self.dirty = true; - let [left, right] = frame; - let dry = Q14::ONE - self.mix; - let left_dry = mul(left, dry); - let right_dry = mul(right, dry); + /// Evaluates the active delay topology one time, advances the delay ring + /// and returns the scaled wet stereo pair. + fn step_network(&mut self, left: Q14, right: Q14, wet_gain: Q14) -> [Q14; 2] { let d = &mut self.delay; - let result = match self.config.mode { + let wet_terms = match self.active_config.mode { ReverbMode::Echo => { let t = &self.taps; d.put(mono(left, right), 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); [ - left_dry + mul(self.mix, d.get(t[25]) - d.get(t[32])), - right_dry + mul(self.mix, d.get(t[26]) - d.get(t[31])), + mul(wet_gain, d.get(t[25]) - d.get(t[32])), + mul(wet_gain, d.get(t[26]) - d.get(t[31])), ] } ReverbMode::Schroeder => { @@ -367,8 +502,8 @@ impl Reverb { ); d.allpass(t[40], t[43], self.decay); d.allpass(t[44], t[45], self.decay); - let wet = mul(self.mix, d.get(t[45])); - [left_dry + wet, right_dry + wet] + let wet = mul(wet_gain, d.get(t[45])); + [wet, wet] } ReverbMode::SmallRoom => { let t = &self.taps; @@ -386,10 +521,7 @@ impl Reverb { d.fir_sum(&[(t[16], q14(0.2)), (t[32], q14(0.2)), (t[51], q14(0.2))]); let right_wet = d.fir_sum(&[(t[49], q14(0.2)), (t[65], q14(0.2)), (t[17], q14(0.2))]); - [ - left_dry + mul(self.mix, left_wet), - right_dry + mul(self.mix, right_wet), - ] + [mul(wet_gain, left_wet), mul(wet_gain, right_wet)] } ReverbMode::Binaural => { let t = &self.taps; @@ -405,14 +537,15 @@ impl Reverb { ); d.put(a, tap); d.lpf(filter, &mut self.lpf1); - let out = left_dry + mul(self.mix, d.get(t[40] + filter) + a); + let wet_left = mul(wet_gain, d.get(t[40] + filter) + a); let b = mul( early, 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, right_dry + mul(self.mix, d.get(filter) + b)] + let wet_right = mul(wet_gain, d.get(filter) + b); + [wet_left, wet_right] } ReverbMode::MediumHall => { let t = &self.taps; @@ -439,10 +572,7 @@ impl Reverb { (t[52], q14(0.25)), (t[56], q14(0.2)), ]); - [ - left_dry + mul(self.mix, left_wet), - right_dry + mul(self.mix, right_wet), - ] + [mul(wet_gain, left_wet), mul(wet_gain, right_wet)] } ReverbMode::LargeHall => { let t = &self.taps; @@ -461,17 +591,71 @@ impl Reverb { d.fir_sum(&[(t[10], q14(0.6)), (t[36], q14(0.3)), (t[61], q14(0.3))]); let right_wet = d.fir_sum(&[(t[10], q14(0.6)), (t[37], q14(0.3)), (t[60], q14(0.3))]); - [ - left_dry + mul(self.mix, left_wet), - right_dry + mul(self.mix, right_wet), - ] + [mul(wet_gain, left_wet), mul(wet_gain, right_wet)] } }; d.step(); + wet_terms + } + /// Calculates the selected network one time and advances the ring by one + /// frame. + /// + /// When the stage is idle in bypass, no delay or filter history advances. + /// The internal mono averages use integer division toward zero. `layout` + /// selects the stereo or mono wet peak measurement. The mono measurement + /// uses a shift. + pub(crate) fn process_sample(&mut self, frame: [Q14; 2], layout: OutputLayout) -> [Q14; 2] { + if !self.config.enabled + && self.bypass_remaining == 0 + && !self.fading_out_mode + && self.enable_fade == Q14::ZERO + { + return frame; + } + self.dirty = true; + if self.config.enabled && self.enable_fade < Q14::ONE { + self.enable_fade = (self.enable_fade + RAMP_STEP).min(Q14::ONE); + } else if !self.config.enabled && self.enable_fade > Q14::ZERO { + self.enable_fade = (self.enable_fade - RAMP_STEP).max(Q14::ZERO); + } + if self.fading_out_mode { + self.mode_fade = (self.mode_fade - RAMP_STEP).max(Q14::ZERO); + } else if self.mode_fade < Q14::ONE { + self.mode_fade = (self.mode_fade + RAMP_STEP).min(Q14::ONE); + } + + let [left, right] = frame; + let dry = Q14::ONE - self.mix; + let steady = self.config.enabled + && !self.fading_out_mode + && self.enable_fade == Q14::ONE + && self.mode_fade == Q14::ONE; + let (dry_terms, wet_terms) = if steady { + let wet_terms = self.step_network(left, right, self.mix); + ([mul(left, dry), mul(right, dry)], wet_terms) + } else { + let net_left = mul(left, self.enable_fade); + let net_right = mul(right, self.enable_fade); + let enabled_dry = if self.fading_out_mode && self.config.enabled { + mul(dry, self.mode_fade) + + mul(Q14::ONE - self.target_mix, Q14::ONE - self.mode_fade) + } else { + dry + }; + let bypass_weight = Q14::ONE - self.enable_fade; + let dry_terms = [ + mul(left, bypass_weight) + mul(mul(left, enabled_dry), self.enable_fade), + mul(right, bypass_weight) + mul(mul(right, enabled_dry), self.enable_fade), + ]; + let wet_gain = mul(self.mix, self.mode_fade); + let wet_terms = self.step_network(net_left, net_right, wet_gain); + (dry_terms, wet_terms) + }; + let result = [dry_terms[0] + wet_terms[0], dry_terms[1] + wet_terms[1]]; // Telemetry only. The wet contribution is the output minus the dry // term. Mono calls measure the wet signal after the downmix. - let left_wet = result[0] - left_dry; - let right_wet = result[1] - right_dry; + let left_wet = result[0] - dry_terms[0]; + let right_wet = result[1] - dry_terms[1]; match layout { OutputLayout::Stereo => { for wet in [left_wet, right_wet] { @@ -487,6 +671,45 @@ impl Reverb { self.wet_peak = self.wet_peak.max(wet); } } + if self.fading_out_mode && self.mode_fade == Q14::ZERO { + if self.config.enabled { + self.clear_all(); + self.fading_out_mode = false; + self.apply_active_config(self.config); + self.bypass_remaining = 0; + } else if self.enable_fade == Q14::ZERO { + self.clear_all(); + self.fading_out_mode = false; + self.apply_active_config(self.config); + self.bypass_remaining = 0; + self.mode_fade = Q14::ONE; + } + } else if !self.config.enabled && self.bypass_remaining > 0 { + let quiet = self.enable_fade == Q14::ZERO + && wet_terms[0].abs().to_bits() <= 2 + && wet_terms[1].abs().to_bits() <= 2; + if quiet { + self.bypass_quiet_frames += 1; + } else { + self.bypass_quiet_frames = 0; + } + self.bypass_remaining -= 1; + if self.bypass_remaining == 0 || self.bypass_quiet_frames >= CAPACITY { + self.bypass_remaining = 0; + self.enable_fade = Q14::ZERO; + self.mode_fade = Q14::ONE; + self.clear_all(); + self.apply_active_config(self.config); + } + } else if !self.config.enabled + && !self.fading_out_mode + && self.bypass_remaining == 0 + && self.enable_fade == Q14::ZERO + { + self.mode_fade = Q14::ONE; + self.clear_all(); + self.apply_active_config(self.config); + } result } } diff --git a/src/formant.rs b/src/formant.rs index b4ea383..4ed37c2 100644 --- a/src/formant.rs +++ b/src/formant.rs @@ -287,6 +287,8 @@ pub(crate) struct Formant { /// If `true`, the next call to `smooth` clears the state of the /// correlation average. smooth_reset: bool, + /// If `true`, the next model design sets `blend` to 1.0 immediately. + snap_blend: bool, /// If `true`, the stage changed state since construction or the last reset. dirty: bool, /// The Q14 first-order coefficient for pre-emphasis and de-emphasis. @@ -372,6 +374,7 @@ impl Formant { smooth_index: 0, smooth_filled: 0, smooth_reset: true, + snap_blend: false, dirty: false, glottal: (0.5_f64.powf(1.0 / d2) * 16384.0) as i32, width: 16384, @@ -509,15 +512,48 @@ impl Formant { self.input.fill(0_i32); self.stamps.fill(Stamp::default()); - self.history = [[0; MAX_ORDER * 2]; 2]; - self.histories_match = true; - self.history_index = 0; + self.reset_synthesis(); self.stamp.current = (BANKS - 1) as u8; self.next_filter(); self.next_filter(); self.design_counter = 0; + self.smooth_reset = true; + self.snap_blend = false; + } + /// Clears the synthesis feedback history and the aspiration filter memory. + pub(crate) fn reset_synthesis(&mut self) { + self.history = [[0; MAX_ORDER * 2]; 2]; + self.histories_match = true; + self.history_index = 0; self.noise_filter.reset(); + } + /// Prepares the analysis history from `raw` when the formant stage becomes + /// active, and keeps active synthesis banks intact. + pub(crate) fn prepare_enable(&mut self, raw: &[Q14; HISTORY], write: usize) { + self.dirty = true; + let max_period = (self.rate.as_u32() as usize / 40).max(1); + let extra = (max_period / 10).max(1); + let count = (ANALYSIS_FRAMES + ORDER) + .max(2 * max_period + extra + 2) + .min(HISTORY - 1); + for offset in (1..=count).rev() { + let index = (write + HISTORY - offset) % HISTORY; + let previous = ring(index as i32 - 1); + let filtered = self.remove_glottal(raw[index].to_bits(), raw[previous].to_bits()); + let reverse_index = HISTORY - 1 - index; + self.input[reverse_index] = filtered; + if reverse_index < ORDER { + self.input[reverse_index + HISTORY] = filtered; + } + } + self.design_counter = 0; self.smooth_reset = true; + self.snap_blend = true; + } + /// Copies the synthesis feedback history from channel zero to channel one. + pub(crate) fn copy_channel_zero(&mut self) { + self.history[1] = self.history[0]; + self.histories_match = true; } /// Starts a new model and a new correlation window when pitch acquisition /// locks. @@ -813,7 +849,10 @@ impl Formant { self.smooth_reset = true; } } - if self.stamp.blend < 16384 { + if self.snap_blend { + self.stamp.blend = 16384; + self.snap_blend = false; + } else if self.stamp.blend < 16384 { self.stamp.blend = (self.stamp.blend + 1638).min(16384); } self.stamps[position] = self.stamp; diff --git a/src/lib.rs b/src/lib.rs index 80f8d33..6d42388 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -78,8 +78,9 @@ //! //! After the last input block, call [`Processor::begin_drain`] one time. Then //! render drain blocks until a call returns zero. Each call fills the unused -//! output with zeros. The drain uses a finite configured budget and mutes -//! aspiration. It is not a silence detector. +//! output with zeros. The drain uses the finite budget from +//! [`Processor::tail_frames`] and mutes aspiration. It is not a silence +//! detector. //! //! The call that uses all of the budget does the same reset as //! [`Processor::reset`]. This occurs also if that call returns audio. A diff --git a/src/processor.rs b/src/processor.rs index 9f8ae9b..7d8962f 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -1,8 +1,8 @@ //! The processor: audio blocks, timed controls, host feedback and the tail. -use crate::effects::alien::{self, Alien}; +use crate::effects::alien::Alien; use crate::effects::punch::Punch; -use crate::effects::reverb::{self, Reverb}; +use crate::effects::reverb::Reverb; use crate::effects::warm::Warm; use crate::events::{ValidatedEvent, ValidatedEvents}; use crate::numeric::rng::RandomStream; @@ -65,12 +65,12 @@ pub struct Processor { /// The pitch tracking and voice histories, in a box to keep the handle /// small. resynthesis: Box, - /// The reverse-loop history, which records also while its wet output is - /// disabled. + /// The reverse-loop history, with a captured loop and wet mix ramps. alien: Alien, /// The delay network and the damping filters. /// - /// In bypass, their histories do not change. + /// When you disable reverb, the network input ramps to zero over 256 + /// frames and an active tail decays before a clear. reverb: Reverb, /// The random sequence of this instance and the cached arctangent position. numeric: NumericContext, @@ -84,8 +84,7 @@ pub struct Processor { output_peaks: [i32; 2], /// The last ratio from correction only. /// - /// It is zero before the first `process` call, after a reset or after a - /// change of stereo output. + /// It is zero before the first `process` call or after a reset. last_resample_ratio: f32, /// The count of rendered frames since reset, with drain frames included. /// @@ -469,20 +468,18 @@ impl Processor { Ok(count) } - /// Returns the finite tail budget for the current configuration. + /// Returns the finite tail budget for the current configuration and active + /// stage transitions. /// - /// This value is a configured limit. It is not the number of drain frames - /// that are left, and it is not a measured decay time. It can include - /// silence. It can also stop filter output that continues for a long - /// time. + /// The budget includes active Alien ramps, reverb mode fades and reverb + /// bypass tails. It is not the number of drain frames that are left. It is + /// not a measured decay time. It can include silence. It can also stop + /// filter output that continues for a long time. pub fn tail_frames(&self) -> usize { self.resynthesis .tail_frames() - .saturating_add(alien::tail_frames(self.config.alien)) - .saturating_add(reverb::tail_frames( - self.preparation.sample_rate, - self.config.reverb, - )) + .saturating_add(self.alien.tail_frames()) + .saturating_add(self.reverb.tail_frames()) } /// Returns the fixed sample rate and block limit. @@ -684,17 +681,21 @@ impl Processor { /// /// The validation also examines the fields of disabled stages. A stage /// that does not change keeps its state. A change of `stereo_output` - /// resets the resynthesis audio state, Alien, the reverb delays, the peak - /// and the reported ratio. It also releases the harmony MIDI notes. It - /// keeps Punch, Warm, the correction keys, the random stream, the reverb - /// low-pass memories and the frame count. A change of `random_seed` starts - /// the random stream again. + /// ramps the voice pan weights over 256 frames and keeps the audio + /// histories, the feedback and the held MIDI notes. A change of + /// `random_seed` starts the random stream again. /// /// Each successful call cancels a drain, also for an identical - /// configuration. A change of reverb mode keeps the delay contents. If you - /// disable Punch, Warm or reverb, the history of that stage stops. Alien - /// continues to record. A change in either half of the `u64` seed starts - /// the stream again, but the new sequence uses only the low 32 bits. + /// configuration. If the reverb mode changes, the stage ramps the wet gain + /// to zero over 256 frames. Then it clears the delay buffer and the + /// damping filters, and ramps the new mode over 256 frames. + /// + /// If you disable Punch or Warm, the history of that stage stops. If you + /// disable reverb, its input ramps to zero over 256 frames and its active + /// tail decays before a clear. When you enable Alien, it captures a fresh + /// loop and ramps the wet mix over 200 frames. A change in either half of + /// the `u64` seed starts the stream again, but the new sequence uses only + /// the low 32 bits. /// /// # Errors /// @@ -717,10 +718,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.reset_post_resynthesis(); - } if self.config.resynthesis.random_seed != config.resynthesis.random_seed { self.numeric.random = RandomStream::new(config.resynthesis.random_seed as u32); } @@ -767,8 +764,7 @@ impl Processor { /// Clears the stages, the peak windows and the ratio after resynthesis. /// - /// Both a full reset and a change of stereo output clear this state. The - /// frame count does not change here. + /// The frame count does not change here. fn reset_post_resynthesis(&mut self) { self.alien.reset(); self.reverb.reset(); @@ -1095,8 +1091,8 @@ pub struct Feedback { /// unity. /// /// It does not include the configured pitch shift or the ratios of - /// individual voices. It is zero before processing, after a reset or after - /// a change of stereo output. + /// individual voices. It is zero before the first `process` call or after a + /// reset. pub resample_ratio: f32, /// The reported input pitch period in samples, with fractional samples. /// @@ -1135,10 +1131,10 @@ pub struct Feedback { pub voiced: bool, /// The largest absolute clipped output 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. Mono calls measure the sample after the downmix. - /// [`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. Mono + /// calls measure the sample after the downmix. [`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. @@ -1163,9 +1159,8 @@ pub struct Feedback { /// `Default` gives a snapshot with all zeros and no target. /// /// 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)] #[non_exhaustive] #[cfg_attr( @@ -1194,15 +1189,15 @@ pub struct Telemetry { /// /// The contribution is the wet signal times the mix, before the output /// gain. Stereo calls measure the larger of the two channels. Mono calls - /// measure the wet signal after the downmix. While the reverb is disabled, - /// the window gets no new values. + /// measure the wet signal after the downmix. Active bypass tails also + /// update this peak. While the reverb is idle in bypass, the window gets no + /// new values. pub reverb_wet_peak: f32, /// The pitch-correction ratio from the last processed frame, where 1 is /// unity, as [`Feedback::resample_ratio`] gives. /// /// It does not include the configured pitch shift or the ratios of - /// individual voices. It is zero before the first frame, after a reset or - /// after a change of stereo output. + /// individual voices. It is zero before the first frame or after a reset. pub resample_ratio: f32, /// The reported input pitch period in samples, with fractional samples, as /// [`Feedback::period_samples`] gives. @@ -1294,14 +1289,16 @@ pub struct Telemetry { /// it during release and updates it on each enabled frame. The value is 1 /// while Warm is disabled. pub warm_gain: f32, - /// The length of the Alien loop in frames, as - /// [`crate::AlienConfig::loop_frames`] gives. + /// The active length of the Alien loop in frames. + /// + /// It equals [`crate::AlienConfig::loop_frames`] after any active wet fade + /// to zero finishes. pub alien_loop_frames: u32, /// The current frame in the Alien loop. It is less than /// [`alien_loop_frames`](Self::alien_loop_frames). /// /// The reverse reader is two times this number of frames behind the - /// recording position. The value advances also while Alien is disabled. + /// write position after loop capture completes. pub alien_phase_frames: u32, /// The wrapping count of formant analyses since construction. /// diff --git a/src/resynthesis.rs b/src/resynthesis.rs index f0e844f..f6db037 100644 --- a/src/resynthesis.rs +++ b/src/resynthesis.rs @@ -16,8 +16,9 @@ //! voices are mixed. //! //! A reader jumps by one pitch period to stay in a range behind the writer. -//! The choir lead uses a crossfade across these jumps. Harmonic modulation -//! applies to the wet mix. Then the code blends in a delayed dry signal. +//! All active Choir and Harmony voices use a crossfade across these jumps. +//! Harmonic modulation applies to the wet mix. Then the code adds a delayed +//! dry signal. //! //! Audio, reader positions and pitch ratios use Q14. Periods use Q6, harmony //! gains use Q12 and the dry mix uses Q8. Some of these units use the same @@ -268,8 +269,9 @@ pub struct ResynthesisConfig { /// Enables a stereo pan for each voice. The default is `false`. /// /// This value is independent of the buffer layout of the process method. - /// A change to this value resets some audio histories and the feedback. - /// [`crate::Processor::set_config`] gives the details. + /// A change to this value ramps the voice pan weights over 256 frames and + /// keeps the audio histories. [`crate::Processor::set_config`] gives the + /// details. pub stereo_output: bool, /// The controls for the four harmony voices. The default is MIDI-channel /// allocation. @@ -441,6 +443,62 @@ const CONTROL_DUE: i32 = 100; const DRIFT_LIMIT: Q14 = Q14::from_bits(3276); /// The step for each frame of the crossfade after a reader jump. const FADE_STEP: Q14 = Q14::from_bits(0x333); +/// The number of frames in a full Q14 stage ramp (`16384 / 64`). +const FORMANT_RAMP_FRAMES: usize = 256; +/// The step for each frame of a 256-frame stage ramp (`16384 / 256`). +const STAGE_RAMP_STEP: Q14 = Q14::from_bits(64); +/// The number of `u64` words that store one bit for each `overlap` slot. +const OVERLAP_WORDS: usize = OVERLAP_FRAMES.div_ceil(64); +/// The number of input frames that warm the anti-alias filters during a +/// formant transition. +const POST_WARMUP_FRAMES: i32 = 128; +/// The `filtered_valid` count when all ring entries and anti-alias filter +/// states are settled. +const FILTERED_SETTLED: u16 = HISTORY as u16 + POST_WARMUP_FRAMES as u16; + +/// Returns a bitset where all `OVERLAP_FRAMES` slots are `true`. +#[inline] +fn full_overlap_lpc() -> [u64; OVERLAP_WORDS] { + let mut bits = [!0_u64; OVERLAP_WORDS]; + let tail = OVERLAP_FRAMES & 63; + if tail != 0 { + bits[OVERLAP_WORDS - 1] = (1_u64 << tail) - 1; + } + bits +} + +/// Returns the stereo pair for one voice sample and its Q14 pan weights. +#[inline] +fn apply_pan(value: Q14, pan: [Q14; 2], stereo_fade: Q14) -> [Q14; 2] { + if stereo_fade == Q14::ZERO { + [value, value] + } else if stereo_fade == Q14::ONE { + [value.mul(pan[0]), value.mul(pan[1])] + } else { + let mono = Q14::ONE - stereo_fade; + [ + value.mul(mono + pan[0].mul(stereo_fade)), + value.mul(mono + pan[1].mul(stereo_fade)), + ] + } +} + +/// Returns the stereo pair for one harmony voice, its Q14 mono gain and pan. +#[inline] +fn apply_harmony_pan(value: Q14, mono_gain: Q14, pan: [Q14; 2], stereo_fade: Q14) -> [Q14; 2] { + if stereo_fade == Q14::ZERO { + let scaled = value.mul(mono_gain); + [scaled, scaled] + } else if stereo_fade == Q14::ONE { + [value.mul(pan[0]), value.mul(pan[1])] + } else { + let mono: Q14 = mono_gain.mul(Q14::ONE - stereo_fade); + [ + value.mul(mono + pan[0].mul(stereo_fade)), + value.mul(mono + pan[1].mul(stereo_fade)), + ] + } +} /// Returns the reader position at the start of the history frame `frame`. #[inline] @@ -483,6 +541,8 @@ pub(crate) struct Resynthesis { /// The delayed source audio after the two prepared shift filters. If /// formants are enabled, the source is inverse-filtered. filtered: Box<[Q14; HISTORY]>, + /// The delayed raw audio after `raw_post`, for formant transitions. + raw_filtered: Box<[Q14; HISTORY]>, /// The history of the rendered choir lead. All secondary choir voices /// read this history. lead: Box<[Q14; HISTORY]>, @@ -535,6 +595,8 @@ pub(crate) struct Resynthesis { /// Two cascaded anti-alias filter sections. If the shift is not upward, /// they have coefficients of 1.0 and zero. post: [Biquad; 2], + /// Two anti-alias filter sections that track the delayed raw audio. + raw_post: [Biquad; 2], /// The current smoothed Q14 correction ratio. It does not include the /// global shift or the voice ratios. correction: Q14, @@ -580,12 +642,35 @@ pub(crate) struct Resynthesis { /// The Q8 weight of the delayed raw audio. The wet weight is 1.0 minus /// this weight. dry_mix: Q8, - /// The previous position of the lead reader. The crossfade after a jump - /// follows this position. - old_position: Q14, - /// The Q14 weight of the new lead reader. After a jump, it increases - /// toward 1.0. - fade: Q14, + /// The previous positions of the voice readers, for crossfades after + /// period wraps or delay changes. + old_positions: [Q14; 16], + /// The Q14 weights of the new voice readers. After a jump, each weight + /// increases toward 1.0. + fades: [Q14; 16], + /// The number of recent contiguous frames in `lead` that `render_lead` + /// wrote. + lead_valid: usize, + /// The state of `formant.enabled` from the previous frame. + was_formant_enabled: bool, + /// A bitset of `overlap` slots that hold formant-analyzed samples. + overlap_lpc: [u64; OVERLAP_WORDS], + /// The count of raw slots in the next `FORMANT_RAMP_FRAMES` of `overlap`. + lookahead_raw: u16, + /// `true` if the frames that enter `filtered` come from formant analysis. + filtered_lpc: bool, + /// The number of recent contiguous frames in `filtered` of `filtered_lpc`. + filtered_valid: u16, + /// The number of recent contiguous frames in `raw_filtered`. + raw_filtered_valid: u16, + /// `true` while `raw_filtered` advances each frame. + raw_filtered_active: bool, + /// `true` if `raw_filtered` holds data since construction or reset. + raw_filtered_dirty: bool, + /// The Q14 crossfade weight of LPC synthesis, in 0..=1. + formant_fade: Q14, + /// The Q14 ramp weight of the stereo pan, in 0..=1. + stereo_fade: Q14, /// The Q6 period that the code selected last for a voice. The modulation /// uses it. current_output_period: Q6, @@ -624,6 +709,7 @@ impl Resynthesis { harmony: HarmonyState::new(rate, config.harmony), scale: CorrectionTable::new(rate, config.correction.notes), filtered: prepare_history(Q14::ZERO), + raw_filtered: prepare_history(Q14::ZERO), lead: prepare_history(Q14::ZERO), periods: prepare_history(Q6::ZERO), previous_periods: prepare_history(Q6::ZERO), @@ -642,6 +728,7 @@ impl Resynthesis { voice_ratios: [Q14::ONE; HARMONY_VOICES + 1], formant_position: 0, post: [Biquad::new(), Biquad::new()], + raw_post: [Biquad::new(), Biquad::new()], correction: Q14::ONE, correction_decay: Q14::ZERO, sustained_decay: Q14::ZERO, @@ -661,8 +748,39 @@ impl Resynthesis { modulation: 0, modulation_phase: Q14::ZERO, dry_mix: Q8::ZERO, - old_position: Q14::ZERO, - fade: Q14::ONE, + old_positions: [Q14::ZERO; 16], + fades: [Q14::ONE; 16], + lead_valid: HISTORY, + was_formant_enabled: config.formant.enabled, + overlap_lpc: if config.formant.enabled { + full_overlap_lpc() + } else { + [0; OVERLAP_WORDS] + }, + lookahead_raw: if config.formant.enabled { + 0 + } else { + FORMANT_RAMP_FRAMES as u16 + }, + filtered_lpc: config.formant.enabled, + filtered_valid: FILTERED_SETTLED, + raw_filtered_valid: if config.formant.enabled { + HISTORY as u16 + } else { + 0 + }, + raw_filtered_active: config.formant.enabled, + raw_filtered_dirty: false, + formant_fade: if config.formant.enabled { + Q14::ONE + } else { + Q14::ZERO + }, + stereo_fade: if config.stereo_output { + Q14::ONE + } else { + Q14::ZERO + }, current_output_period: Q6::ZERO, control_counter: CONTROL_DUE, drift_decay: Q14::ZERO, @@ -672,7 +790,12 @@ impl Resynthesis { result.configure_all(); result.configure_shift_filters(); result.create_delays(); - result.old_position = result.positions[0]; + result.old_positions = result.positions; + result.lead_valid = if config.mode == MultiVoiceMode::Choir { + HISTORY + } else { + 0 + }; result } @@ -797,12 +920,21 @@ impl Resynthesis { /// truncates the numerator of the cutoff before it divides by the pitch /// ratio. fn configure_shift_filters(&mut self) { - for filter in &mut self.post { - if self.config.pitch_ratio > 1.0 { - let numerator = (self.rate.hz() as f64 * 0.49) as i32; - let cutoff = numerator as f32 / self.config.pitch_ratio; - filter.set_design(Design::low_pass(self.rate.hz(), cutoff, 0.707)); - } else { + if self.config.pitch_ratio > 1.0 { + let numerator = (self.rate.hz() as f64 * 0.49) as i32; + let cutoff = numerator as f32 / self.config.pitch_ratio; + let design = Design::low_pass(self.rate.hz(), cutoff, 0.707); + for filter in &mut self.post { + filter.set_design(design); + } + for filter in &mut self.raw_post { + filter.set_design(design); + } + } else { + for filter in &mut self.post { + filter.bypass(); + } + for filter in &mut self.raw_post { filter.bypass(); } } @@ -826,9 +958,28 @@ impl Resynthesis { } } + /// Saves the active reader positions, updates the delay offsets and starts + /// voice crossfades. + fn crossfade_delays(&mut self, active: usize) { + for voice in 0..active { + self.old_positions[voice] = self.positions[voice]; + self.fades[voice] = Q14::ZERO; + } + self.create_delays(); + for voice in active..16 { + self.old_positions[voice] = self.positions[voice]; + self.fades[voice] = Q14::ONE; + } + } + /// Applies a configuration that passed the full validation before. pub(crate) fn apply_config(&mut self, config: ResynthesisConfig) { let old = self.config; + let old_active = if old.mode == MultiVoiceMode::Choir { + old.choir_voices as usize + } else { + HARMONY_VOICES + 1 + }; self.config = config; if old.pitch.threshold != config.pitch.threshold { self.pitch.set_config(config.pitch); @@ -863,13 +1014,22 @@ impl Resynthesis { self.dwell = Q14::ZERO; } if old.mode != config.mode || old.choir_delay != config.choir_delay { - self.create_delays(); - } - if old.choir_voices < config.choir_voices { + self.crossfade_delays(old_active); + } else if old.choir_voices < config.choir_voices { for voice in old.choir_voices as usize..config.choir_voices as usize { - self.positions[voice] = self.positions[0]; + let position = + position_of(self.write as i32 - READER_LAG_FRAMES - self.delays[voice]); + self.positions[voice] = position; + self.old_positions[voice] = position; + self.fades[voice] = Q14::ONE; } } + if (old.mode == MultiVoiceMode::Choir && config.mode == MultiVoiceMode::Harmony) + || (!old.stereo_output && config.stereo_output && self.stereo_fade == Q14::ZERO) + { + self.formant.copy_channel_zero(); + self.previous_output[1] = self.previous_output[0]; + } if old.choir_voices != config.choir_voices || old.choir_spread_percent != config.choir_spread_percent { @@ -887,11 +1047,6 @@ impl Resynthesis { if old.dry_mix != config.dry_mix { self.configure_dry_mix(); } - if old.stereo_output != config.stereo_output { - // A stereo change resets the audio state. The correction keyboard - // keeps its held keys. - self.reset_audio(); - } } /// Sets the temporary aspiration mute for a drain without a change to the @@ -988,7 +1143,11 @@ impl Resynthesis { if old != choir_voices { if old < choir_voices { for voice in old as usize..choir_voices as usize { - self.positions[voice] = self.positions[0]; + let position = + position_of(self.write as i32 - READER_LAG_FRAMES - self.delays[voice]); + self.positions[voice] = position; + self.old_positions[voice] = position; + self.fades[voice] = Q14::ONE; } } self.configure_choir_pan(); @@ -1006,12 +1165,17 @@ impl Resynthesis { } /// Stores the choir delay scale. If the value changed, updates the delay - /// offsets. + /// offsets and starts voice crossfades. pub(crate) fn set_choir_delay(&mut self, choir_delay: f32) { let changed = self.config.choir_delay != choir_delay; self.config.choir_delay = choir_delay; if changed { - self.create_delays(); + let active = if self.config.mode == MultiVoiceMode::Choir { + self.config.choir_voices as usize + } else { + HARMONY_VOICES + 1 + }; + self.crossfade_delays(active); } } @@ -1107,6 +1271,10 @@ impl Resynthesis { self.pitch.reset(); clear_dirty_ring(self.raw.as_mut_slice(), written, Q14::ZERO); clear_dirty_ring(self.filtered.as_mut_slice(), written, Q14::ZERO); + if self.raw_filtered_dirty { + clear_dirty_ring(self.raw_filtered.as_mut_slice(), written, Q14::ZERO); + self.raw_filtered_dirty = false; + } clear_dirty_ring(self.lead.as_mut_slice(), written, Q14::ZERO); if written > 0 { let lead_start = HISTORY - OVERLAP_FRAMES + 1; @@ -1131,10 +1299,47 @@ impl Resynthesis { for filter in &mut self.post { filter.reset(); } + for filter in &mut self.raw_post { + filter.reset(); + } self.create_delays(); self.drift_ratio.fill(Q14::ONE); - self.old_position = self.positions[0]; - self.fade = Q14::ONE; + self.old_positions = self.positions; + self.fades.fill(Q14::ONE); + self.lead_valid = if self.config.mode == MultiVoiceMode::Choir { + HISTORY + } else { + 0 + }; + self.was_formant_enabled = self.config.formant.enabled; + self.overlap_lpc = if self.config.formant.enabled { + full_overlap_lpc() + } else { + [0; OVERLAP_WORDS] + }; + self.lookahead_raw = if self.config.formant.enabled { + 0 + } else { + FORMANT_RAMP_FRAMES as u16 + }; + self.filtered_lpc = self.config.formant.enabled; + self.filtered_valid = FILTERED_SETTLED; + self.raw_filtered_valid = if self.config.formant.enabled { + HISTORY as u16 + } else { + 0 + }; + self.raw_filtered_active = self.config.formant.enabled; + self.formant_fade = if self.config.formant.enabled { + Q14::ONE + } else { + Q14::ZERO + }; + self.stereo_fade = if self.config.stereo_output { + Q14::ONE + } else { + Q14::ZERO + }; self.harmony_ratios.fill(Q14::ONE); self.voice_ratios.fill(Q14::ONE); self.formant_position = 0; @@ -1481,29 +1686,23 @@ impl Resynthesis { /// Advances one Q14 reader by its ratio and keeps it in `bounds`. /// /// `bounds` holds the upper limit, the lower limit and the Q14 period - /// jump. `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. + /// jump. `voice` must identify an allocated reader slot. If the reader + /// jumps, the function saves the old position and starts the crossfade of + /// that voice. #[inline] - fn step_reader( - &mut self, - voice: usize, - ratio: Q14, - bounds: (Q14, Q14, Q14), - fade: bool, - ) -> Q14 { + fn step_reader(&mut self, voice: usize, ratio: Q14, bounds: (Q14, Q14, Q14)) -> Q14 { let (upper, lower, jump) = bounds; let mut position = self.positions[voice] + ratio; if position >= upper { - if fade { - self.old_position = position; - self.fade = Q14::ZERO; + if jump != Q14::ZERO || self.old_positions[voice] == position { + self.old_positions[voice] = position; + self.fades[voice] = Q14::ZERO; } position = position - jump; } else if position <= lower { - if fade { - self.old_position = position; - self.fade = Q14::ZERO; + if jump != Q14::ZERO || self.old_positions[voice] == position { + self.old_positions[voice] = position; + self.fades[voice] = Q14::ZERO; } position = position + jump; } @@ -1514,26 +1713,144 @@ impl Resynthesis { /// Advances one Q14 reader by its ratio and keeps it near the writer. /// /// If the reader gets to one of the two limits, it jumps by one Q6 pitch - /// period. `offset` is an integer voice delay. `voice` must identify an - /// allocated reader slot. If `fade` is `true` and the reader jumps, the - /// function saves the old position and starts the crossfade again. Only - /// the choir lead sets `fade`. - fn move_reader( - &mut self, - voice: usize, - ratio: Q14, - period: Q6, - offset: i32, - fade: bool, - ) -> Q14 { + /// period, saves the old position and starts the crossfade of that voice. + fn move_reader(&mut self, voice: usize, ratio: Q14, period: Q6, offset: i32) -> Q14 { let bounds = self.reader_bounds(period, offset); - self.step_reader(voice, ratio, bounds, fade) + self.step_reader(voice, ratio, bounds) + } + + /// Returns `true` if harmony `voice` adds zero to the two stereo channels. + #[inline] + fn is_harmony_voice_silent(&self, voice: usize, stereo_fade: Q14) -> bool { + if self.harmony_gains[voice] == Q12::ZERO { + return true; + } + let pan = self.harmony_pan[voice]; + let pan_zero = (pan[0].to_bits() | pan[1].to_bits()) == 0; + if stereo_fade == Q14::ONE { + pan_zero + } else if stereo_fade == Q14::ZERO { + self.harmony_gain == Q14::ZERO + } else { + self.harmony_gain == Q14::ZERO && pan_zero + } + } + + /// Returns `true` if the three interpolation taps around `center` in + /// `filtered` match `want_lpc` with settled anti-alias filter state. + #[inline] + fn filtered_tap_ready(&self, center: i32, want_lpc: bool) -> bool { + if self.filtered_lpc != want_lpc { + return false; + } + let warmup = if self.config.pitch_ratio > 1.0 { + POST_WARMUP_FRAMES as usize + } else { + 0 + }; + let valid = usize::from(self.filtered_valid).saturating_sub(warmup); + if valid >= HISTORY { + return true; + } + let age_minus = (self.write + HISTORY - ring(center.wrapping_sub(1))) % HISTORY; + let age_plus = (self.write + HISTORY - ring(center.wrapping_add(1))) % HISTORY; + age_minus < valid && age_plus < valid + } + + /// Returns `true` if `overlap[slot]` holds a formant-analyzed sample. + #[inline] + fn overlap_is_lpc(&self, slot: usize) -> bool { + ((self.overlap_lpc[slot >> 6] >> (slot & 63)) & 1) != 0 + } + + /// Records whether `overlap[slot]` holds a formant-analyzed sample. + #[inline] + fn set_overlap_lpc(&mut self, slot: usize, is_lpc: bool) { + let mask = 1_u64 << (slot & 63); + if is_lpc { + self.overlap_lpc[slot >> 6] |= mask; + } else { + self.overlap_lpc[slot >> 6] &= !mask; + } + } + + /// Advances `formant_fade` by one ramp step and resets synthesis at the + /// start of a new fade-in. + fn step_formant_fade(&mut self, lpc_ready: bool, lower: Q14) -> Q14 { + let prev = self.formant_fade; + let min_lower = position_of((self.write as i32).wrapping_sub(FORMANT_RAMP_FRAMES as i32)); + let lower_ready = prev > Q14::ZERO + || self.filtered_tap_ready(history::center(lower.min(min_lower)), true); + let next = + if self.config.formant.enabled && self.lookahead_raw == 0 && lpc_ready && lower_ready { + (prev + STAGE_RAMP_STEP).min(Q14::ONE) + } else { + (prev - STAGE_RAMP_STEP).max(Q14::ZERO) + }; + if prev == Q14::ZERO && next > Q14::ZERO { + self.formant.reset_synthesis(); + self.previous_output = [Q14::ZERO; 2]; + } + self.formant_fade = next; + next + } + + /// Interpolates the delayed raw history at `position` with the anti-alias + /// filter state of `raw_filtered`. + #[inline] + fn interpolate_raw_filtered(&self, position: Q14) -> Q14 { + let valid = usize::from(self.raw_filtered_valid); + if valid >= HISTORY { + return history::interpolation(&self.raw_filtered, position).0; + } + if !self.raw_filtered_active { + return history::interpolation(&self.filtered, position).0; + } + let bits = position.to_bits(); + let center = history::center(position); + let fraction = Q14::from_bits(bits.wrapping_sub(center.wrapping_shl(14))); + let [left_idx, middle_idx, right_idx] = history::interpolation_indices(center); + let tap = |index: usize| { + let age = if self.write >= index { + self.write - index + } else { + self.write + HISTORY - index + }; + if age < valid { + self.raw_filtered[index] + } else { + self.filtered[index] + } + }; + quadratic(tap(left_idx), tap(middle_idx), tap(right_idx), fraction) + } + + /// Reads a sample from `lead` and outputs zero until fresh frames from + /// `render_lead` arrive. + #[inline] + fn read_lead(&self, position: Q14) -> Q14 { + if self.lead_valid >= HISTORY { + return history::interpolation(&self.lead, position).0; + } + let (sample, center) = history::interpolation(&self.lead, position); + if center > self.write as i32 { + return Q14::ZERO; + } + let margin = self.lead_valid as i32 - (self.write as i32 - center + 2); + if margin < 0 { + Q14::ZERO + } else if margin < 20 { + let gain = Q14::from_bits(((margin + 1) * FADE_STEP.to_bits()).min(Q14::ONE.to_bits())); + sample.mul(gain) + } else { + sample + } } /// Advances one secondary choir reader and returns its position and ratio. /// /// The function selects the delayed period, updates `current_output_period` - /// and moves the reader without a crossfade. `voice` must identify a + /// and moves the reader with its crossfade state. `voice` must identify a /// secondary choir slot, and `delayed` must be less than HISTORY. fn move_choir_reader(&mut self, voice: usize, delayed: usize) -> (Q14, Q14) { let offset = self.delays[voice]; @@ -1541,7 +1858,8 @@ impl Resynthesis { let (period, _) = self.period_for(delay, self.write); self.current_output_period = period; let ratio = self.drift_ratio[voice]; - let position = self.move_reader(voice, ratio, period, offset, false); + self.old_positions[voice] = self.old_positions[voice] + ratio; + let position = self.move_reader(voice, ratio, period, offset); (position, ratio) } @@ -1564,7 +1882,7 @@ impl Resynthesis { /// The function does these steps: /// 1. It selects the period and the ratio. /// 2. It moves the reader and applies the crossfade. - /// 3. If formants are enabled, it applies them and the glottal envelope. + /// 3. If formants are active or in transition, it applies or blends them. /// 4. It stores the Q14 result in the lead history. /// /// Returns the lead sample and its effective ratio, for the modulation @@ -1581,15 +1899,34 @@ impl Resynthesis { if ratio != Q14::ZERO { self.periods[delay] = period.div(ratio); } - self.old_position = self.old_position + ratio; - let position = self.move_reader(0, ratio, period, self.delays[0], true); - 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); + self.old_positions[0] = self.old_positions[0] + ratio; + let bounds = self.reader_bounds(period, self.delays[0]); + let position = self.step_reader(0, ratio, bounds); + let reader_fade = self.fades[0]; + if reader_fade < Q14::ONE { + self.fades[0] = (reader_fade + FADE_STEP).min(Q14::ONE); } - if self.config.formant.enabled { + let (new_value, center) = history::interpolation(&self.filtered, position); + let mut value = new_value; + let mut raw_ready = self.filtered_tap_ready(center, false); + let new_lpc = self.filtered_tap_ready(center, true); + let mut lpc_ready = new_lpc; + let mut old_value = Q14::ZERO; + let mut old_lpc = true; + if reader_fade < Q14::ONE { + let (old, old_center) = history::interpolation(&self.filtered, self.old_positions[0]); + old_value = old; + value = value.mul(reader_fade) + old.mul(Q14::ONE - reader_fade); + raw_ready &= self.filtered_tap_ready(old_center, false); + old_lpc = self.filtered_tap_ready(old_center, true); + lpc_ready &= old_lpc; + } + let steady_off = self.formant_fade == Q14::ZERO && raw_ready; + let steady_on = self.config.formant.enabled + && self.lookahead_raw == 0 + && self.formant_fade == Q14::ONE + && lpc_ready; + if steady_on { self.formant_position = center - FORMANT_OFFSET_FRAMES; value = Q14::from_bits(self.formant.forward( value.to_bits(), @@ -1597,8 +1934,42 @@ impl Resynthesis { numeric, )); value = self.apply_glottal(0, value); + } else if !steady_off { + let mut raw_value = self.interpolate_raw_filtered(position); + if reader_fade < Q14::ONE { + let old_raw = self.interpolate_raw_filtered(self.old_positions[0]); + raw_value = raw_value.mul(reader_fade) + old_raw.mul(Q14::ONE - reader_fade); + } + let fade = self.step_formant_fade(lpc_ready, bounds.1); + if fade > Q14::ZERO { + let lpc_in = if lpc_ready { + self.formant_position = center - FORMANT_OFFSET_FRAMES; + value + } else { + if new_lpc { + self.formant_position = center - FORMANT_OFFSET_FRAMES; + } + let new_part = if new_lpc { new_value } else { Q14::ZERO }; + if reader_fade < Q14::ONE { + let old_part = if old_lpc { old_value } else { Q14::ZERO }; + new_part.mul(reader_fade) + old_part.mul(Q14::ONE - reader_fade) + } else { + new_part + } + }; + let lpc_value = Q14::from_bits(self.formant.forward( + lpc_in.to_bits(), + self.formant_position, + numeric, + )); + let lpc_value = self.apply_glottal(0, lpc_value); + value = raw_value.mul(Q14::ONE - fade) + lpc_value.mul(fade); + } else { + value = raw_value; + } } self.lead[write] = value; + self.lead_valid = (self.lead_valid + 1).min(HISTORY); (value, ratio) } @@ -1631,10 +2002,13 @@ impl Resynthesis { } else { 5 }; + let shift = position_of(HISTORY as i32); for position in &mut self.positions[..voices] { - *position = *position - position_of(HISTORY as i32); + *position = *position - shift; + } + for position in &mut self.old_positions[..voices] { + *position = *position - shift; } - self.old_position = self.old_position - position_of(HISTORY as i32); } if step.restarted { self.correction = Q14::ONE; @@ -1669,10 +2043,18 @@ impl Resynthesis { self.periods[write] = step.period; self.previous_periods[write] = step.previous_period; self.ratios[write] = self.correction; + let prev_read = (self.overlap_index + ANALYSIS_FRAMES) % OVERLAP_FRAMES; self.overlap_index += 1; if self.overlap_index == OVERLAP_FRAMES { self.overlap_index = 0; } + if self.config.formant.enabled != self.was_formant_enabled { + self.was_formant_enabled = self.config.formant.enabled; + if self.config.formant.enabled { + self.formant.prepare_enable(&self.raw, write); + } + } + self.set_overlap_lpc(self.overlap_index, self.config.formant.enabled); self.overlap[self.overlap_index] = if self.config.formant.enabled { let previous = self.raw[ring(write as i32 - 1)]; Q14::from_bits(self.formant.process_analysis( @@ -1685,10 +2067,39 @@ impl Resynthesis { } else { self.raw[ring(write as i32 - ANALYSIS_FRAMES as i32)] }; + if self.config.formant.enabled && !self.raw_filtered_active { + self.raw_post = self.post.clone(); + self.raw_filtered_active = true; + self.raw_filtered_valid = 0; + } + let delayed = ring(write as i32 - OVERLAP_FRAMES as i32); + if self.raw_filtered_active { + let mut raw_sample = self.raw[delayed]; + if self.config.pitch_ratio > 1.0 { + for filter in &mut self.raw_post { + raw_sample = filter.process_sample(raw_sample); + } + } else { + for filter in &mut self.raw_post { + raw_sample = filter.bypass_sample(raw_sample); + } + } + self.raw_filtered[write] = raw_sample; + self.raw_filtered_dirty = true; + self.raw_filtered_valid = (self.raw_filtered_valid + 1).min(HISTORY as u16); + } // The inverse analysis adds a delay of ANALYSIS_FRAMES. Read ahead by // the same number of frames in the overlap ring. Then the total delay // of the source is OVERLAP_FRAMES in the two formant modes. let overlap_read = (self.overlap_index + ANALYSIS_FRAMES) % OVERLAP_FRAMES; + if !self.overlap_is_lpc(prev_read) { + self.lookahead_raw -= 1; + } + let lookahead_tail = (prev_read + FORMANT_RAMP_FRAMES) % OVERLAP_FRAMES; + if !self.overlap_is_lpc(lookahead_tail) { + self.lookahead_raw += 1; + } + let slot_lpc = self.overlap_is_lpc(overlap_read); let mut filtered = self.overlap[overlap_read]; if self.config.pitch_ratio > 1.0 { for filter in &mut self.post { @@ -1700,10 +2111,21 @@ impl Resynthesis { } } self.filtered[write] = filtered; - let delayed = ring(write as i32 - OVERLAP_FRAMES as i32); + if self.filtered_lpc == slot_lpc { + self.filtered_valid = self.filtered_valid.saturating_add(1).min(FILTERED_SETTLED); + } else { + self.filtered_lpc = slot_lpc; + self.filtered_valid = 1; + } + if self.config.stereo_output && self.stereo_fade < Q14::ONE { + self.stereo_fade = (self.stereo_fade + STAGE_RAMP_STEP).min(Q14::ONE); + } else if !self.config.stereo_output && self.stereo_fade > Q14::ZERO { + self.stereo_fade = (self.stereo_fade - STAGE_RAMP_STEP).max(Q14::ZERO); + } + let stereo_fade = self.stereo_fade; let dry = self.raw[ring(write as i32 - LATENCY_FRAMES as i32)]; let mut mix = [Q14::ZERO; 2]; - let mut mono = !self.config.stereo_output; + let mut mono = stereo_fade == Q14::ZERO; let mut final_ratio = Q14::ONE; if self.config.mode == MultiVoiceMode::Choir { let voice_count = self.config.choir_voices as usize; @@ -1712,12 +2134,13 @@ impl Resynthesis { let (value, ratio) = self.render_lead(delayed, numeric); final_ratio = ratio; self.voice_ratios[0] = ratio; - if self.config.stereo_output { + if mono { + mix[0] = mix[0] + value; + } else { + let panned = apply_pan(value, self.pan[0], stereo_fade); for (channel, sum) in mix.iter_mut().enumerate() { - *sum = *sum + value.mul(self.pan[0][channel]); + *sum = *sum + panned[channel]; } - } else { - mix[0] = mix[0] + value; } } { @@ -1729,20 +2152,31 @@ impl Resynthesis { for (lane, position) in positions.iter_mut().enumerate() { (*position, final_ratio) = self.move_choir_reader(voice + lane, delayed); } - let values = - positions.map(|position| history::interpolation(&self.lead, position).0); + let mut values = [Q14::ZERO; 4]; + for (lane, value) in values.iter_mut().enumerate() { + let current_voice = voice + lane; + let mut sample = self.read_lead(positions[lane]); + let fade = self.fades[current_voice]; + if fade < Q14::ONE { + let old = self.read_lead(self.old_positions[current_voice]); + sample = sample.mul(fade) + old.mul(Q14::ONE - fade); + self.fades[current_voice] = (fade + FADE_STEP).min(Q14::ONE); + } + *value = sample; + } // Keep the voice and channel order of each sum. - if self.config.stereo_output { + if mono { + for value in values { + mix[0] = mix[0] + value; + } + } else { for (lane, value) in values.into_iter().enumerate() { let current_voice = voice + lane; + let panned = apply_pan(value, self.pan[current_voice], stereo_fade); for (channel, sum) in mix.iter_mut().enumerate() { - *sum = *sum + value.mul(self.pan[current_voice][channel]); + *sum = *sum + panned[channel]; } } - } else { - for value in values { - mix[0] = mix[0] + value; - } } voice += 4; } @@ -1751,17 +2185,25 @@ impl Resynthesis { for voice in voice..voice_count { let (position, ratio) = self.move_choir_reader(voice, delayed); final_ratio = ratio; - let (value, _) = history::interpolation(&self.lead, position); - if self.config.stereo_output { + let mut value = self.read_lead(position); + let fade = self.fades[voice]; + if fade < Q14::ONE { + let old = self.read_lead(self.old_positions[voice]); + value = value.mul(fade) + old.mul(Q14::ONE - fade); + self.fades[voice] = (fade + FADE_STEP).min(Q14::ONE); + } + if mono { + mix[0] = mix[0] + value; + } else { + let panned = apply_pan(value, self.pan[voice], stereo_fade); for (channel, sum) in mix.iter_mut().enumerate() { - *sum = *sum + value.mul(self.pan[voice][channel]); + *sum = *sum + panned[channel]; } - } else { - mix[0] = mix[0] + value; } } } } else { + self.lead_valid = 0; let (period, ratio) = self.period_for(delayed, write); self.current_output_period = period; let counter = self.control_counter; @@ -1780,6 +2222,10 @@ impl Resynthesis { } } let bounds = self.reader_bounds(period, 0); + let mut slot_positions = [Q14::ZERO; 5]; + let mut slot_fades = [Q14::ONE; 5]; + let mut raw_ready = true; + let mut lpc_ready = true; for slot in 0..5 { let mut current: Q14 = if slot == 0 { ratio @@ -1792,39 +2238,68 @@ impl Resynthesis { } final_ratio = current; self.voice_ratios[slot] = current; - let position = self.step_reader(slot, current, bounds, false); - // If the Q12 gain or the stereo pan is zero, the voice adds - // zero to the mix. - if slot > 0 { - let voice = slot - 1; - let pan = self.harmony_pan[voice]; - let silent_pan = - self.config.stereo_output && (pan[0].to_bits() | pan[1].to_bits()) == 0; - if self.harmony_gains[voice] == Q12::ZERO || silent_pan { - continue; + self.old_positions[slot] = self.old_positions[slot] + current; + let position = self.step_reader(slot, current, bounds); + let fade = self.fades[slot]; + if fade < Q14::ONE { + self.fades[slot] = (fade + FADE_STEP).min(Q14::ONE); + } + slot_positions[slot] = position; + slot_fades[slot] = fade; + // If the voice adds zero to the two channels, do not read the + // audio history. + if slot > 0 && self.is_harmony_voice_silent(slot - 1, stereo_fade) { + if self.filtered_valid < FILTERED_SETTLED { + let center = history::center(position); + raw_ready &= self.filtered_tap_ready(center, false); + lpc_ready &= self.filtered_tap_ready(center, true); + if fade < Q14::ONE { + let old_center = history::center(self.old_positions[slot]); + raw_ready &= self.filtered_tap_ready(old_center, false); + lpc_ready &= self.filtered_tap_ready(old_center, true); + } } + continue; } - let (mut value, _) = history::interpolation(&self.filtered, position); - if slot > 0 { - value = value.mul(self.harmony_gains[slot - 1]); - if !self.config.stereo_output { + let (mut value, center) = history::interpolation(&self.filtered, position); + raw_ready &= self.filtered_tap_ready(center, false); + lpc_ready &= self.filtered_tap_ready(center, true); + if fade < Q14::ONE { + let (old, old_center) = + history::interpolation(&self.filtered, self.old_positions[slot]); + value = value.mul(fade) + old.mul(Q14::ONE - fade); + raw_ready &= self.filtered_tap_ready(old_center, false); + lpc_ready &= self.filtered_tap_ready(old_center, true); + } + if mono { + if slot > 0 { + value = value.mul(self.harmony_gains[slot - 1]); value = value.mul(self.harmony_gain); } - } - if self.config.stereo_output { + mix[0] = mix[0] + value; + } else { + let panned = if slot > 0 { + value = value.mul(self.harmony_gains[slot - 1]); + apply_harmony_pan( + value, + self.harmony_gain, + self.harmony_pan[slot - 1], + stereo_fade, + ) + } else { + [value, value] + }; for (channel, sum) in mix.iter_mut().enumerate() { - *sum = *sum - + if slot > 0 { - value.mul(self.harmony_pan[slot - 1][channel]) - } else { - value - }; + *sum = *sum + panned[channel]; } - } else { - mix[0] = mix[0] + value; } } - if self.config.formant.enabled { + let steady_off = self.formant_fade == Q14::ZERO && raw_ready; + let steady_on = self.config.formant.enabled + && self.lookahead_raw == 0 + && self.formant_fade == Q14::ONE + && lpc_ready; + if steady_on { self.formant_position = (self.positions[0].to_bits() >> 14) - FORMANT_OFFSET_FRAMES; // If Choir changed only channel zero before a switch to // Harmony, synthesize the two channels until their histories @@ -1854,8 +2329,144 @@ impl Resynthesis { } mono = mono && mix[0] == mix[1]; } + } else if !steady_off { + let mut raw_mix = [Q14::ZERO; 2]; + for slot in 0..5 { + if slot > 0 && self.is_harmony_voice_silent(slot - 1, stereo_fade) { + continue; + } + let mut value = self.interpolate_raw_filtered(slot_positions[slot]); + let fade = slot_fades[slot]; + if fade < Q14::ONE { + let old = self.interpolate_raw_filtered(self.old_positions[slot]); + value = value.mul(fade) + old.mul(Q14::ONE - fade); + } + if mono { + if slot > 0 { + value = value.mul(self.harmony_gains[slot - 1]); + value = value.mul(self.harmony_gain); + } + raw_mix[0] = raw_mix[0] + value; + } else { + let panned = if slot > 0 { + value = value.mul(self.harmony_gains[slot - 1]); + apply_harmony_pan( + value, + self.harmony_gain, + self.harmony_pan[slot - 1], + stereo_fade, + ) + } else { + [value, value] + }; + for (channel, sum) in raw_mix.iter_mut().enumerate() { + *sum = *sum + panned[channel]; + } + } + } + let fade = self.step_formant_fade(lpc_ready, bounds.1); + if fade > Q14::ZERO { + let lead_center = self.positions[0].to_bits() >> 14; + if lpc_ready { + self.formant_position = lead_center - FORMANT_OFFSET_FRAMES; + } else { + if self.filtered_tap_ready(history::center(self.positions[0]), true) { + self.formant_position = lead_center - FORMANT_OFFSET_FRAMES; + } + mix = [Q14::ZERO; 2]; + for slot in 0..5 { + if slot > 0 && self.is_harmony_voice_silent(slot - 1, stereo_fade) { + continue; + } + let (new_val, new_c) = + history::interpolation(&self.filtered, slot_positions[slot]); + let new_part = if self.filtered_tap_ready(new_c, true) { + new_val + } else { + Q14::ZERO + }; + let vfade = slot_fades[slot]; + let mut value = if vfade < Q14::ONE { + let (old_val, old_c) = history::interpolation( + &self.filtered, + self.old_positions[slot], + ); + let old_part = if self.filtered_tap_ready(old_c, true) { + old_val + } else { + Q14::ZERO + }; + new_part.mul(vfade) + old_part.mul(Q14::ONE - vfade) + } else { + new_part + }; + if mono { + if slot > 0 { + value = value.mul(self.harmony_gains[slot - 1]); + value = value.mul(self.harmony_gain); + } + mix[0] = mix[0] + value; + } else { + let panned = if slot > 0 { + value = value.mul(self.harmony_gains[slot - 1]); + apply_harmony_pan( + value, + self.harmony_gain, + self.harmony_pan[slot - 1], + stereo_fade, + ) + } else { + [value, value] + }; + for (channel, sum) in mix.iter_mut().enumerate() { + *sum = *sum + panned[channel]; + } + } + } + } + if mono + && self.formant.histories_match() + && self.previous_output[0] == self.previous_output[1] + { + let value = Q14::from_bits(self.formant.forward_mono( + mix[0].to_bits(), + self.formant_position, + numeric, + )); + let value = self.apply_glottal(0, value); + self.previous_output[1] = value; + mix[0] = raw_mix[0].mul(Q14::ONE - fade) + value.mul(fade); + } else { + if mono { + mix[1] = mix[0]; + raw_mix[1] = raw_mix[0]; + } + let mut lpc_mix = self + .formant + .forward_stereo(mix.map(Q14::to_bits), self.formant_position, numeric) + .map(Q14::from_bits); + for (channel, value) in lpc_mix.iter_mut().enumerate() { + *value = self.apply_glottal(channel, *value); + mix[channel] = + raw_mix[channel].mul(Q14::ONE - fade) + (*value).mul(fade); + } + mono = mono && mix[0] == mix[1]; + } + } else { + mix = raw_mix; + } } } + if self.raw_filtered_active + && !self.config.formant.enabled + && self.formant_fade == Q14::ZERO + && self.overlap_lpc == [0; OVERLAP_WORDS] + && !self.filtered_lpc + && self.filtered_valid == FILTERED_SETTLED + { + self.raw_filtered_active = false; + self.raw_filtered_valid = 0; + } if self.modulation != 0 { if self.current_output_period != Q6::ZERO { // The phase advances by depth x 4 x ratio / period, in Q14 diff --git a/src/resynthesis/history.rs b/src/resynthesis/history.rs index 6f3cda2..a2259bf 100644 --- a/src/resynthesis/history.rs +++ b/src/resynthesis/history.rs @@ -60,7 +60,7 @@ pub(crate) fn clear_dirty_ring(buffer: &mut [T], written: usize, value: /// /// The center can be negative or more than one full history length. #[inline] -fn interpolation_indices(center: i32) -> [usize; 3] { +pub(super) fn interpolation_indices(center: i32) -> [usize; 3] { let middle = ring(center); let left = if middle == 0 { HISTORY - 1 } else { middle - 1 }; let right = if middle + 1 == HISTORY { 0 } else { middle + 1 }; @@ -82,6 +82,17 @@ fn interpolation_taps(buffer: &[T; HISTORY], center: i32) -> [T; 3] { } } +/// Returns the integer center frame of a Q14 position without wrap. +#[inline] +pub(super) fn center(position: Q14) -> i32 { + let bits = position.to_bits(); + if position > Q14::ZERO { + bits.wrapping_add(8192) >> 14 + } else { + -(8192_i32.wrapping_sub(bits) >> 14) + } +} + /// Returns the value of a three-point parabola at a Q14 frame position. /// /// The result has two parts: the Q14 sample and the integer center frame @@ -95,11 +106,7 @@ fn interpolation_taps(buffer: &[T; HISTORY], center: i32) -> [T; 3] { /// products use `i64` arithmetic and clamp to `i32`. pub(super) fn interpolation(buffer: &[Q14; HISTORY], position: Q14) -> (Q14, i32) { let bits = position.to_bits(); - let center = if position > Q14::ZERO { - bits.wrapping_add(8192) >> 14 - } else { - -(8192_i32.wrapping_sub(bits) >> 14) - }; + let center = center(position); let fraction = Q14::from_bits(bits.wrapping_sub(center.wrapping_shl(14))); let [left, middle, right] = interpolation_taps(buffer, center); (quadratic(left, middle, right, fraction), center) diff --git a/src/wasm.rs b/src/wasm.rs index e868d16..51cb57c 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -526,8 +526,11 @@ impl WasmProcessor { self.processor.begin_drain() } - /// Returns the tail budget of the current configuration, not the remaining - /// drain count. + /// Returns the finite tail budget for the current configuration and active + /// stage transitions. + /// + /// This value includes active Alien ramps, reverb mode fades and reverb + /// bypass tails. It is not the number of drain frames that are left. #[wasm_bindgen(js_name = tailFrames)] pub fn tail_frames(&self) -> usize { self.processor.tail_frames()