diff --git a/src/effects/punch.rs b/src/effects/punch.rs index e5ed4f9..3f3bb5b 100644 --- a/src/effects/punch.rs +++ b/src/effects/punch.rs @@ -103,6 +103,8 @@ impl PunchConfig { pub(crate) struct Punch { /// The prepared rate, which converts the envelope times to sample counts. rate: SampleRate, + /// The validated controls for this stage. + config: PunchConfig, /// The number of frames in the 6 ms peak-hold window at `rate`. hold_frames: usize, /// The write offset into the leaf half of `hold_tree`. @@ -134,23 +136,27 @@ impl Punch { /// settings. pub(crate) fn new(rate: SampleRate, config: PunchConfig) -> Self { let hold_frames = (rate.as_u32() as usize * HOLD_MS).div_ceil(1000); - let drive_decay = Q30::from_f64(envelope_decay(DRIVE_SMOOTH_MS, rate.hz() as f64, 1)); + let drive_decay = Self::decay(rate, DRIVE_SMOOTH_MS); let mut result = Self { rate, + config, hold_frames, hold_cursor: 0, hold_tree: [Q28::ZERO; MAX_HOLD_FRAMES * 2], slow: Q28::ZERO, fast: Q28::ZERO, slow_decay: Q30::ZERO, - fast_decay: Q30::ZERO, + fast_decay: Self::decay(rate, FAST_RELEASE_MS), attack_decay: Q30::ZERO, drive_decay, gain: Q28::ONE, ceiling_gain: Q28::ONE, drive: BASE_DRIVE, }; - result.set_config(config); + result.prepare_impact(); + result.prepare_attack(); + result.prepare_gain(); + result.prepare_ceiling(); result.reset(); result } @@ -171,21 +177,47 @@ impl Punch { let out = ceiling * two_over_pi * (drive * env / ceiling).atan(); (out / env) as f32 } - /// Calculates the quantized controls again, and keeps the envelopes and - /// the current drive. - /// The processor controls the bypass. This stage never reads an enabled - /// flag. + /// Calculates the quantized controls that changed, and keeps the envelopes + /// and the current drive. + /// The processor controls the bypass. The audio path of this stage does + /// not read `enabled`. pub(crate) fn set_config(&mut self, config: PunchConfig) { - let impact = coefficient_to_exp_value(1.0, 250.0, 5000.0, 1.0 - config.impact); - let decay = |milliseconds: f64| { - Q30::from_f64(envelope_decay(milliseconds, self.rate.hz() as f64, 1)) - }; - self.slow_decay = decay(impact as f64); - self.fast_decay = decay(FAST_RELEASE_MS); - self.attack_decay = decay(config.attack_ms as f64); - self.gain = Q28::from_f64(db_to_gain(config.gain_db as f64)); + let old = self.config; + self.config = config; + if old.impact != config.impact { + self.prepare_impact(); + } + if old.attack_ms != config.attack_ms { + self.prepare_attack(); + } + if old.gain_db != config.gain_db { + self.prepare_gain(); + } + if old.ceiling_db != config.ceiling_db { + self.prepare_ceiling(); + } + } + /// Converts a half-life in milliseconds to a per-sample Q30 coefficient. + fn decay(rate: SampleRate, milliseconds: f64) -> Q30 { + Q30::from_f64(envelope_decay(milliseconds, rate.hz() as f64, 1)) + } + /// Calculates the release coefficient of the adaptive follower. + fn prepare_impact(&mut self) { + let impact = coefficient_to_exp_value(1.0, 250.0, 5000.0, 1.0 - self.config.impact); + self.slow_decay = Self::decay(self.rate, impact as f64); + } + /// Calculates the shared attack coefficient of the two followers. + fn prepare_attack(&mut self) { + self.attack_decay = Self::decay(self.rate, self.config.attack_ms as f64); + } + /// Quantizes the linear input gain to Q28. + fn prepare_gain(&mut self) { + self.gain = Q28::from_f64(db_to_gain(self.config.gain_db as f64)); + } + /// Quantizes the linear output ceiling to Q28, with a minimum of one LSB. + fn prepare_ceiling(&mut self) { self.ceiling_gain = - Q28::from_f64(db_to_gain(config.ceiling_db as f64)).max(Q28::from_bits(1)); + Q28::from_f64(db_to_gain(self.config.ceiling_db as f64)).max(Q28::from_bits(1)); } /// Clears the peak hold and both envelopes, then sets the drive from the /// base drive and the input gain. diff --git a/src/effects/reverb.rs b/src/effects/reverb.rs index cdc1c32..b0dfff6 100644 --- a/src/effects/reverb.rs +++ b/src/effects/reverb.rs @@ -195,20 +195,52 @@ impl Reverb { wet_peak: 0, dirty: false, }; - result.set_config(config); + result.prepare_mix(); + result.prepare_diffusion(); + result.prepare_decay(); + result.prepare_brightness(); result } - /// Updates the coefficients and does not clear the delay or filter state. + /// Updates the coefficients that changed and does not clear the delay or + /// filter state. /// The f32 multiplication by 100 occurs before the f64 division and the /// quantization. If you combine these expressions, the quantized /// coefficients can change. pub(crate) fn set_config(&mut self, config: ReverbConfig) { + let old = self.config; self.config = config; - self.mix = Q14::from_f64((config.mix * 100.0) as f64 / 100.0); - self.diffuse = Q14::from_f64((config.diffusion * 100.0) as f64 / 100.0); - self.decay = Q14::from_f64((config.decay * 100.0) as f64 / 105.0); + if old.mix != config.mix { + self.prepare_mix(); + } + if old.diffusion != config.diffusion { + self.prepare_diffusion(); + } + if old.decay != config.decay { + self.prepare_decay(); + } + if old.brightness_hz != config.brightness_hz { + self.prepare_brightness(); + } + } + /// Quantizes the wet fraction to Q14. + fn prepare_mix(&mut self) { + self.mix = Q14::from_f64((self.config.mix * 100.0) as f64 / 100.0); + } + /// Quantizes the diffusion control and the allpass coefficients of + /// MediumHall and LargeHall to Q14. + fn prepare_diffusion(&mut self) { + self.diffuse = Q14::from_f64((self.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))); - let brightness = config + } + /// Quantizes the feedback coefficient to Q14. + fn prepare_decay(&mut self) { + self.decay = Q14::from_f64((self.config.decay * 100.0) as f64 / 105.0); + } + /// Updates the coefficients of the two low-pass filters and keeps their + /// histories. + fn prepare_brightness(&mut self) { + let brightness = self + .config .brightness_hz .min((self.rate.hz() as f64 * 0.49) as f32); let design = Design::low_pass_one_pole(self.rate.hz(), brightness); diff --git a/src/formant.rs b/src/formant.rs index 5173b41..21bb141 100644 --- a/src/formant.rs +++ b/src/formant.rs @@ -291,6 +291,9 @@ pub(crate) struct Formant { /// The Q14 compensation, from the aspiration cutoff divided by the /// sample rate. noise_amplitude: i32, + /// If `true`, `add_noise` returns the input and does not advance the + /// random stream or the aspiration filter. + aspiration_muted: bool, /// The wrapping count of model designs that the stage tried. Only the /// telemetry reads it. generation: u32, @@ -354,32 +357,70 @@ impl Formant { noise_filter: Biquad::new(), noise_gain: 0_i32, noise_amplitude: 0_i32, + aspiration_muted: false, generation: 0, bank_epoch: 0, }; - result.set_config(config); + result.prepare_width(); + result.prepare_stretch(); + result.prepare_aspiration_mix(); + result.prepare_aspiration_cutoff(); result } - /// Quantizes the validated controls, prepares the Q7 map for the area - /// interpolation and updates the coefficients of the aspiration filter. + /// Quantizes the validated controls that changed, updates the Q7 area map + /// and updates the aspiration filter. /// - /// The histories do not change. A valid stretch gives a model with 25 to - /// 99 entries. Thus, the last point of the map and the denominators of - /// the interpolation are always defined. + /// The histories do not change. pub(crate) fn set_config(&mut self, config: FormantConfig) { + let old = self.config; self.config = config; - self.width = (config.width as f64 * 16384.0) as i32; - self.width_squared = (config.width as f64 * config.width as f64 * 16384.0) as i32; - self.stretch = (config.stretch as f64 * 16384.0) as i32; + if old.width != config.width { + self.prepare_width(); + } + if old.stretch != config.stretch { + self.prepare_stretch(); + } + if old.aspiration_mix != config.aspiration_mix { + self.prepare_aspiration_mix(); + } + if old.aspiration_cutoff_hz != config.aspiration_cutoff_hz { + self.prepare_aspiration_cutoff(); + } + } + /// Mutes or restores the random aspiration and keeps the configured + /// controls. + pub(crate) fn set_aspiration_muted(&mut self, muted: bool) { + self.aspiration_muted = muted; + } + /// Quantizes the width and its square to Q14. + fn prepare_width(&mut self) { + self.width = (self.config.width as f64 * 16384.0) as i32; + self.width_squared = (self.config.width as f64 * self.config.width as f64 * 16384.0) as i32; + } + /// Quantizes the stretch and prepares the Q7 map for the area + /// interpolation. + /// + /// A valid stretch gives a model with 25 to 99 entries. Thus, the last + /// point of the map and the denominators of the interpolation are always + /// defined. + fn prepare_stretch(&mut self) { + self.stretch = (self.config.stretch as f64 * 16384.0) as i32; self.stretch_count = - (((ORDER - 1) as f64 * config.stretch as f64 + 1.001) as usize).min(MAX_ORDER); + (((ORDER - 1) as f64 * self.config.stretch as f64 + 1.001) as usize).min(MAX_ORDER); for i in 0..self.stretch_count - 1 { let fraction = i as f64 / (self.stretch_count - 1) as f64; self.stretch_map[i] = ((ORDER - 1) as f64 * fraction * 128.0) as i32; } self.stretch_map[self.stretch_count - 1] = ((ORDER - 1) * 128) as i32; - self.noise_gain = (config.aspiration_mix as f64 * 16384.0) as i32; - let frequency = (config.aspiration_cutoff_hz as i32) + } + /// Quantizes the aspiration level to Q14. + fn prepare_aspiration_mix(&mut self) { + self.noise_gain = (self.config.aspiration_mix as f64 * 16384.0) as i32; + } + /// Updates the compensation and the high-pass coefficients of the + /// aspiration filter, and keeps the filter history. + fn prepare_aspiration_cutoff(&mut self) { + let frequency = (self.config.aspiration_cutoff_hz as i32) .min((self.rate.hz() as f64 * 0.48) as i32) .max(500); self.noise_amplitude = (frequency as f64 * 0.8 / self.rate.hz() as f64 * 16384.0) as i32; @@ -739,11 +780,11 @@ impl Formant { /// Blends random aspiration into a Q14 sample word. The signal modulates /// the aspiration, and a high-pass filter changes it. /// - /// If the level is 0.01 or less, the function returns immediately. The - /// random stream and the noise filter then do not advance. If not, the - /// function reads one random value. + /// If aspiration is muted or the level is 0.01 or less, the function + /// returns immediately. The random stream and the noise filter then do not + /// advance. If not, the function reads one random value. fn add_noise(&mut self, sample: i32, context: &mut NumericContext) -> i32 { - if self.config.aspiration_mix <= 0.01 { + if self.aspiration_muted || self.config.aspiration_mix <= 0.01 { return sample; } let random = context.random.next_u31() >> 17; diff --git a/src/processor.rs b/src/processor.rs index c728916..b9b685b 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -884,9 +884,9 @@ impl Processor { /// unused frames. /// /// The method mutes aspiration temporarily, but does not change the - /// settings that the host sees. It restores the configuration before - /// completion resets the state. `Some(0)` records completion, so later - /// drain calls continue to return zero. + /// settings that the host sees. It restores aspiration before completion + /// resets the state. `Some(0)` records completion, so later drain calls + /// continue to return zero. fn drain_into( &mut self, frames: usize, @@ -895,19 +895,11 @@ impl Processor { ) -> Result { self.check_block(frames)?; let count = self.drain_remaining.unwrap_or(0).min(frames); - let configured = self.config.resynthesis; - if configured.formant.aspiration_mix != 0.0 { - let mut silent = configured; - silent.formant.aspiration_mix = 0.0; - // Zero aspiration is valid in all validated configurations. - self.resynthesis.apply_config(silent); - } + self.resynthesis.set_aspiration_muted(true); for index in 0..count { write(index, self.next(0, layout)); } - if configured.formant.aspiration_mix != 0.0 { - self.resynthesis.apply_config(configured); - } + self.resynthesis.set_aspiration_muted(false); if let Some(remaining) = self.drain_remaining { let remaining = remaining - count; if remaining == 0 { diff --git a/src/resynthesis.rs b/src/resynthesis.rs index 82588ff..f6c61ad 100644 --- a/src/resynthesis.rs +++ b/src/resynthesis.rs @@ -388,6 +388,8 @@ 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 scale factor that converts milliseconds to Q20 integers. +const Q20_SCALE: f64 = (1_u32 << 20) as f64; /// Returns the reader position at the start of the history frame `frame`. #[inline] @@ -395,6 +397,12 @@ fn position_of(frame: i32) -> Q14 { Q14::from_bits(frame.wrapping_shl(14)) } +/// Returns the decay factor for the random choir drift at `rate`. +fn drift_decay_factor(rate: SampleRate) -> f64 { + let base = (rate.hz() / 100.0) as f64 * 0.2; + (-std::f64::consts::LN_2 / base).exp() +} + /// The resynthesis stage. /// /// The units are as follows: @@ -594,7 +602,8 @@ impl Resynthesis { sustained_decay: Q14::ZERO, retune_half_life: 0, sustained_half_life: 0, - decay_half_step: 0, + decay_half_step: (2500.0 * std::f64::consts::LN_2 / f64::from(rate.hz()) * Q20_SCALE + + 0.5) as i64, dwell: Q14::ZERO, dwell_step: Q14::ZERO, flex_tune: Q14::ZERO, @@ -612,7 +621,7 @@ impl Resynthesis { fade: Q14::ONE, current_output_period: Q6::ZERO, control_counter: CONTROL_DUE, - drift_decay: Q14::ZERO, + drift_decay: Q14::from_f64(drift_decay_factor(rate)), drift_amount: Q14::ZERO, previous_output: [Q14::ZERO; 2], }; @@ -623,18 +632,40 @@ impl Resynthesis { result } - /// Quantizes the controls and calculates the decay coefficients and the - /// voice pan gains again. + /// Quantizes all scalar controls and prepares the decay coefficients and + /// the voice gains. /// /// The coefficients cover correction, humanize, flex-tune and choir drift. - /// The histories and the controller phase do not change. The stereo pan - /// gains include the harmony gain. The mono harmony path uses a separate - /// Q14 gain. + /// The histories and the controller phase do not change. fn configure_coefficients(&mut self) { - const Q20_SCALE: f64 = (1_u32 << 20) as f64; + self.configure_pitch_ratio(); + self.configure_modulation(); + self.configure_dry_mix(); + self.configure_retune(); + self.configure_humanize(); + self.configure_flex_tune(); + self.configure_choir_detune(); + self.configure_choir_pan(); + self.configure_harmony_gain(); + } + + /// Quantizes the global pitch multiplier to Q14. + fn configure_pitch_ratio(&mut self) { self.shift = Q14::from_f64(self.config.pitch_ratio as f64); + } + + /// Quantizes the harmonic modulation depth. + fn configure_modulation(&mut self) { self.modulation = (self.config.harmonic_modulation as f64 / 8.0 * 16.0) as i32; + } + + /// Quantizes the dry mix fraction to Q8. + fn configure_dry_mix(&mut self) { self.dry_mix = Q8::from_f64((self.config.dry_mix * 100.0) as f64 / 100.0); + } + + /// Calculates the Q14 decay and Q20 half-life for `retune_ms`. + fn configure_retune(&mut self) { self.correction_decay = if self.config.correction.retune_ms == 0.0 { Q14::ZERO } else { @@ -643,13 +674,16 @@ impl Resynthesis { }; let retune_ms = f64::from(self.config.correction.retune_ms); self.retune_half_life = (retune_ms * Q20_SCALE + 0.5) as i64; - self.decay_half_step = - (2500.0 * std::f64::consts::LN_2 / f64::from(self.rate.hz()) * Q20_SCALE + 0.5) as i64; + } + + /// Calculates the sustained decay, half-life and dwell step for `humanize`. + fn configure_humanize(&mut self) { if self.config.correction.humanize == 0.0 { self.sustained_decay = self.correction_decay; self.sustained_half_life = self.retune_half_life; self.dwell_step = Q14::ZERO; } else { + let retune_ms = f64::from(self.config.correction.retune_ms); let sustained_ms = retune_ms + (400.0 - retune_ms) * f64::from(self.config.correction.humanize); let t = sustained_ms / 1000.0; @@ -659,15 +693,25 @@ impl Resynthesis { self.dwell_step = Q14::from_f64(1.0 / ((f64::from(self.rate.hz()) / 5.0) * 0.18)) .max(Q14::from_bits(1)); } + } + + /// Quantizes the outer soft-zone width for `flex_tune` to Q14. + fn configure_flex_tune(&mut self) { self.flex_tune = if self.config.correction.flex_tune == 0.0 { Q14::ZERO } else { Q14::from_f64(self.config.correction.flex_tune as f64).max(Q14::from_bits(1)) }; - let base = (self.rate.hz() / 100.0) as f64 * 0.2; - let decay = (-std::f64::consts::LN_2 / base).exp(); - self.drift_decay = Q14::from_f64(decay); + } + + /// Calculates the Q14 step weight for the random choir drift. + fn configure_choir_detune(&mut self) { + let decay = drift_decay_factor(self.rate); self.drift_amount = Q14::from_f64((1.0 - decay) * 0.008 * self.config.choir_detune as f64); + } + + /// Calculates the Q14 stereo pan gains for the active choir voices. + fn configure_choir_pan(&mut self) { for voice in 0..self.config.choir_voices as usize { if self.config.choir_voices > 1 { let normalized = @@ -680,6 +724,13 @@ impl Resynthesis { self.pan[voice] = [Q14::ONE; 2]; } } + } + + /// Calculates the Q14 gains for the four harmony voices. + /// + /// The stereo pan gains include the harmony gain. The mono harmony path + /// uses a separate Q14 gain. + fn configure_harmony_gain(&mut self) { self.harmony_gain = Q14::from_f64(self.config.harmony_gain as f64); for (voice, fraction) in [0.3333333333333333, 0.6666666666666666, 0.0, 1.0] .into_iter() @@ -734,9 +785,15 @@ impl Resynthesis { pub(crate) fn apply_config(&mut self, config: ResynthesisConfig) { let old = self.config; self.config = config; - self.pitch.set_config(config.pitch); - self.formant.set_config(config.formant); - self.harmony.apply_config(config.harmony); + if old.pitch != config.pitch { + self.pitch.set_config(config.pitch); + } + if old.formant != config.formant { + self.formant.set_config(config.formant); + } + if old.harmony != config.harmony { + self.harmony.apply_config(config.harmony); + } if old.correction.notes != config.correction.notes || old.correction.enabled != config.correction.enabled { @@ -746,7 +803,17 @@ impl Resynthesis { } else if config.correction.humanize == 0.0 { self.dwell = Q14::ZERO; } + if old.correction.retune_ms != config.correction.retune_ms { + self.configure_retune(); + self.configure_humanize(); + } else if old.correction.humanize != config.correction.humanize { + self.configure_humanize(); + } + if old.correction.flex_tune != config.correction.flex_tune { + self.configure_flex_tune(); + } if old.pitch_ratio != config.pitch_ratio { + self.configure_pitch_ratio(); self.configure_shift_filters(); self.scale_initialized = false; self.dwell = Q14::ZERO; @@ -759,7 +826,23 @@ impl Resynthesis { self.positions[voice] = self.positions[0]; } } - self.configure_coefficients(); + if old.choir_detune != config.choir_detune { + self.configure_choir_detune(); + } + if old.choir_voices != config.choir_voices + || old.choir_spread_percent != config.choir_spread_percent + { + self.configure_choir_pan(); + } + if old.harmony_gain != config.harmony_gain { + self.configure_harmony_gain(); + } + if old.harmonic_modulation != config.harmonic_modulation { + self.configure_modulation(); + } + if old.dry_mix != config.dry_mix { + self.configure_dry_mix(); + } if old.stereo_output != config.stereo_output { // A stereo change resets the audio state. The correction keyboard // keeps its held keys. @@ -767,6 +850,11 @@ impl Resynthesis { } } + /// Mutes or restores formant aspiration and keeps the configured controls. + pub(crate) fn set_aspiration_muted(&mut self, muted: bool) { + self.formant.set_aspiration_muted(muted); + } + /// Releases the correction keys 0..=127, loads the configured correction /// notes again and resets the audio state. ///