diff --git a/README.md b/README.md index a06715f..65ed463 100644 --- a/README.md +++ b/README.md @@ -259,10 +259,10 @@ 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 scalar -field without a stage copy, use `ControlEvent::Parameter` with a -`ParameterControl` variant. For fields that are not scalar parameters, start -from `processor.config()`. +events. A stage event replaces all settings of that stage. Use +`ControlEvent::Parameter` with `ParameterControl` to change one scalar field. +Use `ControlEvent::Patch` to change selected fields, or start from +`processor.config()`. Harmony MIDI uses `ControlEvent::Midi`. MIDI for the correction keyboard uses `ControlEvent::CorrectionMidi`. For example, these events change the resynthesis @@ -498,7 +498,7 @@ page that opens the JavaScript. | Cached `Float32` memory views | `new TuneletAudioViews(memory, processor)` | | Zero-copy `Float32` stereo | `processF32InPlace(frames, events?)` | | Zero-copy `Float32` mono | `processMonoF32InPlace(frames, events?)` | -| Configuration | `config()`, `setConfig(config)`, `defaultConfig()` | +| Configuration | `config()`, `setConfig(config)`, `patchConfig(patch)`, `defaultConfig()` | | Control activity | `controlActivity()` | | Information about the preparation | `sampleRate`, `maxBlockFrames`, `latencyFrames` | | Feedback | `feedback()`, `takeFeedback()` | @@ -557,8 +557,8 @@ and `views.right`. These lifetime rules apply to `Float32` views: -- A new `Tunelet`, `setConfig`, `events`, `controlActivity`, feedback, - telemetry or `formantEnvelope` can grow Wasm memory and detach +- A new `Tunelet`, `setConfig`, `patchConfig`, `events`, `controlActivity`, + feedback, telemetry or `formantEnvelope` can grow Wasm memory and detach `memory.buffer`. - Read `views.input` before each input write so `TuneletAudioViews` checks `memory.buffer` and refreshes detached views. @@ -585,6 +585,13 @@ default. `resynthesis.correction.humanize` and properties. The generated declarations contain the parameter documentation from the Rust types. +To change selected fields without a full configuration copy, give a +`ProcessorConfigPatch` object to `patchConfig(patch)`. All fields in +`ProcessorConfigPatch` and the stage patches are optional. Absent or `undefined` +fields keep their active values on the processor. `patchConfig()` validates the +supplied fields and the pitch bounds before any state changes. Each successful +call cancels an active drain, also for an empty `{}` patch. + `resynthesis.randomSeed` and the `processedFrames` field of feedback and telemetry use `bigint`. Frame offsets, block lengths and latency use `number`. @@ -599,6 +606,13 @@ example, this event changes the final gain before the first frame: { offset: 0, event: { type: "outputGain", value: 0.5 } } ``` +To merge selected configuration fields before a frame, use +`ControlEvent::Patch` (`type: "patch"`): + +```ts +{ offset: 0, event: { type: "patch", value: { resynthesis: { dryMix: 0.2 } } } } +``` + A scalar parameter event nests a `ParameterControl` object: ```ts @@ -655,7 +669,7 @@ allocate and grow Wasm memory: - A new `Tunelet` instance. - Configuration conversion. - Supplied events when a call gives more events than before, or when an event - converts a stage configuration. + converts a configuration or a patch. - Errors. - Control activity, feedback and telemetry. - The formant envelopes. diff --git a/scripts/normalize-jsdoc.mjs b/scripts/normalize-jsdoc.mjs index 0f6a77f..2535ed6 100644 --- a/scripts/normalize-jsdoc.mjs +++ b/scripts/normalize-jsdoc.mjs @@ -19,6 +19,8 @@ const EXACT_REPLACEMENTS = [ ["[`voice_count`](Self::voice_count)", "`voiceCount`"], ["[`alien_loop_frames`](Self::alien_loop_frames)", "`alienLoopFrames`"], ["[`crate::Processor::set_config`]", "`Tunelet.setConfig`"], + ["[`crate::Processor::patch_config`]", "`Tunelet.patchConfig`"], + ["[`crate::ControlEvent::Patch`]", '`{ type: "patch", value }`'], ["[`crate::Processor::control_activity`]", "`Tunelet.controlActivity`"], ["[`Processor::control_activity`]", "`Tunelet.controlActivity`"], ["[`ProcessorConfig::control_activity`]", "`Tunelet.controlActivity`"], @@ -80,7 +82,15 @@ const EXACT_REPLACEMENTS = [ ["[`ReverbConfig::brightness_hz`]", "`ReverbConfig.brightnessHz`"], ["[`crate::AlienConfig::loop_frames`]", "`AlienConfig.loopFrames`"], ["[`crate::PitchConfig`]", "`PitchConfig`"], + ["[`PitchConfig`]", "`PitchConfig`"], ["[`ProcessorConfig`]", "`ProcessorConfig`"], + ["[`PunchConfig`]", "`PunchConfig`"], + ["[`WarmConfig`]", "`WarmConfig`"], + ["[`ResynthesisConfig`]", "`ResynthesisConfig`"], + ["[`CorrectionConfig`]", "`CorrectionConfig`"], + ["[`FormantConfig`]", "`FormantConfig`"], + ["[`AlienConfig`]", "`AlienConfig`"], + ["[`ReverbConfig`]", "`ReverbConfig`"], ["[`ControlActivity`]", "`ControlActivity`"], ["[`TimedEvent`]", "`TimedEvent`"], ["[`HarmonyScale`]", "`HarmonyScale`"], @@ -90,6 +100,7 @@ const EXACT_REPLACEMENTS = [ "[`ControlEvent::Parameter`]", '`{ type: "parameter", value }` in `ControlEvent`', ], + ["[`Self::Patch`]", '`{ type: "patch", value }`'], ["[`Self::Parameter`]", '`{ type: "parameter", value }`'], ["[`Self::I`]", '`"i"`'], ["[`Self::Echo`]", '`"echo"`'], @@ -102,6 +113,7 @@ const EXACT_REPLACEMENTS = [ ["[`HarmonySource::ChordByDegree`]", '`"chordByDegree"`'], ["[`MultiVoiceMode::Choir`]", '`"choir"`'], ["`None`", "`undefined`"], + ["`0..=u64::MAX`", "from `0n` to `2n ** 64n - 1n` (inclusive)"], ["`u64::MAX`", "`2n ** 64n - 1n`"], ["`0x1234_abcd`", "`0x1234abcdn`"], ["`max_frequency_hz`", "`maxFrequencyHz`"], @@ -164,6 +176,10 @@ const PROSE_REPLACEMENTS = [ /Change\s+a\s+copy,\s+then\s+apply\s+it\s+with\s+\[`crate::Processor::set_config`\]\s+or\s+\[`crate::ControlEvent::Configure`\]\./g, 'Change a copy, then apply it with `Tunelet.setConfig` or\n`{ type: "configure", value }` in `ControlEvent`.', ], + [ + /Apply\s+a\s+patch\s+with\s+\[`crate::Processor::patch_config`\]\s+or\s+\[`crate::ControlEvent::Patch`\]\./g, + 'Apply a patch with `Tunelet.patchConfig` or\n`{ type: "patch", value }` in `ControlEvent`.', + ], [ /The\s+MIDI\s+sources\s+use\s+\[`crate::ControlEvent::Midi`\]\./g, 'The MIDI sources use\n`{ type: "midi", value }` in `ControlEvent`.', diff --git a/scripts/verify-pack.mjs b/scripts/verify-pack.mjs index 66d5b7a..ccd2a3a 100644 --- a/scripts/verify-pack.mjs +++ b/scripts/verify-pack.mjs @@ -370,9 +370,59 @@ function verifyRuntimeImport(consumerDir, packageName) { " assert.equal(processor.config().resynthesis.correction.flexTune, 0);", " assert.equal(processor.config().resynthesis.harmony.voices, 4);", "", + " processor.patchConfig({", + " outputGain: 0.9,", + " resynthesis: {", + " correction: { humanize: 0.4, flexTune: 0.3 },", + " harmony: { chromaticIntervals: [3, 7, 10, 12] },", + " randomSeed: 7n,", + " },", + " });", + " assert.equal(Math.fround(processor.config().outputGain), Math.fround(0.9));", + " assert.equal(Math.fround(processor.config().resynthesis.correction.humanize), Math.fround(0.4));", + " assert.equal(Math.fround(processor.config().resynthesis.correction.flexTune), Math.fround(0.3));", + " assert.deepEqual(processor.config().resynthesis.harmony.chromaticIntervals, [3, 7, 10, 12]);", + " assert.equal(processor.config().resynthesis.randomSeed, 7n);", + " processor.patchConfig({", + " punch: undefined,", + " warm: { enabled: undefined, driveDb: undefined },", + " resynthesis: {", + " pitch: undefined,", + " correction: {", + " enabled: undefined,", + " notes: undefined,", + " retuneMs: undefined,", + " humanize: undefined,", + " flexTune: undefined,", + " },", + " formant: undefined,", + " harmony: {", + " chromaticIntervals: undefined,", + " diatonicIntervals: undefined,", + " voices: undefined,", + " },", + " randomSeed: undefined,", + " },", + " alien: undefined,", + " reverb: undefined,", + " outputGain: undefined,", + " });", + " assert.equal(Math.fround(processor.config().outputGain), Math.fround(0.9));", + " assert.equal(Math.fround(processor.config().resynthesis.correction.humanize), Math.fround(0.4));", + " assert.equal(Math.fround(processor.config().resynthesis.correction.flexTune), Math.fround(0.3));", + " assert.deepEqual(processor.config().resynthesis.harmony.chromaticIntervals, [3, 7, 10, 12]);", + " assert.equal(processor.config().resynthesis.randomSeed, 7n);", + " assert.equal(processor.controlActivity().choirVoices, true);", + ' processor.patchConfig({ resynthesis: { mode: "harmony" } });', + " assert.equal(processor.controlActivity().choirVoices, false);", + "", " const input = new Int16Array(128);", " const left = new Int16Array(128);", " const right = new Int16Array(128);", + ' processor.process(input, left, right, [{ offset: 0, event: { type: "patch", value: { outputGain: undefined, resynthesis: { dryMix: 0.2, randomSeed: undefined } } } }]);', + " assert.equal(Math.fround(processor.config().outputGain), Math.fround(0.9));", + " assert.equal(Math.fround(processor.config().resynthesis.dryMix), Math.fround(0.2));", + " assert.equal(processor.config().resynthesis.randomSeed, 7n);", ' 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 } } },', @@ -736,19 +786,30 @@ function verifyTypeDeclarations(consumerDir, packageName) { " loadTunelet as namedLoadTunelet,", " Tunelet,", " TuneletAudioViews,", + " type AlienConfigPatch,", " type ControlActivity,", " type ControlEvent,", + " type CorrectionConfigPatch,", + " type FormantConfigPatch,", + " type HarmonyConfigPatch,", " type ParameterControl,", + " type PitchConfigPatch,", " type ProcessorConfig,", + " type ProcessorConfigPatch,", + " type PunchConfigPatch,", " type ResynthesisConfig,", + " type ResynthesisConfigPatch,", + " type ReverbConfigPatch,", " type SyncInitInput as RootSyncInitInput,", " type Telemetry,", + " type WarmConfigPatch,", `} from ${pkgLiteral};`, "import init, {", " initSync as wasmInitSync,", " type InitInput,", " type InitOutput,", " type ParameterControl as WasmParameterControl,", + " type ProcessorConfigPatch as WasmProcessorConfigPatch,", " type SyncInitInput,", `} from ${wasmLiteral};`, "", @@ -800,6 +861,103 @@ function verifyTypeDeclarations(consumerDir, packageName) { " }", " const processor = new Tunelet(48000, 128, configWithUndefined);", " processor.setConfig(configWithUndefined);", + " const punchPatch: PunchConfigPatch = {", + " enabled: true,", + " gainDb: optionalVoices,", + " impact: undefined,", + " ceilingDb: undefined,", + " attackMs: undefined,", + " };", + " const warmPatch: WarmConfigPatch = {", + " enabled: undefined,", + " driveDb: optionalVoices ?? 2,", + " };", + " const pitchPatch: PitchConfigPatch = {", + " threshold: undefined,", + " minFrequencyHz: 80,", + " maxFrequencyHz: optionalVoices,", + " };", + " const correctionPatch: CorrectionConfigPatch = {", + " enabled: undefined,", + " notes: undefined,", + " retuneMs: 15,", + " humanize: optionalVoices,", + " flexTune: optionalVoices,", + " };", + " const formantPatch: FormantConfigPatch = {", + " enabled: undefined,", + " width: 1.1,", + " stretch: undefined,", + " aspirationMix: optionalVoices,", + " aspirationCutoffHz: undefined,", + " };", + " const harmonyPatch: HarmonyConfigPatch = {", + " source: undefined,", + " key: undefined,", + " scale: undefined,", + " chromaticIntervals: undefined,", + " diatonicIntervals: undefined,", + " chord: undefined,", + " degree: undefined,", + " inversion: undefined,", + " registerPercent: optionalVoices,", + " voicingSpreadPercent: undefined,", + " portamentoMs: undefined,", + " voices: optionalVoices,", + " };", + " const resynthesisPatch: ResynthesisConfigPatch = {", + " pitch: pitchPatch,", + " correction: correctionPatch,", + " pitchRatio: optionalVoices,", + " formant: formantPatch,", + " mode: undefined,", + " choirVoices: optionalVoices,", + " choirDetune: undefined,", + " choirDelay: undefined,", + " choirSpreadPercent: undefined,", + " stereoOutput: undefined,", + " harmony: harmonyPatch,", + " harmonyGain: undefined,", + " harmonicModulation: undefined,", + " dryMix: 0.2,", + " randomSeed: undefined,", + " };", + " const alienPatch: AlienConfigPatch = {", + " enabled: undefined,", + " loopFrames: 1000,", + " };", + " const reverbPatch: ReverbConfigPatch = {", + " enabled: undefined,", + " mode: undefined,", + " mix: 0.4,", + " diffusion: optionalVoices,", + " decay: undefined,", + " brightnessHz: undefined,", + " };", + " const patch: ProcessorConfigPatch & WasmProcessorConfigPatch = {", + " punch: punchPatch,", + " warm: warmPatch,", + " resynthesis: resynthesisPatch,", + " alien: alienPatch,", + " reverb: reverbPatch,", + " outputGain: optionalVoices,", + " };", + " const emptyUndefinedPatch: ProcessorConfigPatch & WasmProcessorConfigPatch = {", + " punch: undefined,", + " warm: undefined,", + " resynthesis: {", + " pitch: undefined,", + " correction: undefined,", + " formant: undefined,", + " harmony: undefined,", + " },", + " alien: undefined,", + " reverb: undefined,", + " outputGain: undefined,", + " };", + ' const patchEvent: ControlEvent = { type: "patch", value: patch };', + " processor.patchConfig(patch);", + " processor.patchConfig(emptyUndefinedPatch);", " const activity: ControlActivity = processor.controlActivity();", " const telemetry: Telemetry = processor.telemetry();", " const voiceSlices: [Float32Array, Float32Array] = [", @@ -843,6 +1001,7 @@ function verifyTypeDeclarations(consumerDir, packageName) { ' const flexTuneParameter: ParameterControl & WasmParameterControl = { type: "flexTune", value: 0.25 };', ' const parameterEvent: ControlEvent = { type: "parameter", value: dryMixParameter };', " processor.process(input, left, right, [", + " { offset: 0, event: patchEvent },", " { offset: 0, event: parameterEvent },", ' { offset: 0, event: { type: "parameter", value: humanizeParameter } },', ' { offset: 0, event: { type: "parameter", value: flexTuneParameter } },', @@ -857,6 +1016,7 @@ function verifyTypeDeclarations(consumerDir, packageName) { " processor.processF32(inputF32, leftF32, rightF32, [", ' { offset: 0, event: { type: "outputGain", value: 1 } },', " { offset: 0, event: parameterEvent },", + " { offset: 64, event: patchEvent },", " ]);", " processor.processMonoF32(inputF32);", " processor.beginDrain();", @@ -1176,8 +1336,8 @@ function verifyNormalizedJsDoc(consumerDir, packageName) { const throwsCount = [...dts.matchAll(/\* @throws /g)].length; assert.ok( - throwsCount >= 14, - `Expected at least 14 @throws tags, found ${throwsCount}`, + throwsCount >= 15, + `Expected at least 15 @throws tags, found ${throwsCount}`, ); const fallibleSignatures = [ @@ -1188,6 +1348,7 @@ function verifyNormalizedJsDoc(consumerDir, packageName) { ["feedback", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+feedback\(\): Feedback;/], ["formantEnvelope", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+formantEnvelope\([^)]*\): boolean;/], ["constructor", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+constructor\([^)]*\);/], + ["patchConfig", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+patchConfig\(patch: ProcessorConfigPatch\): void;/], ["processMono", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+processMono\([^)]*\): void;/], ["process", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+process\([^)]*\): void;/], ["setConfig", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+setConfig\(config: ProcessorConfig\): void;/], diff --git a/src/config.rs b/src/config.rs index 741d08c..825432b 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,14 +1,14 @@ //! Sample rates, block limits and the complete processor configuration. -use crate::effects::alien::AlienConfig; -use crate::effects::punch::PunchConfig; -use crate::effects::reverb::{ReverbConfig, ReverbMode}; -use crate::effects::warm::WarmConfig; +use crate::effects::alien::{AlienConfig, AlienConfigPatch}; +use crate::effects::punch::{PunchConfig, PunchConfigPatch}; +use crate::effects::reverb::{ReverbConfig, ReverbConfigPatch, ReverbMode}; +use crate::effects::warm::{WarmConfig, WarmConfigPatch}; use crate::error::{check_range, ConfigProblem}; use crate::harmony::HarmonySource; use crate::resynthesis::MultiVoiceMode; use crate::Error; -use crate::ResynthesisConfig; +use crate::{ResynthesisConfig, ResynthesisConfigPatch}; use std::num::NonZeroUsize; /// The sample rate of the input and the output. @@ -326,6 +326,117 @@ pub struct ControlActivity { pub reverb_brightness_hz: bool, } +/// Optional changes to [`ProcessorConfig`], in the order of the stages. +/// +/// Apply a patch with [`crate::Processor::patch_config`] or +/// [`crate::ControlEvent::Patch`]. Each `None` field keeps its active value on +/// the processor. Validation examines only the supplied stages and fields +/// before any state changes. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[non_exhaustive] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + derive(serde::Serialize, serde::Deserialize, tsify::Tsify), + serde(default, rename_all = "camelCase"), + tsify(large_number_types_as_bigints) +)] +pub struct ProcessorConfigPatch { + /// Optional changes to [`PunchConfig`]. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "PunchConfigPatch | undefined") + )] + pub punch: Option, + /// Optional changes to [`WarmConfig`]. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "WarmConfigPatch | undefined") + )] + pub warm: Option, + /// Optional changes to [`ResynthesisConfig`]. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "ResynthesisConfigPatch | undefined") + )] + pub resynthesis: Option, + /// Optional changes to [`AlienConfig`]. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "AlienConfigPatch | undefined") + )] + pub alien: Option, + /// Optional changes to [`ReverbConfig`]. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "ReverbConfigPatch | undefined") + )] + pub reverb: Option, + /// The linear gain after all effects, 0..=64. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "number | undefined") + )] + pub output_gain: Option, +} + +impl ProcessorConfigPatch { + /// Checks all supplied stages and fields in signal order. + pub(crate) fn validate(self) -> Result<(), Error> { + if let Some(punch) = self.punch { + punch.validate()?; + } + if let Some(warm) = self.warm { + warm.validate()?; + } + if let Some(resynthesis) = self.resynthesis { + resynthesis.validate()?; + } + if let Some(alien) = self.alien { + alien.validate()?; + } + if let Some(reverb) = self.reverb { + reverb.validate()?; + } + if let Some(output_gain) = self.output_gain { + validate_output_gain(output_gain)?; + } + Ok(()) + } + + /// Validates all supplied stages and fields in signal order, then writes + /// them into `config`. + pub(crate) fn apply_to(self, config: &mut ProcessorConfig) -> Result<(), Error> { + let mut next = *config; + if let Some(punch) = self.punch { + punch.apply_to(&mut next.punch)?; + } + if let Some(warm) = self.warm { + warm.apply_to(&mut next.warm)?; + } + if let Some(resynthesis) = self.resynthesis { + resynthesis.apply_to(&mut next.resynthesis)?; + } + if let Some(alien) = self.alien { + alien.apply_to(&mut next.alien)?; + } + if let Some(reverb) = self.reverb { + reverb.apply_to(&mut next.reverb)?; + } + if let Some(output_gain) = self.output_gain { + validate_output_gain(output_gain)?; + next.output_gain = output_gain; + } + *config = next; + Ok(()) + } +} + /// Checks the output gain range. /// /// `ProcessorConfig` and `ControlEvent::OutputGain` use the same range. diff --git a/src/effects/alien.rs b/src/effects/alien.rs index 271cae5..407dc89 100644 --- a/src/effects/alien.rs +++ b/src/effects/alien.rs @@ -53,7 +53,62 @@ impl AlienConfig { /// Returns the first [`Error::InvalidConfig`] with its dotted field path /// and the problem. pub fn validate(self) -> Result<(), Error> { - check_count("alien.loop_frames", i64::from(self.loop_frames), 1, 96_000) + validate_loop_frames(self.loop_frames) + } +} + +/// Checks the range of the loop length of Alien. +pub(crate) fn validate_loop_frames(loop_frames: u32) -> Result<(), Error> { + check_count("alien.loop_frames", i64::from(loop_frames), 1, 96_000) +} + +/// Optional changes to [`AlienConfig`]. +/// +/// Each `None` field keeps its active value on the processor. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[non_exhaustive] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + derive(serde::Serialize, serde::Deserialize, tsify::Tsify), + serde(default, rename_all = "camelCase") +)] +pub struct AlienConfigPatch { + /// Selects reversed playback instead of the direct input (`true` or + /// `false`). + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "boolean | undefined") + )] + pub enabled: Option, + /// The loop length in frames, 1..=96000. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "number | undefined") + )] + pub loop_frames: Option, +} + +impl AlienConfigPatch { + /// Checks all supplied fields and does not change the processor state. + pub(crate) fn validate(self) -> Result<(), Error> { + if let Some(loop_frames) = self.loop_frames { + validate_loop_frames(loop_frames)?; + } + Ok(()) + } + + /// Validates all supplied fields and writes them into `config`. + pub(crate) fn apply_to(self, config: &mut AlienConfig) -> Result<(), Error> { + self.validate()?; + if let Some(enabled) = self.enabled { + config.enabled = enabled; + } + if let Some(loop_frames) = self.loop_frames { + config.loop_frames = loop_frames; + } + Ok(()) } } diff --git a/src/effects/punch.rs b/src/effects/punch.rs index 52b2777..14914e0 100644 --- a/src/effects/punch.rs +++ b/src/effects/punch.rs @@ -117,6 +117,94 @@ pub(crate) fn validate_attack_ms(attack_ms: f32) -> Result<(), Error> { check_range("punch.attack_ms", attack_ms, 0.01, 5000.0) } +/// Optional changes to [`PunchConfig`]. +/// +/// Each `None` field keeps its active value on the processor. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[non_exhaustive] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + derive(serde::Serialize, serde::Deserialize, tsify::Tsify), + serde(default, rename_all = "camelCase") +)] +pub struct PunchConfigPatch { + /// Enables this input stage (`true` or `false`). + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "boolean | undefined") + )] + pub enabled: Option, + /// The input gain in decibels, -96..=12. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "number | undefined") + )] + pub gain_db: Option, + /// The transient emphasis without a unit, 0..=1. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "number | undefined") + )] + pub impact: Option, + /// The output ceiling of the saturation in dBFS, -96..=0. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "number | undefined") + )] + pub ceiling_db: Option, + /// The attack half-life of the peak followers in milliseconds, 0.01..=5000. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "number | undefined") + )] + pub attack_ms: Option, +} + +impl PunchConfigPatch { + /// Checks all supplied fields and does not change the processor state. + pub(crate) fn validate(self) -> Result<(), Error> { + if let Some(gain_db) = self.gain_db { + validate_gain_db(gain_db)?; + } + if let Some(impact) = self.impact { + validate_impact(impact)?; + } + if let Some(ceiling_db) = self.ceiling_db { + validate_ceiling_db(ceiling_db)?; + } + if let Some(attack_ms) = self.attack_ms { + validate_attack_ms(attack_ms)?; + } + Ok(()) + } + + /// Validates all supplied fields and writes them into `config`. + pub(crate) fn apply_to(self, config: &mut PunchConfig) -> Result<(), Error> { + self.validate()?; + if let Some(enabled) = self.enabled { + config.enabled = enabled; + } + if let Some(gain_db) = self.gain_db { + config.gain_db = gain_db; + } + if let Some(impact) = self.impact { + config.impact = impact; + } + if let Some(ceiling_db) = self.ceiling_db { + config.ceiling_db = ceiling_db; + } + if let Some(attack_ms) = self.attack_ms { + config.attack_ms = attack_ms; + } + Ok(()) + } +} + /// Two peak followers that control an arctangent saturator, with all buffers /// inline. #[derive(Debug)] diff --git a/src/effects/reverb.rs b/src/effects/reverb.rs index 335a9fa..e1f5d59 100644 --- a/src/effects/reverb.rs +++ b/src/effects/reverb.rs @@ -135,6 +135,104 @@ pub(crate) fn validate_brightness_hz(brightness_hz: f32) -> Result<(), Error> { check_range("reverb.brightness_hz", brightness_hz, 80.0, 20000.0) } +/// Optional changes to [`ReverbConfig`]. +/// +/// Each `None` field keeps its active value on the processor. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[non_exhaustive] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + derive(serde::Serialize, serde::Deserialize, tsify::Tsify), + serde(default, rename_all = "camelCase") +)] +pub struct ReverbConfigPatch { + /// Enables the selected network (`true` or `false`). + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "boolean | undefined") + )] + pub enabled: Option, + /// The topology of the delay network (`ReverbMode`). + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "ReverbMode | undefined") + )] + pub mode: Option, + /// The wet fraction, 0..=1. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "number | undefined") + )] + pub mix: Option, + /// The diffusion control without a unit, 0..=1. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "number | undefined") + )] + pub diffusion: Option, + /// The feedback control without a unit, 0..=1. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "number | undefined") + )] + pub decay: Option, + /// The low-pass cutoff in hertz for networks with damped paths, 80..=20000. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "number | undefined") + )] + pub brightness_hz: Option, +} + +impl ReverbConfigPatch { + /// Checks all supplied fields and does not change the processor state. + pub(crate) fn validate(self) -> Result<(), Error> { + if let Some(mix) = self.mix { + validate_mix(mix)?; + } + if let Some(diffusion) = self.diffusion { + validate_diffusion(diffusion)?; + } + if let Some(decay) = self.decay { + validate_decay(decay)?; + } + if let Some(brightness_hz) = self.brightness_hz { + validate_brightness_hz(brightness_hz)?; + } + Ok(()) + } + + /// Validates all supplied fields and writes them into `config`. + pub(crate) fn apply_to(self, config: &mut ReverbConfig) -> Result<(), Error> { + self.validate()?; + if let Some(enabled) = self.enabled { + config.enabled = enabled; + } + if let Some(mode) = self.mode { + config.mode = mode; + } + if let Some(mix) = self.mix { + config.mix = mix; + } + if let Some(diffusion) = self.diffusion { + config.diffusion = diffusion; + } + if let Some(decay) = self.decay { + config.decay = decay; + } + if let Some(brightness_hz) = self.brightness_hz { + config.brightness_hz = brightness_hz; + } + Ok(()) + } +} + /// The shared Q14 delay network with two low-pass damping filters that keep /// state. #[derive(Debug)] diff --git a/src/effects/warm.rs b/src/effects/warm.rs index a1e1a3c..b437c88 100644 --- a/src/effects/warm.rs +++ b/src/effects/warm.rs @@ -57,6 +57,55 @@ pub(crate) fn validate_drive_db(drive_db: f32) -> Result<(), Error> { check_range("warm.drive_db", drive_db, 0.0, 6.0) } +/// Optional changes to [`WarmConfig`]. +/// +/// Each `None` field keeps its active value on the processor. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[non_exhaustive] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + derive(serde::Serialize, serde::Deserialize, tsify::Tsify), + serde(default, rename_all = "camelCase") +)] +pub struct WarmConfigPatch { + /// Enables the saturation stage (`true` or `false`). + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "boolean | undefined") + )] + pub enabled: Option, + /// The drive in decibels, 0..=6. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "number | undefined") + )] + pub drive_db: Option, +} + +impl WarmConfigPatch { + /// Checks all supplied fields and does not change the processor state. + pub(crate) fn validate(self) -> Result<(), Error> { + if let Some(drive_db) = self.drive_db { + validate_drive_db(drive_db)?; + } + Ok(()) + } + + /// Validates all supplied fields and writes them into `config`. + pub(crate) fn apply_to(self, config: &mut WarmConfig) -> Result<(), Error> { + self.validate()?; + if let Some(enabled) = self.enabled { + config.enabled = enabled; + } + if let Some(drive_db) = self.drive_db { + config.drive_db = drive_db; + } + Ok(()) + } +} + /// An adaptive asymmetric saturator with one persistent high-pass output /// filter. #[derive(Debug)] diff --git a/src/events.rs b/src/events.rs index ef07dee..a1c2481 100644 --- a/src/events.rs +++ b/src/events.rs @@ -10,7 +10,7 @@ use crate::harmony; use crate::midi::MidiEvent; use crate::pitch; use crate::resynthesis; -use crate::{Error, EventProblem, ProcessorConfig, ResynthesisConfig}; +use crate::{Error, EventProblem, ProcessorConfig, ProcessorConfigPatch, ResynthesisConfig}; /// One scalar configuration parameter for [`ControlEvent::Parameter`]. /// @@ -201,9 +201,10 @@ impl ParameterControl { /// /// 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. 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`]. +/// queue. Use [`Self::Parameter`] to change one scalar field, or +/// [`Self::Patch`] to change selected fields. 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( @@ -214,6 +215,8 @@ impl ParameterControl { pub enum ControlEvent { /// This event replaces the full configuration. Configure(ProcessorConfig), + /// This event merges supplied fields into the active configuration. + Patch(ProcessorConfigPatch), /// This event replaces the resynthesis configuration. Resynthesis(ResynthesisConfig), /// This event replaces the Punch configuration. @@ -262,6 +265,10 @@ impl ControlEvent { /// Checks the configuration or MIDI ranges of the event, and does not /// apply the event. /// + /// For [`Self::Patch`], this method checks all supplied fields, and checks + /// the pitch frequency order if the patch gives both bounds. A process + /// call also checks a single pitch bound against the active configuration. + /// /// # Errors /// /// Returns [`Error::InvalidConfig`] for an invalid configuration, scalar @@ -271,6 +278,7 @@ impl ControlEvent { pub fn validate(self) -> Result<(), Error> { match self { Self::Configure(config) => config.validate(), + Self::Patch(patch) => patch.validate(), Self::Resynthesis(config) => config.validate(), Self::Punch(config) => config.validate(), Self::Warm(config) => config.validate(), @@ -389,6 +397,7 @@ fn validate_in_sequence(event: ControlEvent, config: &mut ProcessorConfig) -> Re *config = value; Ok(()) } + ControlEvent::Patch(patch) => patch.apply_to(config), ControlEvent::Resynthesis(value) => { value.validate()?; config.resynthesis = value; diff --git a/src/formant.rs b/src/formant.rs index b4ea383..2f211d8 100644 --- a/src/formant.rs +++ b/src/formant.rs @@ -134,6 +134,94 @@ pub(crate) fn validate_aspiration_cutoff_hz(aspiration_cutoff_hz: f32) -> Result ) } +/// Optional changes to [`FormantConfig`]. +/// +/// Each `None` field keeps its active value on the processor. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[non_exhaustive] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + derive(serde::Serialize, serde::Deserialize, tsify::Tsify), + serde(default, rename_all = "camelCase") +)] +pub struct FormantConfigPatch { + /// Enables formant analysis and synthesis (`true` or `false`). + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "boolean | undefined") + )] + pub enabled: Option, + /// The vocal-tract width factor, 0.5..=2. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "number | undefined") + )] + pub width: Option, + /// The vocal-tract length factor, 0.5..=2. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "number | undefined") + )] + pub stretch: Option, + /// The aspiration level, 0..=1, without a unit. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "number | undefined") + )] + pub aspiration_mix: Option, + /// The high-pass cutoff for aspiration in hertz, 500..=10000. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "number | undefined") + )] + pub aspiration_cutoff_hz: Option, +} + +impl FormantConfigPatch { + /// Checks all supplied fields and does not change the processor state. + pub(crate) fn validate(self) -> Result<(), Error> { + if let Some(width) = self.width { + validate_width(width)?; + } + if let Some(stretch) = self.stretch { + validate_stretch(stretch)?; + } + if let Some(aspiration_mix) = self.aspiration_mix { + validate_aspiration_mix(aspiration_mix)?; + } + if let Some(aspiration_cutoff_hz) = self.aspiration_cutoff_hz { + validate_aspiration_cutoff_hz(aspiration_cutoff_hz)?; + } + Ok(()) + } + + /// Validates all supplied fields and writes them into `config`. + pub(crate) fn apply_to(self, config: &mut FormantConfig) -> Result<(), Error> { + self.validate()?; + if let Some(enabled) = self.enabled { + config.enabled = enabled; + } + if let Some(width) = self.width { + config.width = width; + } + if let Some(stretch) = self.stretch { + config.stretch = stretch; + } + if let Some(aspiration_mix) = self.aspiration_mix { + config.aspiration_mix = aspiration_mix; + } + if let Some(aspiration_cutoff_hz) = self.aspiration_cutoff_hz { + config.aspiration_cutoff_hz = aspiration_cutoff_hz; + } + Ok(()) + } +} + /// 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; diff --git a/src/harmony.rs b/src/harmony.rs index f2adfe3..3bd0872 100644 --- a/src/harmony.rs +++ b/src/harmony.rs @@ -448,6 +448,171 @@ pub(crate) fn validate_portamento_ms(portamento_ms: f32) -> Result<(), Error> { ) } +/// Optional changes to [`HarmonyConfig`]. +/// +/// Each `None` field keeps its active value on the processor. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[non_exhaustive] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + derive(serde::Serialize, serde::Deserialize, tsify::Tsify), + serde(default, rename_all = "camelCase") +)] +pub struct HarmonyConfigPatch { + /// The pitch source (`HarmonySource`). + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "HarmonySource | undefined") + )] + pub source: Option, + /// The pitch class of the tonic (`PitchClass`). + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "PitchClass | undefined") + )] + pub key: Option, + /// The scale for smart intervals and degree chords (`HarmonyScale`). + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "HarmonyScale | undefined") + )] + pub scale: Option, + /// Four fixed semitone offsets, each in -24..=24. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "[number, number, number, number] | undefined") + )] + pub chromatic_intervals: Option<[i8; HARMONY_VOICES]>, + /// Four offsets in scale steps, each in -14..=14. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "[number, number, number, number] | undefined") + )] + pub diatonic_intervals: Option<[i8; HARMONY_VOICES]>, + /// The named chord for [`HarmonySource::ChordByName`] (`ChordName`). + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "ChordName | undefined") + )] + pub chord: Option, + /// The chord on a scale degree for [`HarmonySource::ChordByDegree`] + /// (`ChordDegree`). + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "ChordDegree | undefined") + )] + pub degree: Option, + /// The inversion for named chords and degree chords (`Inversion`). + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "Inversion | undefined") + )] + pub inversion: Option, + /// The chord register from low to high, 0..=100%. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "number | undefined") + )] + pub register_percent: Option, + /// The chord spread from close to open, 0..=100%. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "number | undefined") + )] + pub voicing_spread_percent: Option, + /// The half-life of the target period in milliseconds, 0..=10000. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "number | undefined") + )] + pub portamento_ms: Option, + /// The number of voices that sound in the interval sources, 0..=4. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "number | undefined") + )] + pub voices: Option, +} + +impl HarmonyConfigPatch { + /// Checks all supplied fields and does not change the processor state. + pub(crate) fn validate(self) -> Result<(), Error> { + if let Some(chromatic_intervals) = self.chromatic_intervals { + validate_chromatic_intervals(chromatic_intervals)?; + } + if let Some(diatonic_intervals) = self.diatonic_intervals { + validate_diatonic_intervals(diatonic_intervals)?; + } + if let Some(voices) = self.voices { + validate_voices(voices)?; + } + if let Some(register_percent) = self.register_percent { + validate_register_percent(register_percent)?; + } + if let Some(voicing_spread_percent) = self.voicing_spread_percent { + validate_voicing_spread_percent(voicing_spread_percent)?; + } + if let Some(portamento_ms) = self.portamento_ms { + validate_portamento_ms(portamento_ms)?; + } + Ok(()) + } + + /// Validates all supplied fields and writes them into `config`. + pub(crate) fn apply_to(self, config: &mut HarmonyConfig) -> Result<(), Error> { + self.validate()?; + if let Some(source) = self.source { + config.source = source; + } + if let Some(key) = self.key { + config.key = key; + } + if let Some(scale) = self.scale { + config.scale = scale; + } + if let Some(chromatic_intervals) = self.chromatic_intervals { + config.chromatic_intervals = chromatic_intervals; + } + if let Some(diatonic_intervals) = self.diatonic_intervals { + config.diatonic_intervals = diatonic_intervals; + } + if let Some(chord) = self.chord { + config.chord = chord; + } + if let Some(degree) = self.degree { + config.degree = degree; + } + if let Some(inversion) = self.inversion { + config.inversion = inversion; + } + if let Some(register_percent) = self.register_percent { + config.register_percent = register_percent; + } + if let Some(voicing_spread_percent) = self.voicing_spread_percent { + config.voicing_spread_percent = voicing_spread_percent; + } + if let Some(portamento_ms) = self.portamento_ms { + config.portamento_ms = portamento_ms; + } + if let Some(voices) = self.voices { + config.voices = voices; + } + Ok(()) + } +} + /// The prepared controller of periods and gains, and the MIDI allocator, for /// four voices. /// diff --git a/src/lib.rs b/src/lib.rs index 80f8d33..d09758b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -19,7 +19,8 @@ //! that are not active. //! //! A configuration value is a copy. If you change it, the processor does not -//! change until [`Processor::set_config`] or a configuration event applies it. +//! change until [`Processor::set_config`], [`Processor::patch_config`] or a +//! configuration event applies it. //! You can change settings between blocks, or at a frame offset with a //! [`TimedEvent`]. To change the sample rate or the block limit, you //! must make a new processor. @@ -134,19 +135,25 @@ mod scale; #[cfg(all(feature = "wasm", target_arch = "wasm32"))] pub mod wasm; -pub use config::{ControlActivity, PrepareConfig, ProcessorConfig, SampleRate}; -pub use effects::alien::AlienConfig; -pub use effects::punch::PunchConfig; -pub use effects::reverb::{ReverbConfig, ReverbMode}; -pub use effects::warm::WarmConfig; +pub use config::{ + ControlActivity, PrepareConfig, ProcessorConfig, ProcessorConfigPatch, SampleRate, +}; +pub use effects::alien::{AlienConfig, AlienConfigPatch}; +pub use effects::punch::{PunchConfig, PunchConfigPatch}; +pub use effects::reverb::{ReverbConfig, ReverbConfigPatch, ReverbMode}; +pub use effects::warm::{WarmConfig, WarmConfigPatch}; pub use error::{ConfigProblem, Error, EventProblem}; pub use events::{ControlEvent, ParameterControl, TimedEvent}; -pub use formant::FormantConfig; +pub use formant::{FormantConfig, FormantConfigPatch}; pub use harmony::{ - ChordDegree, ChordName, HarmonyConfig, HarmonyScale, HarmonySource, Inversion, HARMONY_VOICES, + ChordDegree, ChordName, HarmonyConfig, HarmonyConfigPatch, HarmonyScale, HarmonySource, + Inversion, HARMONY_VOICES, }; pub use midi::MidiEvent; -pub use pitch::PitchConfig; +pub use pitch::{PitchConfig, PitchConfigPatch}; pub use processor::{Feedback, Processor, Telemetry}; -pub use resynthesis::{CorrectionConfig, MultiVoiceMode, ResynthesisConfig}; +pub use resynthesis::{ + CorrectionConfig, CorrectionConfigPatch, MultiVoiceMode, ResynthesisConfig, + ResynthesisConfigPatch, +}; pub use scale::{CorrectionScale, NoteMask, PitchClass}; diff --git a/src/pitch.rs b/src/pitch.rs index ee85339..d5f95b7 100644 --- a/src/pitch.rs +++ b/src/pitch.rs @@ -80,24 +80,127 @@ impl PitchConfig { /// `resynthesis.pitch.max_frequency_hz`. pub fn validate(self) -> Result<(), Error> { validate_threshold(self.threshold)?; - let (min, max) = ( - "resynthesis.pitch.min_frequency_hz", - "resynthesis.pitch.max_frequency_hz", - ); - check_range(min, self.min_frequency_hz, 40.0, 2000.0)?; - check_range(max, self.max_frequency_hz, 40.0, 2000.0)?; - if self.min_frequency_hz >= self.max_frequency_hz { - return Err(Error::config(min, ConfigProblem::Unordered { other: max })); - } - Ok(()) + validate_min_frequency_hz(self.min_frequency_hz)?; + validate_max_frequency_hz(self.max_frequency_hz)?; + check_frequency_order(self.min_frequency_hz, self.max_frequency_hz) } } +/// The dotted field path of the lower pitch bound. +const MIN_FIELD: &str = "resynthesis.pitch.min_frequency_hz"; +/// The dotted field path of the upper pitch bound. +const MAX_FIELD: &str = "resynthesis.pitch.max_frequency_hz"; + /// 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) } +/// Checks the range of the lower bound for pitch reports. +pub(crate) fn validate_min_frequency_hz(min_frequency_hz: f32) -> Result<(), Error> { + check_range(MIN_FIELD, min_frequency_hz, 40.0, 2000.0) +} + +/// Checks the range of the upper bound for pitch reports. +pub(crate) fn validate_max_frequency_hz(max_frequency_hz: f32) -> Result<(), Error> { + check_range(MAX_FIELD, max_frequency_hz, 40.0, 2000.0) +} + +/// Checks that `min_frequency_hz` is strictly below `max_frequency_hz`. +fn check_frequency_order(min_frequency_hz: f32, max_frequency_hz: f32) -> Result<(), Error> { + if min_frequency_hz >= max_frequency_hz { + return Err(Error::config( + MIN_FIELD, + ConfigProblem::Unordered { other: MAX_FIELD }, + )); + } + Ok(()) +} + +/// Optional changes to [`PitchConfig`]. +/// +/// Each `None` field keeps its active value on the processor. After a merge, +/// `min_frequency_hz` must stay strictly below `max_frequency_hz`. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[non_exhaustive] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + derive(serde::Serialize, serde::Deserialize, tsify::Tsify), + serde(default, rename_all = "camelCase") +)] +pub struct PitchConfigPatch { + /// The normalized cycle-difference threshold for acquisition, 0.002..=0.2. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "number | undefined") + )] + pub threshold: Option, + /// The lower bound of the feedback in hertz (inclusive), 40..=2000. + /// + /// It must stay strictly below `max_frequency_hz`. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "number | undefined") + )] + pub min_frequency_hz: Option, + /// The upper bound of the feedback in hertz (inclusive), 40..=2000. + /// + /// It must stay strictly above `min_frequency_hz`. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "number | undefined") + )] + pub max_frequency_hz: Option, +} + +impl PitchConfigPatch { + /// Checks the ranges of all supplied fields. + fn validate_fields(self) -> Result<(), Error> { + if let Some(threshold) = self.threshold { + validate_threshold(threshold)?; + } + if let Some(min_frequency_hz) = self.min_frequency_hz { + validate_min_frequency_hz(min_frequency_hz)?; + } + if let Some(max_frequency_hz) = self.max_frequency_hz { + validate_max_frequency_hz(max_frequency_hz)?; + } + Ok(()) + } + + /// Checks all supplied fields, and checks their order if both bounds are + /// present. + pub(crate) fn validate(self) -> Result<(), Error> { + self.validate_fields()?; + if let (Some(min_frequency_hz), Some(max_frequency_hz)) = + (self.min_frequency_hz, self.max_frequency_hz) + { + check_frequency_order(min_frequency_hz, max_frequency_hz)?; + } + Ok(()) + } + + /// Validates all supplied fields, checks the frequency order against + /// `config` and writes the fields into `config`. + pub(crate) fn apply_to(self, config: &mut PitchConfig) -> Result<(), Error> { + self.validate_fields()?; + let min_frequency_hz = self.min_frequency_hz.unwrap_or(config.min_frequency_hz); + let max_frequency_hz = self.max_frequency_hz.unwrap_or(config.max_frequency_hz); + if self.min_frequency_hz.is_some() || self.max_frequency_hz.is_some() { + check_frequency_order(min_frequency_hz, max_frequency_hz)?; + } + if let Some(threshold) = self.threshold { + config.threshold = threshold; + } + config.min_frequency_hz = min_frequency_hz; + config.max_frequency_hz = max_frequency_hz; + Ok(()) + } +} + /// 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/processor.rs b/src/processor.rs index 9f8ae9b..c86120f 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -10,7 +10,7 @@ use crate::numeric::NumericContext; use crate::resynthesis::{self, Resynthesis}; use crate::{ ControlActivity, ControlEvent, Error, ParameterControl, PrepareConfig, ProcessorConfig, - TimedEvent, + ProcessorConfigPatch, TimedEvent, }; /// Selects the output channel layout for the downmix and the peak meters. @@ -706,6 +706,26 @@ impl Processor { Ok(()) } + /// Merges supplied fields onto the active configuration, validates touched + /// stages and applies the result. + /// + /// State retention, resets on a change of `stereo_output`, restarts on a + /// change of `random_seed` and drain cancellation are the same as for + /// [`set_config`](Self::set_config). An empty patch also cancels an active + /// drain. + /// + /// # Errors + /// + /// Returns [`Error::InvalidConfig`] if a supplied field or the merged + /// pitch frequency order is not valid. The method returns this error + /// before it changes any state or any active drain. + pub fn patch_config(&mut self, patch: ProcessorConfigPatch) -> Result<(), Error> { + let mut config = self.config; + patch.apply_to(&mut config)?; + self.apply_config(config); + Ok(()) + } + /// Applies a configuration that the public setter or the preflight checked. fn apply_config(&mut self, config: ProcessorConfig) { if self.config.punch != config.punch { @@ -802,13 +822,18 @@ impl Processor { /// Applies a validated control immediately before its frame is rendered. /// - /// A stage event replaces one stage in the active configuration. A scalar + /// A stage or patch event updates 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) { match event.into_inner() { ControlEvent::Configure(value) => self.apply_config(value), + ControlEvent::Patch(patch) => { + let mut config = self.config; + let _ = patch.apply_to(&mut config); + self.apply_config(config); + } ControlEvent::Resynthesis(value) => { let mut config = self.config; config.resynthesis = value; diff --git a/src/resynthesis.rs b/src/resynthesis.rs index f0e844f..e817115 100644 --- a/src/resynthesis.rs +++ b/src/resynthesis.rs @@ -31,13 +31,13 @@ pub(crate) mod history; use crate::error::{check_count, check_range}; use crate::filter::{Biquad, Design}; -use crate::formant::{Formant, FormantConfig, ANALYSIS_FRAMES}; -use crate::harmony::{HarmonyConfig, HarmonyState, HARMONY_VOICES}; +use crate::formant::{Formant, FormantConfig, FormantConfigPatch, ANALYSIS_FRAMES}; +use crate::harmony::{HarmonyConfig, HarmonyConfigPatch, HarmonyState, HARMONY_VOICES}; use crate::midi::MidiEvent; use crate::numeric::fixed::{Q12, Q14, Q6, Q8}; use crate::numeric::{clamp_i32, quadratic, ring, NumericContext, HISTORY}; use crate::pitch::tracker::PitchTracker; -use crate::pitch::{PitchConfig, PitchEstimate}; +use crate::pitch::{PitchConfig, PitchConfigPatch, PitchEstimate}; use crate::scale::{CorrectionTable, NoteMask}; use crate::{Error, SampleRate}; use history::{clear_dirty_ring, prepare_history, record_history}; @@ -192,6 +192,91 @@ pub(crate) fn validate_flex_tune(flex_tune: f32) -> Result<(), Error> { check_range("resynthesis.correction.flex_tune", flex_tune, 0.0, 1.0) } +/// Optional changes to [`CorrectionConfig`]. +/// +/// Each `None` field keeps its active value on the processor. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[non_exhaustive] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + derive(serde::Serialize, serde::Deserialize, tsify::Tsify), + serde(default, rename_all = "camelCase") +)] +pub struct CorrectionConfigPatch { + /// Enables the selection of correction targets (`true` or `false`). + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "boolean | undefined") + )] + pub enabled: Option, + /// The configured target pitch classes (`NoteMask`). + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "NoteMask | undefined") + )] + pub notes: Option, + /// The half-life of the ratio in milliseconds, 0..=400. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "number | undefined") + )] + pub retune_ms: Option, + /// The relaxation on sustained notes without a unit, 0..=1. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "number | undefined") + )] + pub humanize: Option, + /// The outer soft-zone width of each target bin without a unit, 0..=1. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "number | undefined") + )] + pub flex_tune: Option, +} + +impl CorrectionConfigPatch { + /// Checks all supplied fields and does not change the processor state. + pub(crate) fn validate(self) -> Result<(), Error> { + if let Some(retune_ms) = self.retune_ms { + validate_retune_ms(retune_ms)?; + } + if let Some(humanize) = self.humanize { + validate_humanize(humanize)?; + } + if let Some(flex_tune) = self.flex_tune { + validate_flex_tune(flex_tune)?; + } + Ok(()) + } + + /// Validates all supplied fields and writes them into `config`. + pub(crate) fn apply_to(self, config: &mut CorrectionConfig) -> Result<(), Error> { + self.validate()?; + if let Some(enabled) = self.enabled { + config.enabled = enabled; + } + if let Some(notes) = self.notes { + config.notes = notes; + } + if let Some(retune_ms) = self.retune_ms { + config.retune_ms = retune_ms; + } + if let Some(humanize) = self.humanize { + config.humanize = humanize; + } + if let Some(flex_tune) = self.flex_tune { + config.flex_tune = flex_tune; + } + Ok(()) + } +} + /// The controls for pitch correction, pitch shift, voice arrangement and /// formants. /// @@ -408,6 +493,224 @@ pub(crate) fn validate_dry_mix(dry_mix: f32) -> Result<(), Error> { check_range("resynthesis.dry_mix", dry_mix, 0.0, 1.0) } +/// Optional changes to [`ResynthesisConfig`]. +/// +/// Each `None` field keeps its active value on the processor. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[non_exhaustive] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + derive(serde::Serialize, serde::Deserialize, tsify::Tsify), + serde(default, rename_all = "camelCase"), + tsify(large_number_types_as_bigints) +)] +pub struct ResynthesisConfigPatch { + /// Optional changes to [`PitchConfig`]. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "PitchConfigPatch | undefined") + )] + pub pitch: Option, + /// Optional changes to [`CorrectionConfig`]. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "CorrectionConfigPatch | undefined") + )] + pub correction: Option, + /// The pitch multiplier, 0.25..=4. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "number | undefined") + )] + pub pitch_ratio: Option, + /// Optional changes to [`FormantConfig`]. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "FormantConfigPatch | undefined") + )] + pub formant: Option, + /// The voice arrangement (`MultiVoiceMode`). + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "MultiVoiceMode | undefined") + )] + pub mode: Option, + /// The total number of choir voices, with the lead voice, 1..=16. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "number | undefined") + )] + pub choir_voices: Option, + /// The drift control for secondary voices, 10..=100, without a unit. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "number | undefined") + )] + pub choir_detune: Option, + /// The scale of the choir delay table, 20..=200, without a unit. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "number | undefined") + )] + pub choir_delay: Option, + /// The stereo width of the choir, 0..=100%. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "number | undefined") + )] + pub choir_spread_percent: Option, + /// Enables a stereo pan for each voice (`true` or `false`). + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "boolean | undefined") + )] + pub stereo_output: Option, + /// Optional changes to [`HarmonyConfig`]. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "HarmonyConfigPatch | undefined") + )] + pub harmony: Option, + /// The linear gain of the four harmony voices, 0..=1. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "number | undefined") + )] + pub harmony_gain: Option, + /// The modulation depth, 0..=24, without a unit. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "number | undefined") + )] + pub harmonic_modulation: Option, + /// The dry fraction at the resynthesis stage, 0..=1. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "number | undefined") + )] + pub dry_mix: Option, + /// The seed for choir drift and aspiration (`0..=u64::MAX`). + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional, type = "bigint | undefined") + )] + pub random_seed: Option, +} + +impl ResynthesisConfigPatch { + /// Checks the supplied scalar fields of resynthesis. + fn validate_scalars(self) -> Result<(), Error> { + if let Some(pitch_ratio) = self.pitch_ratio { + validate_pitch_ratio(pitch_ratio)?; + } + if let Some(choir_detune) = self.choir_detune { + validate_choir_detune(choir_detune)?; + } + if let Some(choir_delay) = self.choir_delay { + validate_choir_delay(choir_delay)?; + } + if let Some(choir_spread_percent) = self.choir_spread_percent { + validate_choir_spread_percent(choir_spread_percent)?; + } + if let Some(harmony_gain) = self.harmony_gain { + validate_harmony_gain(harmony_gain)?; + } + if let Some(harmonic_modulation) = self.harmonic_modulation { + validate_harmonic_modulation(harmonic_modulation)?; + } + if let Some(dry_mix) = self.dry_mix { + validate_dry_mix(dry_mix)?; + } + if let Some(choir_voices) = self.choir_voices { + validate_choir_voices(choir_voices)?; + } + Ok(()) + } + + /// Checks all supplied sub-stages and scalar fields. + pub(crate) fn validate(self) -> Result<(), Error> { + if let Some(pitch) = self.pitch { + pitch.validate()?; + } + if let Some(correction) = self.correction { + correction.validate()?; + } + if let Some(formant) = self.formant { + formant.validate()?; + } + if let Some(harmony) = self.harmony { + harmony.validate()?; + } + self.validate_scalars() + } + + /// Validates all supplied fields and writes them into `config`. + pub(crate) fn apply_to(self, config: &mut ResynthesisConfig) -> Result<(), Error> { + if let Some(pitch) = self.pitch { + pitch.apply_to(&mut config.pitch)?; + } + if let Some(correction) = self.correction { + correction.apply_to(&mut config.correction)?; + } + if let Some(formant) = self.formant { + formant.apply_to(&mut config.formant)?; + } + if let Some(harmony) = self.harmony { + harmony.apply_to(&mut config.harmony)?; + } + self.validate_scalars()?; + if let Some(pitch_ratio) = self.pitch_ratio { + config.pitch_ratio = pitch_ratio; + } + if let Some(mode) = self.mode { + config.mode = mode; + } + if let Some(choir_voices) = self.choir_voices { + config.choir_voices = choir_voices; + } + if let Some(choir_detune) = self.choir_detune { + config.choir_detune = choir_detune; + } + if let Some(choir_delay) = self.choir_delay { + config.choir_delay = choir_delay; + } + if let Some(choir_spread_percent) = self.choir_spread_percent { + config.choir_spread_percent = choir_spread_percent; + } + if let Some(stereo_output) = self.stereo_output { + config.stereo_output = stereo_output; + } + if let Some(harmony_gain) = self.harmony_gain { + config.harmony_gain = harmony_gain; + } + if let Some(harmonic_modulation) = self.harmonic_modulation { + config.harmonic_modulation = harmonic_modulation; + } + if let Some(dry_mix) = self.dry_mix { + config.dry_mix = dry_mix; + } + if let Some(random_seed) = self.random_seed { + config.random_seed = random_seed; + } + Ok(()) + } +} + /// The fixed choir delay offsets in frames, before the scale by /// `choir_delay / 200`. /// diff --git a/src/wasm.rs b/src/wasm.rs index e868d16..6196d3c 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -20,9 +20,11 @@ //! //! - Field names use camelCase. //! - Enum values are strings. -//! - Each object must contain all required fields. +//! - Each object for `setConfig` must contain all required fields. //! - The optional correction `humanize` and `flexTune` fields default to 0. //! - The optional harmony `voices` field defaults to 4. +//! - Patch objects in `ProcessorConfigPatch` can omit fields that do not +//! change. //! //! [`default_config`] gives a configuration to start from. Control events use //! `{ type, value }`, and the reset control has no `value`. Scalar parameter @@ -36,7 +38,7 @@ //! across calls. These operations can allocate: //! //! - Event decode when a call gives more events than before, or when an event -//! converts a stage configuration. +//! converts a configuration or a patch. //! - The conversion of configurations. //! - Feedback, control-activity and telemetry objects. //! - The buffers of the formant envelopes. @@ -53,7 +55,7 @@ use crate::events::ValidatedEvents; use crate::processor::EnvelopeKey; use crate::{ ControlActivity, ControlEvent, Error, Feedback, MidiEvent, ParameterControl, PrepareConfig, - Processor, ProcessorConfig, SampleRate, Telemetry, TimedEvent, + Processor, ProcessorConfig, ProcessorConfigPatch, SampleRate, Telemetry, TimedEvent, }; use js_sys::{Array, Float32Array, Int16Array, Object, Reflect}; use serde::{Deserialize, Serialize}; @@ -270,8 +272,8 @@ impl WasmProcessor { /// Returns a copy of the active configuration as a new JavaScript object. /// - /// A change to the object has no effect until `setConfig` or a timed event - /// applies it. + /// A change to the object has no effect until `setConfig`, `patchConfig` + /// or a timed event applies it. /// /// # Errors /// @@ -296,6 +298,25 @@ impl WasmProcessor { Ok(()) } + /// Decodes and validates a partial configuration, then merges its supplied + /// fields into the active configuration. + /// + /// Omitted fields keep their active values. State retention and drain + /// cancellation are the same as for `setConfig`. An empty object also + /// cancels an active drain. The conversion ignores additional properties of + /// the JavaScript object. + /// + /// # Errors + /// + /// The method throws if an object, a supplied value or the pitch bound + /// order is not valid. After an error, all processor state and any active + /// drain stay the same. + #[wasm_bindgen(js_name = patchConfig)] + pub fn patch_config(&mut self, patch: Ts) -> Result<(), JsError> { + self.processor.patch_config(patch.to_rust()?)?; + Ok(()) + } + /// Processes mono input into left and right `Int16Array` buffers of equal /// length. /// @@ -861,6 +882,7 @@ struct EventKeys { parameter: JsValue, reset: JsValue, configure: JsValue, + patch: JsValue, resynthesis: JsValue, punch: JsValue, warm: JsValue, @@ -890,6 +912,7 @@ impl EventKeys { parameter: JsValue::from_str("parameter"), reset: JsValue::from_str("reset"), configure: JsValue::from_str("configure"), + patch: JsValue::from_str("patch"), resynthesis: JsValue::from_str("resynthesis"), punch: JsValue::from_str("punch"), warm: JsValue::from_str("warm"), @@ -1105,6 +1128,9 @@ fn decode_control_event(event: &JsValue, keys: &EventKeys) -> Result