diff --git a/README.md b/README.md index 66060d8..d516268 100644 --- a/README.md +++ b/README.md @@ -259,23 +259,68 @@ 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 | +| `Humanize` | `"humanize"` | `resynthesis.correction.humanize` | `0..=1` | +| `FlexTune` | `"flexTune"` | `resynthesis.correction.flex_tune` | `0..=1` | +| `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) @@ -552,6 +597,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/scripts/normalize-jsdoc.mjs b/scripts/normalize-jsdoc.mjs index ad18b1d..f7323d4 100644 --- a/scripts/normalize-jsdoc.mjs +++ b/scripts/normalize-jsdoc.mjs @@ -81,6 +81,11 @@ const EXACT_REPLACEMENTS = [ ["[`HarmonyScale`]", "`HarmonyScale`"], ["[`Feedback`]", "`Feedback`"], ["[`HarmonyConfig`]", "`HarmonyConfig`"], + [ + "[`ControlEvent::Parameter`]", + '`{ type: "parameter", value }` in `ControlEvent`', + ], + ["[`Self::Parameter`]", '`{ type: "parameter", value }`'], ["[`Self::I`]", '`"i"`'], ["[`Self::Echo`]", '`"echo"`'], ["[`ReverbMode::Echo`]", '`"echo"`'], diff --git a/scripts/verify-pack.mjs b/scripts/verify-pack.mjs index be2bc0f..5dfcbba 100644 --- a/scripts/verify-pack.mjs +++ b/scripts/verify-pack.mjs @@ -367,7 +367,14 @@ function verifyRuntimeImport(consumerDir, packageName) { " const input = new Int16Array(128);", " const left = new Int16Array(128);", " const right = new Int16Array(128);", - " processor.process(input, left, right);", + ' processor.process(input, left, right, [', + ' { offset: 0, event: { type: "parameter", value: { type: "dryMix", value: 0.25 } } },', + ' { offset: 0, event: { type: "parameter", value: { type: "humanize", value: 0.5 } } },', + ' { offset: 0, event: { type: "parameter", value: { type: "flexTune", value: 0.25 } } },', + " ]);", + " assert.equal(processor.config().resynthesis.dryMix, 0.25);", + " assert.equal(processor.config().resynthesis.correction.humanize, 0.5);", + " assert.equal(processor.config().resynthesis.correction.flexTune, 0.25);", "} finally {", " processor.free();", "}", @@ -724,6 +731,8 @@ function verifyTypeDeclarations(consumerDir, packageName) { " Tunelet,", " TuneletAudioViews,", " type ControlActivity,", + " type ControlEvent,", + " type ParameterControl,", " type ProcessorConfig,", " type ResynthesisConfig,", " type SyncInitInput as RootSyncInitInput,", @@ -732,6 +741,7 @@ function verifyTypeDeclarations(consumerDir, packageName) { " initSync as wasmInitSync,", " type InitInput,", " type InitOutput,", + " type ParameterControl as WasmParameterControl,", " type SyncInitInput,", `} from ${wasmLiteral};`, "", @@ -816,7 +826,15 @@ function verifyTypeDeclarations(consumerDir, packageName) { " processor.processMono(input, [", ' { offset: 0, event: { type: "resynthesis", value: resynthesisUpdate } },', " ]);", - " processor.process(input, left, right);", + ' const dryMixParameter: ParameterControl & WasmParameterControl = { type: "dryMix", value: 0.25 };', + ' const humanizeParameter: ParameterControl & WasmParameterControl = { type: "humanize", value: 0.5 };', + ' const flexTuneParameter: ParameterControl & WasmParameterControl = { type: "flexTune", value: 0.25 };', + ' const parameterEvent: ControlEvent = { type: "parameter", value: dryMixParameter };', + " processor.process(input, left, right, [", + " { offset: 0, event: parameterEvent },", + ' { offset: 0, event: { type: "parameter", value: humanizeParameter } },', + ' { offset: 0, event: { type: "parameter", value: flexTuneParameter } },', + " ]);", " processor.beginDrain();", " const drained: number = processor.drain(left, right);", " const drainedMono: number = processor.drainMono(input);", @@ -826,6 +844,7 @@ function verifyTypeDeclarations(consumerDir, packageName) { " processor.processF32(inputF32, leftF32, rightF32);", " processor.processF32(inputF32, leftF32, rightF32, [", ' { offset: 0, event: { type: "outputGain", value: 1 } },', + " { offset: 0, event: parameterEvent },", " ]);", " processor.processMonoF32(inputF32);", " processor.beginDrain();", diff --git a/src/effects/punch.rs b/src/effects/punch.rs index e5ed4f9..52b2777 100644 --- a/src/effects/punch.rs +++ b/src/effects/punch.rs @@ -90,19 +90,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 counts. rate: SampleRate, + /// The validated controls that set the quantized coefficients. + 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 +156,25 @@ 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 fast_decay = Q30::from_f64(envelope_decay(FAST_RELEASE_MS, rate.hz() as f64, 1)); let drive_decay = Q30::from_f64(envelope_decay(DRIVE_SMOOTH_MS, rate.hz() as f64, 1)); 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, attack_decay: Q30::ZERO, drive_decay, gain: Q28::ONE, ceiling_gain: Q28::ONE, drive: BASE_DRIVE, }; - result.set_config(config); + result.configure_all(); result.reset(); result } @@ -171,21 +195,89 @@ 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. + /// Quantizes a per-sample decay half-life in milliseconds. + fn decay(&self, milliseconds: f64) -> Q30 { + Q30::from_f64(envelope_decay(milliseconds, self.rate.hz() as f64, 1)) + } + /// 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 = Q28::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 = + Q28::from_f64(db_to_gain(self.config.ceiling_db as f64)).max(Q28::from_bits(1)); + } + /// 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 current 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| { - 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)); - self.ceiling_gain = - Q28::from_f64(db_to_gain(config.ceiling_db as f64)).max(Q28::from_bits(1)); + 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 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..335a9fa 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)] @@ -195,26 +215,95 @@ impl Reverb { wet_peak: 0, dirty: false, }; - 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); + /// 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 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.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 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 a3f9718..a1e1a3c 100644 --- a/src/effects/warm.rs +++ b/src/effects/warm.rs @@ -48,14 +48,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 Q28 peak envelope of the input. @@ -82,6 +89,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: Q28::ZERO, compression: Q22::ONE, @@ -91,7 +99,7 @@ impl Warm { input_threshold: Q28::from_f64(db_to_gain(-30.0)), output_headroom: Q22::from_f64(db_to_gain(30.0)), }; - result.set_config(config); + result.configure_drive_db(); result } /// Returns the Q22 normalization gain as f32. The stage state does not @@ -99,11 +107,28 @@ impl Warm { pub(crate) fn normalization_gain(&self) -> f32 { (self.compression.to_bits() as f64 / f64::from(1u32 << 22)) 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 = Q24::from_f64(db_to_gain(self.config.drive_db as f64)); + self.output_gain = Q28::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 = Q24::from_f64(db_to_gain(config.drive_db as f64)); - self.output_gain = Q28::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 envelope and the normalization, /// and keeps the coefficients. diff --git a/src/events.rs b/src/events.rs index 0cc1900..ef07dee 100644 --- a/src/events.rs +++ b/src/events.rs @@ -2,21 +2,210 @@ 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 [`crate::CorrectionConfig::humanize`] + /// (`resynthesis.correction.humanize`), 0..=1. + Humanize(f32), + /// Sets [`crate::CorrectionConfig::flex_tune`] + /// (`resynthesis.correction.flex_tune`), 0..=1. + FlexTune(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::Humanize(value) => resynthesis::validate_humanize(value), + Self::FlexTune(value) => resynthesis::validate_flex_tune(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), + } + } + + /// Validates the scalar parameter and writes it into `config`. + pub(crate) fn apply_to(self, config: &mut ProcessorConfig) -> Result<(), Error> { + self.validate()?; + match self { + Self::PunchGainDb(value) => config.punch.gain_db = value, + Self::PunchImpact(value) => config.punch.impact = value, + Self::PunchCeilingDb(value) => config.punch.ceiling_db = value, + Self::PunchAttackMs(value) => config.punch.attack_ms = value, + Self::WarmDriveDb(value) => config.warm.drive_db = value, + Self::PitchThreshold(value) => config.resynthesis.pitch.threshold = value, + Self::RetuneMs(value) => config.resynthesis.correction.retune_ms = value, + Self::Humanize(value) => config.resynthesis.correction.humanize = value, + Self::FlexTune(value) => config.resynthesis.correction.flex_tune = value, + Self::PitchRatio(value) => config.resynthesis.pitch_ratio = value, + Self::FormantWidth(value) => config.resynthesis.formant.width = value, + Self::FormantStretch(value) => config.resynthesis.formant.stretch = value, + Self::FormantAspirationMix(value) => config.resynthesis.formant.aspiration_mix = value, + Self::FormantAspirationCutoffHz(value) => { + config.resynthesis.formant.aspiration_cutoff_hz = value; + } + Self::ChoirVoices(value) => config.resynthesis.choir_voices = value, + Self::ChoirDetune(value) => config.resynthesis.choir_detune = value, + Self::ChoirDelay(value) => config.resynthesis.choir_delay = value, + Self::ChoirSpreadPercent(value) => config.resynthesis.choir_spread_percent = value, + Self::HarmonyRegisterPercent(value) => { + config.resynthesis.harmony.register_percent = value; + } + Self::HarmonyVoicingSpreadPercent(value) => { + config.resynthesis.harmony.voicing_spread_percent = value; + } + Self::HarmonyPortamentoMs(value) => { + config.resynthesis.harmony.portamento_ms = value; + } + Self::HarmonyVoices(value) => config.resynthesis.harmony.voices = value, + Self::HarmonyGain(value) => config.resynthesis.harmony_gain = value, + Self::HarmonicModulation(value) => { + config.resynthesis.harmonic_modulation = value; + } + Self::DryMix(value) => config.resynthesis.dry_mix = value, + Self::ReverbMix(value) => config.reverb.mix = value, + Self::ReverbDiffusion(value) => config.reverb.diffusion = value, + Self::ReverbDecay(value) => config.reverb.decay = value, + Self::ReverbBrightnessHz(value) => config.reverb.brightness_hz = value, + } + Ok(()) + } +} + /// 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)] +#[non_exhaustive] #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), derive(serde::Serialize, serde::Deserialize, tsify::Tsify), @@ -40,6 +229,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. /// @@ -69,10 +264,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(), @@ -82,6 +277,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(()), } @@ -141,7 +337,11 @@ impl<'a> ValidatedEvents<'a> { /// first invalid event. The offset bounds have priority over the order. /// The order has priority over the payload validation. The function gives /// no tokens unless the full slice passes. - pub(crate) fn new(events: &'a [TimedEvent], frames: usize) -> Result { + pub(crate) fn new( + events: &'a [TimedEvent], + frames: usize, + mut config: ProcessorConfig, + ) -> Result { let mut previous = 0; for (index, event) in events.iter().enumerate() { let problem = if event.offset >= frames { @@ -149,7 +349,7 @@ impl<'a> ValidatedEvents<'a> { } else if event.offset < previous { Some(EventProblem::OffsetDecreasing) } else { - match event.event.validate() { + match validate_in_sequence(event.event, &mut config) { Ok(()) => None, Err(Error::InvalidConfig { field, problem }) => { Some(EventProblem::Config { field, problem }) @@ -180,3 +380,47 @@ impl<'a> ValidatedEvents<'a> { Some(ValidatedEvent(event.event)) } } + +/// Validates one event and advances the stack configuration copy. +fn validate_in_sequence(event: ControlEvent, config: &mut ProcessorConfig) -> Result<(), Error> { + match event { + ControlEvent::Configure(value) => { + value.validate()?; + *config = value; + Ok(()) + } + ControlEvent::Resynthesis(value) => { + value.validate()?; + config.resynthesis = value; + Ok(()) + } + ControlEvent::Punch(value) => { + value.validate()?; + config.punch = value; + Ok(()) + } + ControlEvent::Warm(value) => { + value.validate()?; + config.warm = value; + Ok(()) + } + ControlEvent::Alien(value) => { + value.validate()?; + config.alien = value; + Ok(()) + } + ControlEvent::Reverb(value) => { + value.validate()?; + config.reverb = value; + Ok(()) + } + ControlEvent::OutputGain(gain) => { + validate_output_gain(gain)?; + config.output_gain = gain; + Ok(()) + } + ControlEvent::Parameter(parameter) => parameter.apply_to(config), + ControlEvent::Midi(midi) | ControlEvent::CorrectionMidi(midi) => midi.validate(), + ControlEvent::Reset => Ok(()), + } +} diff --git a/src/formant.rs b/src/formant.rs index 5173b41..b4ea383 100644 --- a/src/formant.rs +++ b/src/formant.rs @@ -97,15 +97,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 in each analysis step. The analysis output has a /// delay of this number of frames. pub(crate) const ANALYSIS_FRAMES: usize = 441; @@ -291,6 +319,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, @@ -354,38 +384,116 @@ 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.configure_all(); 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. /// @@ -393,6 +501,7 @@ impl Formant { /// the correlation smoothing again. The other banks stay allocated. The /// stage clears each bank when it uses that bank again. pub(crate) fn reset(&mut self) { + self.aspiration_muted = false; if !self.dirty { return; } @@ -739,11 +848,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 9d869e9..f2adfe3 100644 --- a/src/harmony.rs +++ b/src/harmony.rs @@ -377,27 +377,75 @@ impl HarmonyConfig { /// and the problem. For an array control, the error identifies the array /// field, not the index of an element. pub fn validate(self) -> Result<(), Error> { - for interval in self.chromatic_intervals { - let field = "resynthesis.harmony.chromatic_intervals"; - check_count(field, i64::from(interval), -24, 24)?; - } - for interval in self.diatonic_intervals { - 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_chromatic_intervals(self.chromatic_intervals)?; + validate_diatonic_intervals(self.diatonic_intervals)?; + 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 four fixed semitone offsets of harmony. +pub(crate) fn validate_chromatic_intervals( + chromatic_intervals: [i8; HARMONY_VOICES], +) -> Result<(), Error> { + for interval in chromatic_intervals { + let field = "resynthesis.harmony.chromatic_intervals"; + check_count(field, i64::from(interval), -24, 24)?; } + Ok(()) +} + +/// Checks the four offsets in scale steps of harmony. +pub(crate) fn validate_diatonic_intervals( + diatonic_intervals: [i8; HARMONY_VOICES], +) -> Result<(), Error> { + for interval in diatonic_intervals { + let field = "resynthesis.harmony.diatonic_intervals"; + check_count(field, i64::from(interval), -14, 14)?; + } + Ok(()) +} + +/// 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 @@ -537,10 +585,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 + /// portamento 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 171bca7..a5041ef 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -140,7 +140,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 757ec46..71bbbc0 100644 --- a/src/pitch/tracker.rs +++ b/src/pitch/tracker.rs @@ -141,7 +141,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 c728916..7d7ba1c 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -8,7 +8,10 @@ use crate::events::{ValidatedEvent, ValidatedEvents}; use crate::numeric::rng::RandomStream; use crate::numeric::NumericContext; use crate::resynthesis::{self, Resynthesis}; -use crate::{ControlActivity, ControlEvent, Error, PrepareConfig, ProcessorConfig, TimedEvent}; +use crate::{ + ControlActivity, ControlEvent, Error, ParameterControl, PrepareConfig, ProcessorConfig, + TimedEvent, +}; /// Selects the output channel layout for the downmix and the peak meters. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -777,7 +780,7 @@ impl Processor { events: &'a [TimedEvent], ) -> Result, Error> { self.check_block(frames)?; - ValidatedEvents::new(events, frames) + ValidatedEvents::new(events, frames, self.config) } /// Enforces the prepared block limit for each call. @@ -793,33 +796,171 @@ 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::Configure(value) => self.apply_config(value), + ControlEvent::Resynthesis(value) => { + let mut config = self.config; + config.resynthesis = value; + self.apply_config(config); } - ControlEvent::CorrectionMidi(event) => { - self.resynthesis.apply_correction_midi(event); - return; + ControlEvent::Punch(value) => { + let mut config = self.config; + config.punch = value; + self.apply_config(config); } - ControlEvent::Reset => { - self.reset(); - return; + 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::Humanize(value) => { + self.config.resynthesis.correction.humanize = value; + self.resynthesis.set_humanize(value); + } + ParameterControl::FlexTune(value) => { + self.config.resynthesis.correction.flex_tune = value; + self.resynthesis.set_flex_tune(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 the peak meters. @@ -884,9 +1025,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, @@ -895,19 +1036,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..f0e844f 100644 --- a/src/resynthesis.rs +++ b/src/resynthesis.rs @@ -171,17 +171,27 @@ impl CorrectionConfig { /// Returns [`Error::InvalidConfig`], with the dotted path of the field and /// the problem, if a field is not valid. pub fn validate(self) -> Result<(), Error> { - check_range( - "resynthesis.correction.retune_ms", - self.retune_ms, - 0.0, - 400.0, - )?; - check_range("resynthesis.correction.humanize", self.humanize, 0.0, 1.0)?; - check_range("resynthesis.correction.flex_tune", self.flex_tune, 0.0, 1.0) + validate_retune_ms(self.retune_ms)?; + validate_humanize(self.humanize)?; + validate_flex_tune(self.flex_tune) } } +/// 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) +} + +/// Checks the range of the relaxation on sustained notes. +pub(crate) fn validate_humanize(humanize: f32) -> Result<(), Error> { + check_range("resynthesis.correction.humanize", humanize, 0.0, 1.0) +} + +/// Checks the range of the outer soft-zone width of each target bin. +pub(crate) fn validate_flex_tune(flex_tune: f32) -> Result<(), Error> { + check_range("resynthesis.correction.flex_tune", flex_tune, 0.0, 1.0) +} + /// The controls for pitch correction, pitch shift, voice arrangement and /// formants. /// @@ -337,24 +347,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 linear gain of the harmony voices. +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`. /// @@ -616,25 +669,32 @@ impl Resynthesis { drift_amount: Q14::ZERO, previous_output: [Q14::ZERO; 2], }; - result.configure_coefficients(); + result.configure_all(); result.configure_shift_filters(); result.create_delays(); result.old_position = result.positions[0]; result } - /// Quantizes the controls and calculates the decay coefficients and the - /// voice pan gains again. - /// - /// 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. - fn configure_coefficients(&mut self) { - const Q20_SCALE: f64 = (1_u32 << 20) as f64; + /// 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 and humanize half-life coefficients + /// unconditionally. + fn configure_correction_decay(&mut self) { + const Q20_SCALE: f64 = (1_u32 << 20) as f64; self.correction_decay = if self.config.correction.retune_ms == 0.0 { Q14::ZERO } else { @@ -659,15 +719,28 @@ 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 of each target bin unconditionally. + 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)) }; + } + + /// 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 = @@ -680,6 +753,14 @@ impl Resynthesis { self.pan[voice] = [Q14::ONE; 2]; } } + } + + /// Quantizes the harmony gain and calculates the stereo pan gains for the + /// harmony voices unconditionally. + /// + /// 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() @@ -694,6 +775,21 @@ 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_flex_tune(); + self.configure_choir_drift(); + self.configure_choir_pan(); + self.configure_harmony_gain(); + } + /// Prepares two low-pass sections if the global shift is upward. If not, /// sets coefficients of 1.0 and zero. /// @@ -734,9 +830,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.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 { @@ -746,7 +848,16 @@ impl Resynthesis { } else if config.correction.humanize == 0.0 { self.dwell = Q14::ZERO; } + if old.correction.retune_ms != config.correction.retune_ms + || old.correction.humanize != config.correction.humanize + { + self.configure_correction_decay(); + } + 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 +870,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_gain(); + } + 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. @@ -767,6 +894,191 @@ 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 and humanize decays. + 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 relaxation on sustained notes. If the value is zero, clears + /// the dwell progress. If the value changed, updates the humanize decay. + pub(crate) fn set_humanize(&mut self, humanize: f32) { + let changed = self.config.correction.humanize != humanize; + self.config.correction.humanize = humanize; + if humanize == 0.0 { + self.dwell = Q14::ZERO; + } + if changed { + self.configure_correction_decay(); + } + } + + /// Stores the outer soft-zone width of each target bin. If the value + /// changed, quantizes it again. + pub(crate) fn set_flex_tune(&mut self, flex_tune: f32) { + let changed = self.config.correction.flex_tune != flex_tune; + self.config.correction.flex_tune = flex_tune; + if changed { + self.configure_flex_tune(); + } + } + + /// Stores the global pitch multiplier. If the value changed, updates the + /// shift and the anti-alias filters, and restarts target selection. + 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(); + self.scale_initialized = false; + self.dwell = Q14::ZERO; + } + } + + /// 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 gain. If the value changed, updates the mono gain and + /// the stereo 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_gain(); + } + } + + /// 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..=127, loads the configured correction /// notes again and resets the audio state. /// diff --git a/src/wasm.rs b/src/wasm.rs index 6bb06fa..49880f6 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -25,10 +25,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. It also keeps an event buffer and uses that capacity again @@ -51,8 +52,8 @@ use crate::events::ValidatedEvents; use crate::processor::EnvelopeKey; use crate::{ - ControlActivity, ControlEvent, Error, Feedback, MidiEvent, PrepareConfig, Processor, - ProcessorConfig, SampleRate, Telemetry, TimedEvent, + ControlActivity, ControlEvent, Error, Feedback, MidiEvent, ParameterControl, PrepareConfig, + Processor, ProcessorConfig, SampleRate, Telemetry, TimedEvent, }; use js_sys::{Array, Float32Array, Int16Array, Reflect}; use serde::{Deserialize, Serialize}; @@ -322,7 +323,9 @@ impl WasmProcessor { Error::check_length(frames, right.length() as usize)?; self.processor.check_block(frames)?; let events = match events { - Some(events) => decode_events(&mut self.events, events, frames)?, + Some(events) => { + decode_events(&mut self.events, events, frames, self.processor.config())? + } None => &[], }; input.copy_to(&mut self.input[..frames]); @@ -356,7 +359,9 @@ impl WasmProcessor { let frames = audio.length() as usize; self.processor.check_block(frames)?; let events = match events { - Some(events) => decode_events(&mut self.events, events, frames)?, + Some(events) => { + decode_events(&mut self.events, events, frames, self.processor.config())? + } None => &[], }; audio.copy_to(&mut self.input[..frames]); @@ -395,7 +400,9 @@ impl WasmProcessor { Error::check_length(frames, right.length() as usize)?; self.processor.check_block(frames)?; let events = match events { - Some(events) => decode_events(&mut self.events, events, frames)?, + Some(events) => { + decode_events(&mut self.events, events, frames, self.processor.config())? + } None => &[], }; input.copy_to(&mut self.input_f32[..frames]); @@ -430,7 +437,9 @@ impl WasmProcessor { let frames = audio.length() as usize; self.processor.check_block(frames)?; let events = match events { - Some(events) => decode_events(&mut self.events, events, frames)?, + Some(events) => { + decode_events(&mut self.events, events, frames, self.processor.config())? + } None => &[], }; audio.copy_to(&mut self.input_f32[..frames]); @@ -461,7 +470,9 @@ impl WasmProcessor { ) -> Result<(), JsError> { let frames = self.check_frames(frames)?; let events = match events { - Some(events) => decode_events(&mut self.events, events, frames)?, + Some(events) => { + decode_events(&mut self.events, events, frames, self.processor.config())? + } None => &[], }; self.processor.process_planar_f32( @@ -493,7 +504,9 @@ impl WasmProcessor { ) -> Result<(), JsError> { let frames = self.check_frames(frames)?; let events = match events { - Some(events) => decode_events(&mut self.events, events, frames)?, + Some(events) => { + decode_events(&mut self.events, events, frames, self.processor.config())? + } None => &[], }; self.processor @@ -812,6 +825,24 @@ impl WasmProcessor { } } +/// One cached `ParameterControl` discriminant and its constructor. +struct ParameterKey { + name: JsValue, + field: &'static str, + make: fn(T) -> ParameterControl, +} + +impl ParameterKey { + /// Allocates one cached discriminant key and stores its constructor. + fn new(name: &'static str, field: &'static str, make: fn(T) -> ParameterControl) -> Self { + Self { + name: JsValue::from_str(name), + field, + make, + } + } +} + /// The cached property keys and variant names for JavaScript events. struct EventKeys { offset: JsValue, @@ -824,6 +855,7 @@ struct EventKeys { midi: JsValue, correction_midi: JsValue, output_gain: JsValue, + parameter: JsValue, reset: JsValue, configure: JsValue, resynthesis: JsValue, @@ -834,6 +866,8 @@ struct EventKeys { note_on: JsValue, note_off: JsValue, all_notes_off: JsValue, + f32_parameters: [ParameterKey; 27], + u8_parameters: [ParameterKey; 2], } impl EventKeys { @@ -850,6 +884,7 @@ impl EventKeys { midi: JsValue::from_str("midi"), correction_midi: JsValue::from_str("correctionMidi"), output_gain: JsValue::from_str("outputGain"), + parameter: JsValue::from_str("parameter"), reset: JsValue::from_str("reset"), configure: JsValue::from_str("configure"), resynthesis: JsValue::from_str("resynthesis"), @@ -860,6 +895,135 @@ impl EventKeys { note_on: JsValue::from_str("noteOn"), note_off: JsValue::from_str("noteOff"), all_notes_off: JsValue::from_str("allNotesOff"), + f32_parameters: [ + ParameterKey::new( + "punchGainDb", + "punchGainDb value", + ParameterControl::PunchGainDb, + ), + ParameterKey::new( + "punchImpact", + "punchImpact value", + ParameterControl::PunchImpact, + ), + ParameterKey::new( + "punchCeilingDb", + "punchCeilingDb value", + ParameterControl::PunchCeilingDb, + ), + ParameterKey::new( + "punchAttackMs", + "punchAttackMs value", + ParameterControl::PunchAttackMs, + ), + ParameterKey::new( + "warmDriveDb", + "warmDriveDb value", + ParameterControl::WarmDriveDb, + ), + ParameterKey::new( + "pitchThreshold", + "pitchThreshold value", + ParameterControl::PitchThreshold, + ), + ParameterKey::new("retuneMs", "retuneMs value", ParameterControl::RetuneMs), + ParameterKey::new("humanize", "humanize value", ParameterControl::Humanize), + ParameterKey::new("flexTune", "flexTune value", ParameterControl::FlexTune), + ParameterKey::new( + "pitchRatio", + "pitchRatio value", + ParameterControl::PitchRatio, + ), + ParameterKey::new( + "formantWidth", + "formantWidth value", + ParameterControl::FormantWidth, + ), + ParameterKey::new( + "formantStretch", + "formantStretch value", + ParameterControl::FormantStretch, + ), + ParameterKey::new( + "formantAspirationMix", + "formantAspirationMix value", + ParameterControl::FormantAspirationMix, + ), + ParameterKey::new( + "formantAspirationCutoffHz", + "formantAspirationCutoffHz value", + ParameterControl::FormantAspirationCutoffHz, + ), + ParameterKey::new( + "choirDetune", + "choirDetune value", + ParameterControl::ChoirDetune, + ), + ParameterKey::new( + "choirDelay", + "choirDelay value", + ParameterControl::ChoirDelay, + ), + ParameterKey::new( + "choirSpreadPercent", + "choirSpreadPercent value", + ParameterControl::ChoirSpreadPercent, + ), + ParameterKey::new( + "harmonyRegisterPercent", + "harmonyRegisterPercent value", + ParameterControl::HarmonyRegisterPercent, + ), + ParameterKey::new( + "harmonyVoicingSpreadPercent", + "harmonyVoicingSpreadPercent value", + ParameterControl::HarmonyVoicingSpreadPercent, + ), + ParameterKey::new( + "harmonyPortamentoMs", + "harmonyPortamentoMs value", + ParameterControl::HarmonyPortamentoMs, + ), + ParameterKey::new( + "harmonyGain", + "harmonyGain value", + ParameterControl::HarmonyGain, + ), + ParameterKey::new( + "harmonicModulation", + "harmonicModulation value", + ParameterControl::HarmonicModulation, + ), + ParameterKey::new("dryMix", "dryMix value", ParameterControl::DryMix), + ParameterKey::new("reverbMix", "reverbMix value", ParameterControl::ReverbMix), + ParameterKey::new( + "reverbDiffusion", + "reverbDiffusion value", + ParameterControl::ReverbDiffusion, + ), + ParameterKey::new( + "reverbDecay", + "reverbDecay value", + ParameterControl::ReverbDecay, + ), + ParameterKey::new( + "reverbBrightnessHz", + "reverbBrightnessHz value", + ParameterControl::ReverbBrightnessHz, + ), + ], + u8_parameters: [ + ParameterKey::new( + "choirVoices", + "choirVoices value", + ParameterControl::ChoirVoices, + ), + ParameterKey::new( + "harmonyVoices", + "harmonyVoices value", + ParameterControl::HarmonyVoices, + ), + ], } } } @@ -877,6 +1041,7 @@ fn decode_events( buffer: &mut Vec, events: Ts, frames: usize, + config: ProcessorConfig, ) -> Result<&[TimedEvent], JsError> { let value = JsValue::from(events); let Some(array) = value.dyn_ref::() else { @@ -893,7 +1058,7 @@ fn decode_events( Ok(()) })?; } - ValidatedEvents::new(buffer, frames)?; + ValidatedEvents::new(buffer, frames, config)?; Ok(buffer) } @@ -917,10 +1082,15 @@ fn decode_control_event(event: &JsValue, keys: &EventKeys) -> Result Result Result { + let kind = get_property(value, &keys.kind)?; + for entry in &keys.f32_parameters { + if kind == entry.name { + let raw = get_property(value, &keys.value)?; + return Ok((entry.make)(decode_f32(&raw, entry.field)?)); + } + } + for entry in &keys.u8_parameters { + if kind == entry.name { + let raw = get_property(value, &keys.value)?; + return Ok((entry.make)(decode_u8(&raw, entry.field)?)); + } + } + Err(JsError::new("parameter event type is absent or unknown")) +} + /// Reads a property from a JavaScript object and converts any exception. fn get_property(target: &JsValue, key: &JsValue) -> Result { Reflect::get(target, key).map_err(|err| match err.dyn_ref::() { @@ -1000,6 +1191,14 @@ fn decode_offset(value: &JsValue) -> Result { Ok(number as usize) } +/// Converts a JavaScript number into an `f32` scalar. +fn decode_f32(value: &JsValue, field: &str) -> Result { + let Some(number) = value.as_f64() else { + return Err(JsError::new(&format!("{field} must be a number"))); + }; + Ok(number as f32) +} + /// Converts a JavaScript number into a `u8` integer. fn decode_u8(value: &JsValue, field: &str) -> Result { let Some(number) = value.as_f64() else {