From f18960d8500507c533c69d2f2e6bae2249ad2c98 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Sat, 21 Nov 2026 01:55:10 +0000 Subject: [PATCH] feat(events)!: add scalar parameter control events - Add the ParameterControl enum and ControlEvent::Parameter. - Validate scalar controls with their stage paths and ranges. - Guard unchanged fields in the stage setters. - Mute aspiration with a flag on Formant for each drain call. - Add serde and tsify attributes for the Wasm package. - Document the scalar parameter variants and their ranges. --- README.md | 69 +++++++-- src/effects/punch.rs | 134 ++++++++++++++--- src/effects/reverb.rs | 118 +++++++++++++-- src/effects/warm.rs | 37 ++++- src/events.rs | 162 ++++++++++++++++++-- src/formant.rs | 159 ++++++++++++++++---- src/harmony.rs | 97 ++++++++++-- src/lib.rs | 2 +- src/pitch.rs | 7 +- src/pitch/tracker.rs | 7 +- src/processor.rs | 196 ++++++++++++++++++++----- src/resynthesis.rs | 333 +++++++++++++++++++++++++++++++++++++----- src/wasm.rs | 9 +- 13 files changed, 1151 insertions(+), 179 deletions(-) diff --git a/README.md b/README.md index d2993dc..0e404e3 100644 --- a/README.md +++ b/README.md @@ -237,23 +237,66 @@ These rules apply to the offsets: - An offset must not be less than the offset before it. Events with equal offsets execute in slice order. An empty block accepts no -events. A stage event replaces all settings of that stage. To change one -field, start from `processor.config()`. +events. A stage event replaces all settings of that stage. To change one scalar +field without a stage copy, use `ControlEvent::Parameter` with a +`ParameterControl` variant. For fields that are not scalar parameters, start +from `processor.config()`. Harmony MIDI uses `ControlEvent::Midi`. MIDI for the correction keyboard uses -`ControlEvent::CorrectionMidi`. For example, this event starts a harmony note -at frame 256: +`ControlEvent::CorrectionMidi`. For example, these events change the resynthesis +dry mix at frame 0 and start a harmony note at frame 256: ```rust -use tunelet::{ControlEvent, MidiEvent, TimedEvent}; - -let events = [TimedEvent { - offset: 256, - event: ControlEvent::Midi(MidiEvent::NoteOn { channel: 0, note: 64, velocity: 100 }), -}]; +use tunelet::{ControlEvent, MidiEvent, ParameterControl, TimedEvent}; + +let events = [ + TimedEvent { + offset: 0, + event: ControlEvent::Parameter(ParameterControl::DryMix(0.25)), + }, + TimedEvent { + offset: 256, + event: ControlEvent::Midi(MidiEvent::NoteOn { channel: 0, note: 64, velocity: 100 }), + }, +]; processor.process(&input, &mut output, &events)?; ``` +### Scalar parameters + +`ControlEvent::Parameter` accepts these `ParameterControl` variants. All ranges +are inclusive, and `f32` values must be finite. + +| Variant | TypeScript `type` | Configuration field | Range | +| ----------------------------- | ------------------------------- | --------------------------------------- | ----------------- | +| `PunchGainDb` | `"punchGainDb"` | `punch.gain_db` | `-96..=12` dB | +| `PunchImpact` | `"punchImpact"` | `punch.impact` | `0..=1` | +| `PunchCeilingDb` | `"punchCeilingDb"` | `punch.ceiling_db` | `-96..=0` dBFS | +| `PunchAttackMs` | `"punchAttackMs"` | `punch.attack_ms` | `0.01..=5000` ms | +| `WarmDriveDb` | `"warmDriveDb"` | `warm.drive_db` | `0..=6` dB | +| `PitchThreshold` | `"pitchThreshold"` | `resynthesis.pitch.threshold` | `0.002..=0.2` | +| `RetuneMs` | `"retuneMs"` | `resynthesis.correction.retune_ms` | `0..=400` ms | +| `PitchRatio` | `"pitchRatio"` | `resynthesis.pitch_ratio` | `0.25..=4` | +| `FormantWidth` | `"formantWidth"` | `resynthesis.formant.width` | `0.5..=2` | +| `FormantStretch` | `"formantStretch"` | `resynthesis.formant.stretch` | `0.5..=2` | +| `FormantAspirationMix` | `"formantAspirationMix"` | `resynthesis.formant.aspiration_mix` | `0..=1` | +| `FormantAspirationCutoffHz` | `"formantAspirationCutoffHz"` | `resynthesis.formant.aspiration_cutoff_hz` | `500..=10000` Hz | +| `ChoirVoices` | `"choirVoices"` | `resynthesis.choir_voices` | `1..=16` | +| `ChoirDetune` | `"choirDetune"` | `resynthesis.choir_detune` | `10..=100` | +| `ChoirDelay` | `"choirDelay"` | `resynthesis.choir_delay` | `20..=200` | +| `ChoirSpreadPercent` | `"choirSpreadPercent"` | `resynthesis.choir_spread_percent` | `0..=100`% | +| `HarmonyRegisterPercent` | `"harmonyRegisterPercent"` | `resynthesis.harmony.register_percent` | `0..=100`% | +| `HarmonyVoicingSpreadPercent` | `"harmonyVoicingSpreadPercent"` | `resynthesis.harmony.voicing_spread_percent` | `0..=100`% | +| `HarmonyPortamentoMs` | `"harmonyPortamentoMs"` | `resynthesis.harmony.portamento_ms` | `0..=10000` ms | +| `HarmonyVoices` | `"harmonyVoices"` | `resynthesis.harmony.voices` | `0..=4` | +| `HarmonyGain` | `"harmonyGain"` | `resynthesis.harmony_gain` | `0..=1` | +| `HarmonicModulation` | `"harmonicModulation"` | `resynthesis.harmonic_modulation` | `0..=24` | +| `DryMix` | `"dryMix"` | `resynthesis.dry_mix` | `0..=1` | +| `ReverbMix` | `"reverbMix"` | `reverb.mix` | `0..=1` | +| `ReverbDiffusion` | `"reverbDiffusion"` | `reverb.diffusion` | `0..=1` | +| `ReverbDecay` | `"reverbDecay"` | `reverb.decay` | `0..=1` | +| `ReverbBrightnessHz` | `"reverbBrightnessHz"` | `reverb.brightness_hz` | `80..=20000` Hz | + ## Lifecycle ![The processor lifecycle: construction, process calls, drain and reset](docs/images/lifecycle.svg) @@ -463,6 +506,12 @@ example, this event changes the final gain before the first frame: { offset: 0, event: { type: "outputGain", value: 0.5 } } ``` +A scalar parameter event nests a `ParameterControl` object: + +```ts +{ offset: 0, event: { type: "parameter", value: { type: "dryMix", value: 0.25 } } } +``` + A harmony Note On event has this form: ```ts diff --git a/src/effects/punch.rs b/src/effects/punch.rs index 867dc09..07bac17 100644 --- a/src/effects/punch.rs +++ b/src/effects/punch.rs @@ -78,19 +78,41 @@ impl PunchConfig { /// Returns the first [`Error::InvalidConfig`] with its dotted field path /// and the problem. pub fn validate(self) -> Result<(), Error> { - check_range("punch.gain_db", self.gain_db, -96.0, 12.0)?; - check_range("punch.impact", self.impact, 0.0, 1.0)?; - check_range("punch.ceiling_db", self.ceiling_db, -96.0, 0.0)?; - check_range("punch.attack_ms", self.attack_ms, 0.01, 5000.0) + validate_gain_db(self.gain_db)?; + validate_impact(self.impact)?; + validate_ceiling_db(self.ceiling_db)?; + validate_attack_ms(self.attack_ms) } } +/// Checks the range of the input gain of Punch. +pub(crate) fn validate_gain_db(gain_db: f32) -> Result<(), Error> { + check_range("punch.gain_db", gain_db, -96.0, 12.0) +} + +/// Checks the range of the transient emphasis of Punch. +pub(crate) fn validate_impact(impact: f32) -> Result<(), Error> { + check_range("punch.impact", impact, 0.0, 1.0) +} + +/// Checks the range of the output ceiling of Punch. +pub(crate) fn validate_ceiling_db(ceiling_db: f32) -> Result<(), Error> { + check_range("punch.ceiling_db", ceiling_db, -96.0, 0.0) +} + +/// Checks the range of the attack half-life of Punch. +pub(crate) fn validate_attack_ms(attack_ms: f32) -> Result<(), Error> { + check_range("punch.attack_ms", attack_ms, 0.01, 5000.0) +} + /// Two peak followers that control an arctangent saturator, with all buffers /// inline. #[derive(Debug)] pub(crate) struct Punch { /// The prepared rate, which converts the envelope times to sample windows. rate: SampleRate, + /// The validated controls that set the quantized coefficients. + config: PunchConfig, /// The adaptive Q14 peak envelope. The impact control sets its release. slow: Q14, /// The second Q14 peak envelope, with a fixed release half-life of 5 @@ -117,20 +139,22 @@ impl Punch { /// Prepares the coefficients and resets both followers from validated /// settings. pub(crate) fn new(rate: SampleRate, config: PunchConfig) -> Self { + let fast_decay = Q14::from_f64(envelope_decay(5000.0, rate.hz() as f64, WINDOW_FRAMES)); let mut result = Self { rate, + config, slow: Q14::default(), fast: Q14::default(), counter: 0, peak: Q14::default(), slow_decay: Q14::default(), - fast_decay: Q14::default(), + fast_decay, attack_decay: Q14::default(), gain: Q8::ONE, ceiling_gain: Q14::default(), drive: BASE_DRIVE, }; - result.set_config(config); + result.configure_all(); result.reset(); result } @@ -141,24 +165,92 @@ impl Punch { pub(crate) fn drive_ratio(&self) -> f32 { (self.drive.to_bits() as f64 / BASE_DRIVE.to_bits() as f64) as f32 } - /// Calculates the quantized controls again, and keeps the envelopes and - /// the cached drive. + /// Quantizes a decay half-life in milliseconds at the 100-frame cadence. + fn decay(&self, milliseconds: f64) -> Q14 { + Q14::from_f64(envelope_decay( + milliseconds, + self.rate.hz() as f64, + WINDOW_FRAMES, + )) + } + /// Updates the release coefficient of the adaptive follower. + fn configure_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(impact as f64); + } + /// Updates the shared attack coefficient of the two followers. + fn configure_attack_ms(&mut self) { + self.attack_decay = self.decay(self.config.attack_ms as f64); + } + /// Updates the quantized input gain. + fn configure_gain_db(&mut self) { + self.gain = Q8::from_f64(db_to_gain(self.config.gain_db as f64)); + } + /// Updates the quantized output ceiling. + fn configure_ceiling_db(&mut self) { + self.ceiling_gain = Q14::from_f64(db_to_gain(self.config.ceiling_db as f64)); + } + /// Initializes all configurable coefficients unconditionally. + fn configure_all(&mut self) { + self.configure_impact(); + self.configure_attack_ms(); + self.configure_gain_db(); + self.configure_ceiling_db(); + } + /// Calculates the changed quantized controls again, and keeps the + /// envelopes and the cached drive. + /// /// The processor controls the bypass. This stage never reads an enabled /// flag. pub(crate) fn set_config(&mut self, config: PunchConfig) { - let impact = coefficient_to_exp_value(1.0, 250.0, 5000.0, 1.0 - config.impact); - let decay = |milliseconds: f64| { - Q14::from_f64(envelope_decay( - milliseconds, - self.rate.hz() as f64, - WINDOW_FRAMES, - )) - }; - self.slow_decay = decay(impact as f64); - self.fast_decay = decay(5000.0); - self.attack_decay = decay(config.attack_ms as f64); - self.gain = Q8::from_f64(db_to_gain(config.gain_db as f64)); - self.ceiling_gain = Q14::from_f64(db_to_gain(config.ceiling_db as f64)); + let old = self.config; + self.config = config; + if old.impact != config.impact { + self.configure_impact(); + } + if old.attack_ms != config.attack_ms { + self.configure_attack_ms(); + } + if old.gain_db != config.gain_db { + self.configure_gain_db(); + } + if old.ceiling_db != config.ceiling_db { + self.configure_ceiling_db(); + } + } + /// Stores the input gain. If the value changed, quantizes it again. + pub(crate) fn set_gain_db(&mut self, gain_db: f32) { + let changed = self.config.gain_db != gain_db; + self.config.gain_db = gain_db; + if changed { + self.configure_gain_db(); + } + } + /// Stores the transient emphasis. If the value changed, updates the + /// release coefficient. + pub(crate) fn set_impact(&mut self, impact: f32) { + let changed = self.config.impact != impact; + self.config.impact = impact; + if changed { + self.configure_impact(); + } + } + /// Stores the output ceiling. If the value changed, quantizes it again. + pub(crate) fn set_ceiling_db(&mut self, ceiling_db: f32) { + let changed = self.config.ceiling_db != ceiling_db; + self.config.ceiling_db = ceiling_db; + if changed { + self.configure_ceiling_db(); + } + } + /// Stores the attack half-life. If the value changed, updates the attack + /// coefficient. + pub(crate) fn set_attack_ms(&mut self, attack_ms: f32) { + let changed = self.config.attack_ms != attack_ms; + self.config.attack_ms = attack_ms; + if changed { + self.configure_attack_ms(); + } } /// Clears both envelopes and the current window, then calculates the drive /// again from the base drive and the input gain. diff --git a/src/effects/reverb.rs b/src/effects/reverb.rs index fe60cd4..2329ddb 100644 --- a/src/effects/reverb.rs +++ b/src/effects/reverb.rs @@ -108,13 +108,33 @@ impl ReverbConfig { /// Returns the first [`Error::InvalidConfig`] with its dotted field path /// and the problem. pub fn validate(self) -> Result<(), Error> { - check_range("reverb.mix", self.mix, 0.0, 1.0)?; - check_range("reverb.diffusion", self.diffusion, 0.0, 1.0)?; - check_range("reverb.decay", self.decay, 0.0, 1.0)?; - check_range("reverb.brightness_hz", self.brightness_hz, 80.0, 20000.0) + validate_mix(self.mix)?; + validate_diffusion(self.diffusion)?; + validate_decay(self.decay)?; + validate_brightness_hz(self.brightness_hz) } } +/// Checks the range of the wet mix of the reverb. +pub(crate) fn validate_mix(mix: f32) -> Result<(), Error> { + check_range("reverb.mix", mix, 0.0, 1.0) +} + +/// Checks the range of the diffusion control of the reverb. +pub(crate) fn validate_diffusion(diffusion: f32) -> Result<(), Error> { + check_range("reverb.diffusion", diffusion, 0.0, 1.0) +} + +/// Checks the range of the decay control of the reverb. +pub(crate) fn validate_decay(decay: f32) -> Result<(), Error> { + check_range("reverb.decay", decay, 0.0, 1.0) +} + +/// Checks the range of the low-pass cutoff of the reverb. +pub(crate) fn validate_brightness_hz(brightness_hz: f32) -> Result<(), Error> { + check_range("reverb.brightness_hz", brightness_hz, 80.0, 20000.0) +} + /// The shared Q14 delay network with two low-pass damping filters that keep /// state. #[derive(Debug)] @@ -185,25 +205,93 @@ impl Reverb { scratch: layout.capacity - 1, wet_peak: 0, }; - result.set_config(config); + result.configure_all(); result } - /// Updates the coefficients and does not clear the delay or filter state. - /// The f32 multiplication by 100 occurs before the f64 division and the - /// quantization. If you combine these expressions, the quantized - /// coefficients can change. - pub(crate) fn set_config(&mut self, config: ReverbConfig) { - self.config = config; - self.mix = Q14::from_f64((config.mix * 100.0) as f64 / 100.0); - self.diffuse = Q14::from_f64((config.diffusion * 100.0) as f64 / 100.0); - self.decay = Q14::from_f64((config.decay * 100.0) as f64 / 105.0); - let brightness = config + /// Quantizes the wet contribution unconditionally. + fn configure_mix(&mut self) { + self.mix = Q14::from_f64((self.config.mix * 100.0) as f64 / 100.0); + } + /// Quantizes the diffusion control unconditionally. + fn configure_diffusion(&mut self) { + self.diffuse = Q14::from_f64((self.config.diffusion * 100.0) as f64 / 100.0); + } + /// Quantizes the feedback control unconditionally. + fn configure_decay(&mut self) { + self.decay = Q14::from_f64((self.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 .brightness_hz .min((self.rate.hz() as f64 * 0.49) as f32); let design = Design::low_pass_one_pole(self.rate.hz(), brightness); self.lpf1.set_design(design); self.lpf2.set_design(design); } + /// Initializes all coefficients and filter designs unconditionally. + fn configure_all(&mut self) { + self.configure_mix(); + self.configure_diffusion(); + self.configure_decay(); + self.configure_brightness_hz(); + } + /// Updates the changed coefficients and does not clear the delay or filter + /// state. + /// + /// The f32 multiplication by 100 occurs before the f64 division and the + /// quantization. If you combine these expressions, the quantized + /// coefficients can change. + pub(crate) fn set_config(&mut self, config: ReverbConfig) { + let old = self.config; + self.config = config; + if old.mix != config.mix { + self.configure_mix(); + } + if old.diffusion != config.diffusion { + self.configure_diffusion(); + } + if old.decay != config.decay { + self.configure_decay(); + } + if old.brightness_hz != config.brightness_hz { + self.configure_brightness_hz(); + } + } + /// 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.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 { + 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 { + 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 { + self.configure_brightness_hz(); + } + } /// Clears only the delay contents, and keeps the write cursor and the /// damping memories. pub(crate) fn reset(&mut self) { diff --git a/src/effects/warm.rs b/src/effects/warm.rs index 9721ced..71eed2e 100644 --- a/src/effects/warm.rs +++ b/src/effects/warm.rs @@ -51,14 +51,21 @@ impl WarmConfig { /// Returns the first [`Error::InvalidConfig`] with its dotted field path /// and the problem. pub fn validate(self) -> Result<(), Error> { - check_range("warm.drive_db", self.drive_db, 0.0, 6.0) + validate_drive_db(self.drive_db) } } +/// Checks the range of the drive of Warm. +pub(crate) fn validate_drive_db(drive_db: f32) -> Result<(), Error> { + check_range("warm.drive_db", drive_db, 0.0, 6.0) +} + /// An adaptive asymmetric saturator with one persistent high-pass output /// filter. #[derive(Debug)] pub(crate) struct Warm { + /// The validated controls that set the saturation drive. + config: WarmConfig, /// The 50 Hz one-pole high-pass output filter. filter: Biquad, /// The kept Q14 peak envelope from completed windows. @@ -90,6 +97,7 @@ impl Warm { let mut filter = Biquad::new(); filter.set_design(Design::high_pass_one_pole(rate.hz(), 50.0)); let mut result = Self { + config, filter, peak: Q14::default(), window_peak: Q14::default(), @@ -101,7 +109,7 @@ impl Warm { input_threshold: Q14::from_f64(db_to_gain(-30.0)), output_headroom: Q8::from_f64(db_to_gain(30.0)), }; - result.set_config(config); + result.configure_drive_db(); result } /// Returns the Q8 normalization gain as f32. The stage state does not @@ -109,11 +117,28 @@ impl Warm { pub(crate) fn normalization_gain(&self) -> f32 { (self.compression.to_bits() as f64 / 256.0) as f32 } - /// Updates the drive and the output compensation, and keeps the envelope - /// and filter state. + /// Quantizes the drive and its output compensation unconditionally. + fn configure_drive_db(&mut self) { + self.drive = Q12::from_f64(db_to_gain(self.config.drive_db as f64)); + self.output_gain = Q14::from_f64(db_to_gain(-(self.config.drive_db as f64) * 0.35)); + } + /// Stores the configuration. If the drive changed, updates the drive and + /// the output compensation, and keeps the envelope and filter state. pub(crate) fn set_config(&mut self, config: WarmConfig) { - self.drive = Q12::from_f64(db_to_gain(config.drive_db as f64)); - self.output_gain = Q14::from_f64(db_to_gain(-(config.drive_db as f64) * 0.35)); + let old = self.config; + self.config = config; + if old.drive_db != config.drive_db { + self.configure_drive_db(); + } + } + /// Stores the drive. If the value changed, updates the quantized drive and + /// its output compensation. + pub(crate) fn set_drive_db(&mut self, drive_db: f32) { + let changed = self.config.drive_db != drive_db; + self.config.drive_db = drive_db; + if changed { + self.configure_drive_db(); + } } /// Clears the filter memories, the peak windows and the normalization, /// and keeps the coefficients. diff --git a/src/events.rs b/src/events.rs index e1c975c..7da6353 100644 --- a/src/events.rs +++ b/src/events.rs @@ -2,20 +2,153 @@ use crate::config::validate_output_gain; use crate::effects::alien::AlienConfig; -use crate::effects::punch::PunchConfig; -use crate::effects::reverb::ReverbConfig; -use crate::effects::warm::WarmConfig; +use crate::effects::punch::{self, PunchConfig}; +use crate::effects::reverb::{self, ReverbConfig}; +use crate::effects::warm::{self, WarmConfig}; +use crate::formant; +use crate::harmony; use crate::midi::MidiEvent; +use crate::pitch; +use crate::resynthesis; use crate::{Error, EventProblem, ProcessorConfig, ResynthesisConfig}; +/// One scalar configuration parameter for [`ControlEvent::Parameter`]. +/// +/// Each variant updates one scalar field in [`ProcessorConfig`] and reports +/// the same dotted field name and inclusive range as its stage structure. All +/// `f32` values must be finite. +#[derive(Clone, Copy, Debug, PartialEq)] +#[non_exhaustive] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + derive(serde::Serialize, serde::Deserialize, tsify::Tsify), + serde(rename_all = "camelCase", tag = "type", content = "value") +)] +pub enum ParameterControl { + /// Sets [`PunchConfig::gain_db`] (`punch.gain_db`), -96..=12 dB. + PunchGainDb(f32), + /// Sets [`PunchConfig::impact`] (`punch.impact`), 0..=1. + PunchImpact(f32), + /// Sets [`PunchConfig::ceiling_db`] (`punch.ceiling_db`), -96..=0 dBFS. + PunchCeilingDb(f32), + /// Sets [`PunchConfig::attack_ms`] (`punch.attack_ms`), 0.01..=5000 ms. + PunchAttackMs(f32), + /// Sets [`WarmConfig::drive_db`] (`warm.drive_db`), 0..=6 dB. + WarmDriveDb(f32), + /// Sets [`crate::PitchConfig::threshold`] (`resynthesis.pitch.threshold`), + /// 0.002..=0.2. + PitchThreshold(f32), + /// Sets [`crate::CorrectionConfig::retune_ms`] + /// (`resynthesis.correction.retune_ms`), 0..=400 ms. + RetuneMs(f32), + /// Sets [`ResynthesisConfig::pitch_ratio`] (`resynthesis.pitch_ratio`), + /// 0.25..=4. + PitchRatio(f32), + /// Sets [`crate::FormantConfig::width`] (`resynthesis.formant.width`), + /// 0.5..=2. + FormantWidth(f32), + /// Sets [`crate::FormantConfig::stretch`] (`resynthesis.formant.stretch`), + /// 0.5..=2. + FormantStretch(f32), + /// Sets [`crate::FormantConfig::aspiration_mix`] + /// (`resynthesis.formant.aspiration_mix`), 0..=1. + FormantAspirationMix(f32), + /// Sets [`crate::FormantConfig::aspiration_cutoff_hz`] + /// (`resynthesis.formant.aspiration_cutoff_hz`), 500..=10000 Hz. + FormantAspirationCutoffHz(f32), + /// Sets [`ResynthesisConfig::choir_voices`] (`resynthesis.choir_voices`), + /// 1..=16. + ChoirVoices(u8), + /// Sets [`ResynthesisConfig::choir_detune`] (`resynthesis.choir_detune`), + /// 10..=100. + ChoirDetune(f32), + /// Sets [`ResynthesisConfig::choir_delay`] (`resynthesis.choir_delay`), + /// 20..=200. + ChoirDelay(f32), + /// Sets [`ResynthesisConfig::choir_spread_percent`] + /// (`resynthesis.choir_spread_percent`), 0..=100%. + ChoirSpreadPercent(f32), + /// Sets [`crate::HarmonyConfig::register_percent`] + /// (`resynthesis.harmony.register_percent`), 0..=100%. + HarmonyRegisterPercent(f32), + /// Sets [`crate::HarmonyConfig::voicing_spread_percent`] + /// (`resynthesis.harmony.voicing_spread_percent`), 0..=100%. + HarmonyVoicingSpreadPercent(f32), + /// Sets [`crate::HarmonyConfig::portamento_ms`] + /// (`resynthesis.harmony.portamento_ms`), 0..=10000 ms. + HarmonyPortamentoMs(f32), + /// Sets [`crate::HarmonyConfig::voices`] (`resynthesis.harmony.voices`), + /// 0..=4. + HarmonyVoices(u8), + /// Sets [`ResynthesisConfig::harmony_gain`] (`resynthesis.harmony_gain`), + /// 0..=1. + HarmonyGain(f32), + /// Sets [`ResynthesisConfig::harmonic_modulation`] + /// (`resynthesis.harmonic_modulation`), 0..=24. + HarmonicModulation(f32), + /// Sets [`ResynthesisConfig::dry_mix`] (`resynthesis.dry_mix`), 0..=1. + DryMix(f32), + /// Sets [`ReverbConfig::mix`] (`reverb.mix`), 0..=1. + ReverbMix(f32), + /// Sets [`ReverbConfig::diffusion`] (`reverb.diffusion`), 0..=1. + ReverbDiffusion(f32), + /// Sets [`ReverbConfig::decay`] (`reverb.decay`), 0..=1. + ReverbDecay(f32), + /// Sets [`ReverbConfig::brightness_hz`] (`reverb.brightness_hz`), + /// 80..=20000 Hz. + ReverbBrightnessHz(f32), +} + +impl ParameterControl { + /// Checks the finiteness and the inclusive range of the scalar parameter, + /// and does not apply it. + /// + /// # Errors + /// + /// Returns [`Error::InvalidConfig`] with the dotted field path and the + /// range or finiteness problem of the related stage field. + pub fn validate(self) -> Result<(), Error> { + match self { + Self::PunchGainDb(value) => punch::validate_gain_db(value), + Self::PunchImpact(value) => punch::validate_impact(value), + Self::PunchCeilingDb(value) => punch::validate_ceiling_db(value), + Self::PunchAttackMs(value) => punch::validate_attack_ms(value), + Self::WarmDriveDb(value) => warm::validate_drive_db(value), + Self::PitchThreshold(value) => pitch::validate_threshold(value), + Self::RetuneMs(value) => resynthesis::validate_retune_ms(value), + Self::PitchRatio(value) => resynthesis::validate_pitch_ratio(value), + Self::FormantWidth(value) => formant::validate_width(value), + Self::FormantStretch(value) => formant::validate_stretch(value), + Self::FormantAspirationMix(value) => formant::validate_aspiration_mix(value), + Self::FormantAspirationCutoffHz(value) => formant::validate_aspiration_cutoff_hz(value), + Self::ChoirVoices(value) => resynthesis::validate_choir_voices(value), + Self::ChoirDetune(value) => resynthesis::validate_choir_detune(value), + Self::ChoirDelay(value) => resynthesis::validate_choir_delay(value), + Self::ChoirSpreadPercent(value) => resynthesis::validate_choir_spread_percent(value), + Self::HarmonyRegisterPercent(value) => harmony::validate_register_percent(value), + Self::HarmonyVoicingSpreadPercent(value) => { + harmony::validate_voicing_spread_percent(value) + } + Self::HarmonyPortamentoMs(value) => harmony::validate_portamento_ms(value), + Self::HarmonyVoices(value) => harmony::validate_voices(value), + Self::HarmonyGain(value) => resynthesis::validate_harmony_gain(value), + Self::HarmonicModulation(value) => resynthesis::validate_harmonic_modulation(value), + Self::DryMix(value) => resynthesis::validate_dry_mix(value), + Self::ReverbMix(value) => reverb::validate_mix(value), + Self::ReverbDiffusion(value) => reverb::validate_diffusion(value), + Self::ReverbDecay(value) => reverb::validate_decay(value), + Self::ReverbBrightnessHz(value) => reverb::validate_brightness_hz(value), + } + } +} + /// A configuration or MIDI control that applies before a frame in the block. /// /// Give controls to a process call as [`TimedEvent`] values. The call borrows /// the slice only for that call. There is no heap allocation and no deferred -/// queue. A stage event replaces all settings of that stage. To change one -/// field, start from the current configuration of the processor. -/// Configuration changes have the same effects on state as -/// [`crate::Processor::set_config`]. +/// queue. Use [`Self::Parameter`] to change one scalar field. A stage event +/// replaces all settings of that stage. Configuration changes have the same +/// effects on state as [`crate::Processor::set_config`]. #[derive(Clone, Copy, Debug, PartialEq)] #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), @@ -40,6 +173,12 @@ pub enum ControlEvent { /// The quantization and the mute behavior are the same as for /// [`ProcessorConfig::output_gain`]. The value must be finite. OutputGain(f32), + /// This event updates one scalar parameter without a copy of the full stage + /// structure. + /// + /// Validation, quantization, state retention and drain cancellation are + /// identical to an equivalent stage event. + Parameter(ParameterControl), /// This event sends a note control to the harmony source that /// [`crate::HarmonyConfig`] selects. /// @@ -68,10 +207,10 @@ impl ControlEvent { /// /// # Errors /// - /// Returns [`Error::InvalidConfig`] for an invalid configuration or gain. - /// Returns [`Error::InvalidMidi`] for invalid MIDI fields. Reset is always - /// valid. The process call that contains the event checks the offset and - /// the order. + /// Returns [`Error::InvalidConfig`] for an invalid configuration, scalar + /// parameter or gain. Returns [`Error::InvalidMidi`] for invalid MIDI + /// fields. Reset is always valid. The process call that contains the event + /// checks the offset and the order. pub fn validate(self) -> Result<(), Error> { match self { Self::Configure(config) => config.validate(), @@ -81,6 +220,7 @@ impl ControlEvent { Self::Alien(config) => config.validate(), Self::Reverb(config) => config.validate(), Self::OutputGain(gain) => validate_output_gain(gain), + Self::Parameter(parameter) => parameter.validate(), Self::Midi(event) | Self::CorrectionMidi(event) => event.validate(), Self::Reset => Ok(()), } diff --git a/src/formant.rs b/src/formant.rs index 5072ee1..0c0e41a 100644 --- a/src/formant.rs +++ b/src/formant.rs @@ -95,15 +95,43 @@ impl FormantConfig { /// Returns the first [`Error::InvalidConfig`], with the dotted path of the /// field and the problem. pub fn validate(self) -> Result<(), Error> { - check_range("resynthesis.formant.width", self.width, 0.5, 2.0)?; - check_range("resynthesis.formant.stretch", self.stretch, 0.5, 2.0)?; - let field = "resynthesis.formant.aspiration_mix"; - check_range(field, self.aspiration_mix, 0.0, 1.0)?; - let field = "resynthesis.formant.aspiration_cutoff_hz"; - check_range(field, self.aspiration_cutoff_hz, 500.0, 10000.0) + validate_width(self.width)?; + validate_stretch(self.stretch)?; + validate_aspiration_mix(self.aspiration_mix)?; + validate_aspiration_cutoff_hz(self.aspiration_cutoff_hz) } } +/// Checks the range of the vocal-tract width. +pub(crate) fn validate_width(width: f32) -> Result<(), Error> { + check_range("resynthesis.formant.width", width, 0.5, 2.0) +} + +/// Checks the range of the vocal-tract length. +pub(crate) fn validate_stretch(stretch: f32) -> Result<(), Error> { + check_range("resynthesis.formant.stretch", stretch, 0.5, 2.0) +} + +/// Checks the range of the aspiration mix. +pub(crate) fn validate_aspiration_mix(aspiration_mix: f32) -> Result<(), Error> { + check_range( + "resynthesis.formant.aspiration_mix", + aspiration_mix, + 0.0, + 1.0, + ) +} + +/// Checks the range of the aspiration high-pass cutoff. +pub(crate) fn validate_aspiration_cutoff_hz(aspiration_cutoff_hz: f32) -> Result<(), Error> { + check_range( + "resynthesis.formant.aspiration_cutoff_hz", + aspiration_cutoff_hz, + 500.0, + 10000.0, + ) +} + /// The number of frames of input history for analysis and synthesis. The /// value is equal to the resynthesis history length. pub(crate) const HISTORY_FRAMES: usize = 11568; @@ -230,6 +258,8 @@ pub(crate) struct Formant { /// The Q14 compensation, from the aspiration cutoff divided by the /// sample rate. noise_amplitude: i32, + /// If `true`, the stage mutes aspiration temporarily for a drain. + aspiration_muted: bool, /// The wrapping count of model designs that the stage tried. Only the /// telemetry reads it. generation: u32, @@ -276,38 +306,116 @@ impl Formant { noise_filter: Biquad::new(), noise_gain: 0_i32, noise_amplitude: 0_i32, + aspiration_muted: false, generation: 0, }; - result.set_config(config); + result.configure_all(); result.reset(); result } - /// Quantizes the validated controls, prepares the Q7 map for the area - /// interpolation and updates the coefficients of the aspiration filter. + /// Sets the temporary aspiration mute for a drain without a change to the + /// configuration. + pub(crate) fn set_aspiration_muted(&mut self, muted: bool) { + self.aspiration_muted = muted; + } + /// Quantizes the vocal-tract width and its square unconditionally. + fn configure_width(&mut self) { + let width = self.config.width as f64; + self.width = (width * 16384.0) as i32; + self.width_squared = (width * width * 16384.0) as i32; + } + /// Quantizes the stretch factor and prepares the Q7 interpolation map + /// unconditionally. /// - /// 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. - pub(crate) fn set_config(&mut self, config: FormantConfig) { - 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; - self.stretch_count = - (((ORDER - 1) as f64 * config.stretch as f64 + 1.001) as usize).min(MAX_ORDER); + /// 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 configure_stretch(&mut self) { + let stretch = self.config.stretch as f64; + self.stretch = (stretch * 16384.0) as i32; + self.stretch_count = (((ORDER - 1) as f64 * stretch + 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 wet mix unconditionally. + fn configure_aspiration_mix(&mut self) { + self.noise_gain = (self.config.aspiration_mix as f64 * 16384.0) as i32; + } + /// Updates the compensation and high-pass filter for aspiration + /// unconditionally. + fn configure_aspiration_cutoff_hz(&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; self.noise_filter .set_design(Design::high_pass(self.rate.hz(), frequency as f32, 0.707)); } + /// Initializes all configurable controls and filter coefficients + /// unconditionally. + fn configure_all(&mut self) { + self.configure_width(); + self.configure_stretch(); + self.configure_aspiration_mix(); + self.configure_aspiration_cutoff_hz(); + } + /// Updates the quantized controls, the Q7 area map and the aspiration + /// filter for the fields that changed. + /// + /// The histories do not change. + pub(crate) fn set_config(&mut self, config: FormantConfig) { + let old = self.config; + self.config = config; + if old.width != config.width { + self.configure_width(); + } + if old.stretch != config.stretch { + self.configure_stretch(); + } + if old.aspiration_mix != config.aspiration_mix { + self.configure_aspiration_mix(); + } + if old.aspiration_cutoff_hz != config.aspiration_cutoff_hz { + self.configure_aspiration_cutoff_hz(); + } + } + /// Stores the vocal-tract width. If the value changed, quantizes it again. + pub(crate) fn set_width(&mut self, width: f32) { + let changed = self.config.width != width; + self.config.width = width; + if changed { + self.configure_width(); + } + } + /// Stores the vocal-tract stretch. If the value changed, prepares the area + /// map again. + pub(crate) fn set_stretch(&mut self, stretch: f32) { + let changed = self.config.stretch != stretch; + self.config.stretch = stretch; + if changed { + self.configure_stretch(); + } + } + /// Stores the aspiration mix. If the value changed, quantizes it again. + pub(crate) fn set_aspiration_mix(&mut self, aspiration_mix: f32) { + let changed = self.config.aspiration_mix != aspiration_mix; + self.config.aspiration_mix = aspiration_mix; + if changed { + self.configure_aspiration_mix(); + } + } + /// Stores the aspiration cutoff. If the value changed, updates the + /// high-pass filter. + pub(crate) fn set_aspiration_cutoff_hz(&mut self, aspiration_cutoff_hz: f32) { + let changed = self.config.aspiration_cutoff_hz != aspiration_cutoff_hz; + self.config.aspiration_cutoff_hz = aspiration_cutoff_hz; + if changed { + self.configure_aspiration_cutoff_hz(); + } + } /// Clears the audio, the stamps, the synthesis history and the history of /// the aspiration filter. /// @@ -325,6 +433,7 @@ impl Formant { self.next_filter(); self.design_counter = 0; self.noise_filter.reset(); + self.aspiration_muted = false; self.smooth_reset = true; } /// Starts a new model and a new correlation window when pitch acquisition @@ -660,11 +769,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 the stage mutes aspiration 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/harmony.rs b/src/harmony.rs index 67b7111..2fa2d59 100644 --- a/src/harmony.rs +++ b/src/harmony.rs @@ -378,21 +378,53 @@ impl HarmonyConfig { let field = "resynthesis.harmony.diatonic_intervals"; check_count(field, i64::from(interval), -14, 14)?; } - let field = "resynthesis.harmony.voices"; - check_count(field, i64::from(self.voices), 0, HARMONY_VOICES as i64)?; - let field = "resynthesis.harmony.register_percent"; - check_range(field, self.register_percent, 0.0, 100.0)?; - let field = "resynthesis.harmony.voicing_spread_percent"; - check_range(field, self.voicing_spread_percent, 0.0, 100.0)?; - check_range( - "resynthesis.harmony.portamento_ms", - self.portamento_ms, - 0.0, - 10_000.0, - ) + validate_voices(self.voices)?; + validate_register_percent(self.register_percent)?; + validate_voicing_spread_percent(self.voicing_spread_percent)?; + validate_portamento_ms(self.portamento_ms) } } +/// Checks the count of interval harmony voices. +pub(crate) fn validate_voices(voices: u8) -> Result<(), Error> { + check_count( + "resynthesis.harmony.voices", + i64::from(voices), + 0, + HARMONY_VOICES as i64, + ) +} + +/// Checks the range of the chord register. +pub(crate) fn validate_register_percent(register_percent: f32) -> Result<(), Error> { + check_range( + "resynthesis.harmony.register_percent", + register_percent, + 0.0, + 100.0, + ) +} + +/// Checks the range of the chord spread. +pub(crate) fn validate_voicing_spread_percent(voicing_spread_percent: f32) -> Result<(), Error> { + check_range( + "resynthesis.harmony.voicing_spread_percent", + voicing_spread_percent, + 0.0, + 100.0, + ) +} + +/// Checks the range of the portamento half-life. +pub(crate) fn validate_portamento_ms(portamento_ms: f32) -> Result<(), Error> { + check_range( + "resynthesis.harmony.portamento_ms", + portamento_ms, + 0.0, + 10_000.0, + ) +} + /// The prepared controller of periods and gains, and the MIDI allocator, for /// four voices. /// @@ -539,10 +571,49 @@ impl HarmonyState { if old.portamento_ms != config.portamento_ms { self.prepare_portamento(); } - if old != config { + if old.source != config.source + || old.key != config.key + || old.scale != config.scale + || old.chord != config.chord + || old.degree != config.degree + || old.inversion != config.inversion + || old.register_percent != config.register_percent + || old.voicing_spread_percent != config.voicing_spread_percent + { + self.setup_chord(); + } + } + /// Stores the chord register. If the value changed, prepares the chord + /// again. + pub(crate) fn set_register_percent(&mut self, register_percent: f32) { + let changed = self.config.register_percent != register_percent; + self.config.register_percent = register_percent; + if changed { self.setup_chord(); } } + /// Stores the chord spread. If the value changed, prepares the chord + /// again. + pub(crate) fn set_voicing_spread_percent(&mut self, voicing_spread_percent: f32) { + let changed = self.config.voicing_spread_percent != voicing_spread_percent; + self.config.voicing_spread_percent = voicing_spread_percent; + if changed { + self.setup_chord(); + } + } + /// Stores the portamento half-life. If the value changed, prepares the + /// smoothing coefficient again. + pub(crate) fn set_portamento_ms(&mut self, portamento_ms: f32) { + let changed = self.config.portamento_ms != portamento_ms; + self.config.portamento_ms = portamento_ms; + if changed { + self.prepare_portamento(); + } + } + /// Stores the count of interval voices. + pub(crate) fn set_voices(&mut self, voices: u8) { + self.config.voices = voices; + } /// Releases all MIDI notes and starts the MIDI assignment order again. /// /// The function clears these items: diff --git a/src/lib.rs b/src/lib.rs index 0e29119..f446e4a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -127,7 +127,7 @@ pub use effects::punch::PunchConfig; pub use effects::reverb::{ReverbConfig, ReverbMode}; pub use effects::warm::WarmConfig; pub use error::{ConfigProblem, Error, EventProblem}; -pub use events::{ControlEvent, TimedEvent}; +pub use events::{ControlEvent, ParameterControl, TimedEvent}; pub use formant::FormantConfig; pub use harmony::{ ChordDegree, ChordName, HarmonyConfig, HarmonyScale, HarmonySource, Inversion, HARMONY_VOICES, diff --git a/src/pitch.rs b/src/pitch.rs index 6b682ca..ee85339 100644 --- a/src/pitch.rs +++ b/src/pitch.rs @@ -79,7 +79,7 @@ impl PitchConfig { /// [`ConfigProblem::Unordered`]. The `other` value of that problem is /// `resynthesis.pitch.max_frequency_hz`. pub fn validate(self) -> Result<(), Error> { - check_range("resynthesis.pitch.threshold", self.threshold, 0.002, 0.2)?; + validate_threshold(self.threshold)?; let (min, max) = ( "resynthesis.pitch.min_frequency_hz", "resynthesis.pitch.max_frequency_hz", @@ -93,6 +93,11 @@ impl PitchConfig { } } +/// Checks the range of the pitch acquisition threshold. +pub(crate) fn validate_threshold(threshold: f32) -> Result<(), Error> { + check_range("resynthesis.pitch.threshold", threshold, 0.002, 0.2) +} + /// A pitch estimate as a period in samples and a frequency in hertz. /// /// The kept analysis and the host report use this type. The host gets it diff --git a/src/pitch/tracker.rs b/src/pitch/tracker.rs index 5123e0b..95f63c0 100644 --- a/src/pitch/tracker.rs +++ b/src/pitch/tracker.rs @@ -140,7 +140,12 @@ impl PitchTracker { /// The reporting bounds apply outside the tracker. A change of the /// sensitivity does not reset a tracked period. pub(crate) fn set_config(&mut self, config: PitchConfig) { - self.threshold = Q14::from_f64(config.threshold as f64); + self.set_threshold(config.threshold); + } + + /// Quantizes and stores a validated acquisition threshold. + pub(crate) fn set_threshold(&mut self, threshold: f32) { + self.threshold = Q14::from_f64(threshold as f64); } /// Clears the full-rate audio, the current period and the prefilter diff --git a/src/processor.rs b/src/processor.rs index cc910f4..c32a0c8 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -8,7 +8,7 @@ use crate::events::{ValidatedEvent, ValidatedEvents}; use crate::numeric::rng::RandomStream; use crate::numeric::NumericContext; use crate::resynthesis::{self, Resynthesis}; -use crate::{ControlEvent, Error, PrepareConfig, ProcessorConfig, TimedEvent}; +use crate::{ControlEvent, Error, ParameterControl, PrepareConfig, ProcessorConfig, TimedEvent}; /// A prepared vocal processor with state, mono input and stereo synthesis. /// @@ -573,33 +573,163 @@ impl Processor { /// Applies a validated control immediately before its frame is rendered. /// - /// A partial configuration event replaces one stage in the active - /// configuration. MIDI and reset events act directly. A reset does not - /// discard later events in the block. + /// A stage event replaces one stage in the active configuration. A scalar + /// parameter event updates one field and its quantized state. MIDI and + /// reset events act directly. A reset does not discard later events in the + /// block. fn apply(&mut self, event: ValidatedEvent) { - let mut config = self.config; match event.into_inner() { - ControlEvent::Configure(value) => config = value, - ControlEvent::Resynthesis(value) => config.resynthesis = value, - ControlEvent::Punch(value) => config.punch = value, - ControlEvent::Warm(value) => config.warm = value, - ControlEvent::Alien(value) => config.alien = value, - ControlEvent::Reverb(value) => config.reverb = value, - ControlEvent::OutputGain(value) => config.output_gain = value, - ControlEvent::Midi(event) => { - self.resynthesis.apply_midi(event); - return; - } - ControlEvent::CorrectionMidi(event) => { - self.resynthesis.apply_correction_midi(event); - return; - } - ControlEvent::Reset => { - self.reset(); - return; + ControlEvent::Configure(value) => self.apply_config(value), + ControlEvent::Resynthesis(value) => { + let mut config = self.config; + config.resynthesis = value; + self.apply_config(config); + } + ControlEvent::Punch(value) => { + let mut config = self.config; + config.punch = value; + self.apply_config(config); + } + ControlEvent::Warm(value) => { + let mut config = self.config; + config.warm = value; + self.apply_config(config); + } + ControlEvent::Alien(value) => { + let mut config = self.config; + config.alien = value; + self.apply_config(config); + } + ControlEvent::Reverb(value) => { + let mut config = self.config; + config.reverb = value; + self.apply_config(config); } + ControlEvent::OutputGain(value) => { + self.config.output_gain = value; + self.drain_remaining = None; + } + ControlEvent::Parameter(parameter) => self.apply_parameter(parameter), + ControlEvent::Midi(event) => self.resynthesis.apply_midi(event), + ControlEvent::CorrectionMidi(event) => self.resynthesis.apply_correction_midi(event), + ControlEvent::Reset => self.reset(), } - self.apply_config(config); + } + + /// Updates one validated scalar parameter, cancels an active drain and + /// calls only the setter for that field. + fn apply_parameter(&mut self, parameter: ParameterControl) { + match parameter { + ParameterControl::PunchGainDb(value) => { + self.config.punch.gain_db = value; + self.punch.set_gain_db(value); + } + ParameterControl::PunchImpact(value) => { + self.config.punch.impact = value; + self.punch.set_impact(value); + } + ParameterControl::PunchCeilingDb(value) => { + self.config.punch.ceiling_db = value; + self.punch.set_ceiling_db(value); + } + ParameterControl::PunchAttackMs(value) => { + self.config.punch.attack_ms = value; + self.punch.set_attack_ms(value); + } + ParameterControl::WarmDriveDb(value) => { + self.config.warm.drive_db = value; + self.warm.set_drive_db(value); + } + ParameterControl::PitchThreshold(value) => { + self.config.resynthesis.pitch.threshold = value; + self.resynthesis.set_pitch_threshold(value); + } + ParameterControl::RetuneMs(value) => { + self.config.resynthesis.correction.retune_ms = value; + self.resynthesis.set_retune_ms(value); + } + ParameterControl::PitchRatio(value) => { + self.config.resynthesis.pitch_ratio = value; + self.resynthesis.set_pitch_ratio(value); + } + ParameterControl::FormantWidth(value) => { + self.config.resynthesis.formant.width = value; + self.resynthesis.set_formant_width(value); + } + ParameterControl::FormantStretch(value) => { + self.config.resynthesis.formant.stretch = value; + self.resynthesis.set_formant_stretch(value); + } + ParameterControl::FormantAspirationMix(value) => { + self.config.resynthesis.formant.aspiration_mix = value; + self.resynthesis.set_formant_aspiration_mix(value); + } + ParameterControl::FormantAspirationCutoffHz(value) => { + self.config.resynthesis.formant.aspiration_cutoff_hz = value; + self.resynthesis.set_formant_aspiration_cutoff_hz(value); + } + ParameterControl::ChoirVoices(value) => { + self.config.resynthesis.choir_voices = value; + self.resynthesis.set_choir_voices(value); + } + ParameterControl::ChoirDetune(value) => { + self.config.resynthesis.choir_detune = value; + self.resynthesis.set_choir_detune(value); + } + ParameterControl::ChoirDelay(value) => { + self.config.resynthesis.choir_delay = value; + self.resynthesis.set_choir_delay(value); + } + ParameterControl::ChoirSpreadPercent(value) => { + self.config.resynthesis.choir_spread_percent = value; + self.resynthesis.set_choir_spread_percent(value); + } + ParameterControl::HarmonyRegisterPercent(value) => { + self.config.resynthesis.harmony.register_percent = value; + self.resynthesis.set_harmony_register_percent(value); + } + ParameterControl::HarmonyVoicingSpreadPercent(value) => { + self.config.resynthesis.harmony.voicing_spread_percent = value; + self.resynthesis.set_harmony_voicing_spread_percent(value); + } + ParameterControl::HarmonyPortamentoMs(value) => { + self.config.resynthesis.harmony.portamento_ms = value; + self.resynthesis.set_harmony_portamento_ms(value); + } + ParameterControl::HarmonyVoices(value) => { + self.config.resynthesis.harmony.voices = value; + self.resynthesis.set_harmony_voices(value); + } + ParameterControl::HarmonyGain(value) => { + self.config.resynthesis.harmony_gain = value; + self.resynthesis.set_harmony_gain(value); + } + ParameterControl::HarmonicModulation(value) => { + self.config.resynthesis.harmonic_modulation = value; + self.resynthesis.set_harmonic_modulation(value); + } + ParameterControl::DryMix(value) => { + self.config.resynthesis.dry_mix = value; + self.resynthesis.set_dry_mix(value); + } + ParameterControl::ReverbMix(value) => { + self.config.reverb.mix = value; + self.reverb.set_mix(value); + } + ParameterControl::ReverbDiffusion(value) => { + self.config.reverb.diffusion = value; + self.reverb.set_diffusion(value); + } + ParameterControl::ReverbDecay(value) => { + self.config.reverb.decay = value; + self.reverb.set_decay(value); + } + ParameterControl::ReverbBrightnessHz(value) => { + self.config.reverb.brightness_hz = value; + self.reverb.set_brightness_hz(value); + } + } + self.drain_remaining = None; } /// Renders one frame through the full chain and updates stereo feedback. @@ -662,9 +792,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 clears the mute before completion + /// resets the state. `Some(0)` records completion, so later drain calls + /// continue to return zero. fn drain_into( &mut self, frames: usize, @@ -672,19 +802,11 @@ impl Processor { ) -> Result { self.check_block(frames)?; let count = self.drain_remaining.unwrap_or(0).min(frames); - let configured = self.config.resynthesis; - if configured.formant.aspiration_mix != 0.0 { - let mut silent = configured; - silent.formant.aspiration_mix = 0.0; - // Zero aspiration is valid in all validated configurations. - self.resynthesis.apply_config(silent); - } + self.resynthesis.set_aspiration_muted(true); for index in 0..count { write(index, self.next(0)); } - if configured.formant.aspiration_mix != 0.0 { - self.resynthesis.apply_config(configured); - } + self.resynthesis.set_aspiration_muted(false); if let Some(remaining) = self.drain_remaining { let remaining = remaining - count; if remaining == 0 { diff --git a/src/resynthesis.rs b/src/resynthesis.rs index 34e98fa..e09885a 100644 --- a/src/resynthesis.rs +++ b/src/resynthesis.rs @@ -130,15 +130,15 @@ impl CorrectionConfig { /// Returns [`Error::InvalidConfig`], with the dotted path of the field and /// the problem, if `retune_ms` is not valid. pub fn validate(self) -> Result<(), Error> { - check_range( - "resynthesis.correction.retune_ms", - self.retune_ms, - 0.0, - 400.0, - ) + validate_retune_ms(self.retune_ms) } } +/// Checks the range of the retune half-life. +pub(crate) fn validate_retune_ms(retune_ms: f32) -> Result<(), Error> { + check_range("resynthesis.correction.retune_ms", retune_ms, 0.0, 400.0) +} + /// The controls for pitch correction, pitch shift, voice arrangement and /// formants. /// @@ -293,24 +293,67 @@ impl ResynthesisConfig { self.correction.validate()?; self.formant.validate()?; self.harmony.validate()?; - check_range("resynthesis.pitch_ratio", self.pitch_ratio, 0.25, 4.0)?; - check_range("resynthesis.choir_detune", self.choir_detune, 10.0, 100.0)?; - check_range("resynthesis.choir_delay", self.choir_delay, 20.0, 200.0)?; - let field = "resynthesis.choir_spread_percent"; - check_range(field, self.choir_spread_percent, 0.0, 100.0)?; - check_range("resynthesis.harmony_gain", self.harmony_gain, 0.0, 1.0)?; - let field = "resynthesis.harmonic_modulation"; - check_range(field, self.harmonic_modulation, 0.0, 24.0)?; - check_range("resynthesis.dry_mix", self.dry_mix, 0.0, 1.0)?; - check_count( - "resynthesis.choir_voices", - i64::from(self.choir_voices), - 1, - 16, - ) + validate_pitch_ratio(self.pitch_ratio)?; + validate_choir_detune(self.choir_detune)?; + validate_choir_delay(self.choir_delay)?; + validate_choir_spread_percent(self.choir_spread_percent)?; + validate_harmony_gain(self.harmony_gain)?; + validate_harmonic_modulation(self.harmonic_modulation)?; + validate_dry_mix(self.dry_mix)?; + validate_choir_voices(self.choir_voices) } } +/// Checks the range of the global pitch multiplier. +pub(crate) fn validate_pitch_ratio(pitch_ratio: f32) -> Result<(), Error> { + check_range("resynthesis.pitch_ratio", pitch_ratio, 0.25, 4.0) +} + +/// Checks the range of the choir voice count. +pub(crate) fn validate_choir_voices(choir_voices: u8) -> Result<(), Error> { + check_count("resynthesis.choir_voices", i64::from(choir_voices), 1, 16) +} + +/// Checks the range of the choir detune. +pub(crate) fn validate_choir_detune(choir_detune: f32) -> Result<(), Error> { + check_range("resynthesis.choir_detune", choir_detune, 10.0, 100.0) +} + +/// Checks the range of the choir delay scale. +pub(crate) fn validate_choir_delay(choir_delay: f32) -> Result<(), Error> { + check_range("resynthesis.choir_delay", choir_delay, 20.0, 200.0) +} + +/// Checks the range of the choir stereo width. +pub(crate) fn validate_choir_spread_percent(choir_spread_percent: f32) -> Result<(), Error> { + check_range( + "resynthesis.choir_spread_percent", + choir_spread_percent, + 0.0, + 100.0, + ) +} + +/// Checks the range of the harmony pan gain. +pub(crate) fn validate_harmony_gain(harmony_gain: f32) -> Result<(), Error> { + check_range("resynthesis.harmony_gain", harmony_gain, 0.0, 1.0) +} + +/// Checks the range of the harmonic modulation depth. +pub(crate) fn validate_harmonic_modulation(harmonic_modulation: f32) -> Result<(), Error> { + check_range( + "resynthesis.harmonic_modulation", + harmonic_modulation, + 0.0, + 24.0, + ) +} + +/// Checks the range of the resynthesis dry mix. +pub(crate) fn validate_dry_mix(dry_mix: f32) -> Result<(), Error> { + check_range("resynthesis.dry_mix", dry_mix, 0.0, 1.0) +} + /// The fixed choir delay offsets in frames, before the scale by /// `choir_delay / 200`. /// @@ -549,33 +592,48 @@ impl Resynthesis { drift_amount: Q14::ZERO, previous_output: [Q14::ZERO; 2], }; - result.configure_coefficients(); + result.configure_all(); result.configure_shift_filters(); result.reset(); result } - /// Quantizes the controls and calculates the decay coefficients and the - /// voice pan gains again. - /// - /// The coefficients are the correction decay, the drift decay and the - /// drift amount. The histories and the controller phase do not change. - /// The harmony level is part of the stereo pan gains. Thus, the path - /// without pan never applies that control. - fn configure_coefficients(&mut self) { + /// Quantizes the global pitch multiplier unconditionally. + fn configure_pitch_ratio(&mut self) { self.shift = Q14::from_f64(self.config.pitch_ratio as f64); + } + + /// Quantizes the harmonic modulation depth unconditionally. + fn configure_harmonic_modulation(&mut self) { self.modulation = (self.config.harmonic_modulation as f64 / 8.0 * 16.0) as i32; + } + + /// Quantizes the dry mix weight unconditionally. + fn configure_dry_mix(&mut self) { self.dry_mix = Q8::from_f64((self.config.dry_mix * 100.0) as f64 / 100.0); + } + + /// Calculates the correction half-life coefficient unconditionally. + fn configure_correction_decay(&mut self) { self.correction_decay = if self.config.correction.retune_ms == 0.0 { Q14::ZERO } else { let t = self.config.correction.retune_ms / 1000.0; Q14::from_f64(0.5_f64.powf(1.0 / ((self.rate.hz() / 5.0) * t) as f64)) }; + } + + /// Calculates the choir drift decay and drift amount unconditionally. + fn configure_choir_drift(&mut self) { 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); self.drift_amount = Q14::from_f64((1.0 - decay) * 0.008 * self.config.choir_detune as f64); + } + + /// Calculates the stereo pan gains for the active choir voices + /// unconditionally. + fn configure_choir_pan(&mut self) { for voice in 0..self.config.choir_voices as usize { if self.config.choir_voices > 1 { let normalized = @@ -588,6 +646,13 @@ impl Resynthesis { self.pan[voice] = [Q14::ONE; 2]; } } + } + + /// Calculates the stereo pan gains for the harmony voices unconditionally. + /// + /// The harmony level is part of the stereo pan gains. Thus, the path + /// without pan never applies that control. + fn configure_harmony_pan(&mut self) { for (voice, fraction) in [0.3333333333333333, 0.6666666666666666, 0.0, 1.0] .into_iter() .enumerate() @@ -601,6 +666,20 @@ impl Resynthesis { } } + /// Initializes all quantized controls, decays and pan gains + /// unconditionally. + /// + /// The histories and the controller phase do not change. + fn configure_all(&mut self) { + self.configure_pitch_ratio(); + self.configure_harmonic_modulation(); + self.configure_dry_mix(); + self.configure_correction_decay(); + self.configure_choir_drift(); + self.configure_choir_pan(); + self.configure_harmony_pan(); + } + /// Prepares two low-pass sections if the global shift is upward. If not, /// sets coefficients of 1.0 and zero. /// @@ -641,16 +720,26 @@ impl Resynthesis { pub(crate) fn apply_config(&mut self, config: ResynthesisConfig) { let old = self.config; self.config = config; - self.pitch.set_config(config.pitch); - self.formant.set_config(config.formant); - self.harmony.apply_config(config.harmony); + if old.pitch.threshold != config.pitch.threshold { + self.pitch.set_config(config.pitch); + } + if old.formant != config.formant { + self.formant.set_config(config.formant); + } + if old.harmony != config.harmony { + self.harmony.apply_config(config.harmony); + } if old.correction.notes != config.correction.notes || old.correction.enabled != config.correction.enabled { self.scale.set_notes(config.correction.notes); self.scale_initialized = false; } + if old.correction.retune_ms != config.correction.retune_ms { + self.configure_correction_decay(); + } if old.pitch_ratio != config.pitch_ratio { + self.configure_pitch_ratio(); self.configure_shift_filters(); } if old.mode != config.mode || old.choir_delay != config.choir_delay { @@ -661,7 +750,23 @@ impl Resynthesis { self.positions[voice] = self.positions[0]; } } - self.configure_coefficients(); + if old.choir_voices != config.choir_voices + || old.choir_spread_percent != config.choir_spread_percent + { + self.configure_choir_pan(); + } + if old.choir_detune != config.choir_detune { + self.configure_choir_drift(); + } + if old.harmony_gain != config.harmony_gain { + self.configure_harmony_pan(); + } + if old.harmonic_modulation != config.harmonic_modulation { + self.configure_harmonic_modulation(); + } + if old.dry_mix != config.dry_mix { + self.configure_dry_mix(); + } if old.stereo_output != config.stereo_output { // A stereo change resets the audio state. The correction keyboard // keeps its held keys. @@ -669,6 +774,166 @@ impl Resynthesis { } } + /// Sets the temporary aspiration mute for a drain without a change to the + /// configuration. + pub(crate) fn set_aspiration_muted(&mut self, muted: bool) { + self.formant.set_aspiration_muted(muted); + } + + /// Stores the pitch acquisition threshold. If the value changed, quantizes + /// it again. + pub(crate) fn set_pitch_threshold(&mut self, threshold: f32) { + let changed = self.config.pitch.threshold != threshold; + self.config.pitch.threshold = threshold; + if changed { + self.pitch.set_threshold(threshold); + } + } + + /// Stores the retune half-life. If the value changed, updates the + /// correction decay. + pub(crate) fn set_retune_ms(&mut self, retune_ms: f32) { + let changed = self.config.correction.retune_ms != retune_ms; + self.config.correction.retune_ms = retune_ms; + if changed { + self.configure_correction_decay(); + } + } + + /// Stores the global pitch multiplier. If the value changed, updates the + /// shift and the anti-alias filters. + pub(crate) fn set_pitch_ratio(&mut self, pitch_ratio: f32) { + let changed = self.config.pitch_ratio != pitch_ratio; + self.config.pitch_ratio = pitch_ratio; + if changed { + self.configure_pitch_ratio(); + self.configure_shift_filters(); + } + } + + /// Stores the vocal-tract width and updates the formant stage. + pub(crate) fn set_formant_width(&mut self, width: f32) { + self.config.formant.width = width; + self.formant.set_width(width); + } + + /// Stores the vocal-tract stretch and updates the formant stage. + pub(crate) fn set_formant_stretch(&mut self, stretch: f32) { + self.config.formant.stretch = stretch; + self.formant.set_stretch(stretch); + } + + /// Stores the aspiration mix and updates the formant stage. + pub(crate) fn set_formant_aspiration_mix(&mut self, aspiration_mix: f32) { + self.config.formant.aspiration_mix = aspiration_mix; + self.formant.set_aspiration_mix(aspiration_mix); + } + + /// Stores the aspiration high-pass cutoff and updates the formant stage. + pub(crate) fn set_formant_aspiration_cutoff_hz(&mut self, aspiration_cutoff_hz: f32) { + self.config.formant.aspiration_cutoff_hz = aspiration_cutoff_hz; + self.formant.set_aspiration_cutoff_hz(aspiration_cutoff_hz); + } + + /// Stores the choir voice count. If the value changed, updates new reader + /// positions and the choir pan gains. + pub(crate) fn set_choir_voices(&mut self, choir_voices: u8) { + let old = self.config.choir_voices; + self.config.choir_voices = choir_voices; + if old != choir_voices { + if old < choir_voices { + for voice in old as usize..choir_voices as usize { + self.positions[voice] = self.positions[0]; + } + } + self.configure_choir_pan(); + } + } + + /// Stores the choir detune. If the value changed, updates the drift + /// coefficients. + pub(crate) fn set_choir_detune(&mut self, choir_detune: f32) { + let changed = self.config.choir_detune != choir_detune; + self.config.choir_detune = choir_detune; + if changed { + self.configure_choir_drift(); + } + } + + /// Stores the choir delay scale. If the value changed, updates the delay + /// offsets. + 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(); + } + } + + /// Stores the choir stereo width. If the value changed, updates the choir + /// pan gains. + pub(crate) fn set_choir_spread_percent(&mut self, choir_spread_percent: f32) { + let changed = self.config.choir_spread_percent != choir_spread_percent; + self.config.choir_spread_percent = choir_spread_percent; + if changed { + self.configure_choir_pan(); + } + } + + /// Stores the chord register and updates the harmony stage. + pub(crate) fn set_harmony_register_percent(&mut self, register_percent: f32) { + self.config.harmony.register_percent = register_percent; + self.harmony.set_register_percent(register_percent); + } + + /// Stores the chord spread and updates the harmony stage. + pub(crate) fn set_harmony_voicing_spread_percent(&mut self, voicing_spread_percent: f32) { + self.config.harmony.voicing_spread_percent = voicing_spread_percent; + self.harmony + .set_voicing_spread_percent(voicing_spread_percent); + } + + /// Stores the portamento half-life and updates the harmony stage. + pub(crate) fn set_harmony_portamento_ms(&mut self, portamento_ms: f32) { + self.config.harmony.portamento_ms = portamento_ms; + self.harmony.set_portamento_ms(portamento_ms); + } + + /// Stores the count of interval voices and updates the harmony stage. + pub(crate) fn set_harmony_voices(&mut self, voices: u8) { + self.config.harmony.voices = voices; + self.harmony.set_voices(voices); + } + + /// Stores the harmony pan gain. If the value changed, updates the harmony + /// pan gains. + pub(crate) fn set_harmony_gain(&mut self, harmony_gain: f32) { + let changed = self.config.harmony_gain != harmony_gain; + self.config.harmony_gain = harmony_gain; + if changed { + self.configure_harmony_pan(); + } + } + + /// Stores the harmonic modulation depth. If the value changed, quantizes it + /// again. + pub(crate) fn set_harmonic_modulation(&mut self, harmonic_modulation: f32) { + let changed = self.config.harmonic_modulation != harmonic_modulation; + self.config.harmonic_modulation = harmonic_modulation; + if changed { + self.configure_harmonic_modulation(); + } + } + + /// Stores the dry mix weight. If the value changed, quantizes it again. + pub(crate) fn set_dry_mix(&mut self, dry_mix: f32) { + let changed = self.config.dry_mix != dry_mix; + self.config.dry_mix = dry_mix; + if changed { + self.configure_dry_mix(); + } + } + /// Releases the correction keys 0..=126 and resets the audio state. /// /// The active correction table, key 127 and the items that diff --git a/src/wasm.rs b/src/wasm.rs index c9cec08..3df5d02 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -22,10 +22,11 @@ //! - The optional harmony `voices` field defaults to 4. //! //! [`default_config`] gives a configuration to start from. Control events use -//! `{ type, value }`, and the reset control has no `value`. MIDI messages use -//! `{ type, channel, note, velocity }`, with the fields that apply to the -//! selected variant. The TypeScript declarations come from the same Rust types -//! that validation uses. +//! `{ type, value }`, and the reset control has no `value`. Scalar parameter +//! events nest `{ type, value }` inside `{ type: "parameter", value }`. MIDI +//! messages use `{ type, channel, note, velocity }`, with the fields that +//! apply to the selected variant. The TypeScript declarations come from the +//! same Rust types that validation uses. //! //! The class allocates the PCM storage at construction and uses it again for //! each block. These operations can allocate: