From 76b850d03231f0407b97b34a4aaec478086c41c5 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Sat, 21 Nov 2026 01:57:01 +0000 Subject: [PATCH] feat!: use patch structures for configurations and events - Add Copy patch types and builders for all stages. - Merge validated patches in Processor::new and update_config. - Add non-destructive patch variants to ControlEvent. - Change ResynthesisConfig::random_seed to u32. - Serialize Wasm frame counts as JavaScript numbers. - Add all seven HarmonyScale modes to CorrectionScale. - Export updateConfig, noteMaskFromKeyScale and parseMidiBytes in Wasm. --- README.md | 128 +++++++---- src/config.rs | 201 ++++++++++++++++- src/effects/alien.rs | 82 +++++++ src/effects/punch.rs | 151 +++++++++++++ src/effects/reverb.rs | 174 ++++++++++++++ src/effects/warm.rs | 82 +++++++ src/events.rs | 134 ++++++++--- src/formant.rs | 152 +++++++++++++ src/harmony.rs | 350 +++++++++++++++++++++++++++- src/index.ts | 26 ++- src/lib.rs | 39 ++-- src/pitch.rs | 111 +++++++++ src/processor.rs | 76 +++++-- src/resynthesis.rs | 515 ++++++++++++++++++++++++++++++++++++++++-- src/scale.rs | 69 ++++-- src/wasm.rs | 160 ++++++++++--- 16 files changed, 2255 insertions(+), 195 deletions(-) diff --git a/README.md b/README.md index d2993dc..0f3b406 100644 --- a/README.md +++ b/README.md @@ -97,8 +97,8 @@ If you use the scoped package, import from `@bytelandtechnology/tunelet`. ```rust use tunelet::{ - CorrectionScale, NoteMask, PitchClass, PrepareConfig, Processor, ProcessorConfig, - SampleRate, + CorrectionPatch, CorrectionScale, NoteMask, PitchClass, PrepareConfig, Processor, + ProcessorPatch, ResynthesisPatch, SampleRate, }; fn main() -> Result<(), tunelet::Error> { @@ -106,14 +106,20 @@ fn main() -> Result<(), tunelet::Error> { let rate = SampleRate::try_from(48_000)?; let preparation = PrepareConfig::new(rate, 1024)?; - // 2. Start from the default configuration and change fields. - let mut config = ProcessorConfig::default(); - config.resynthesis.correction.notes = - NoteMask::from_key_scale(PitchClass::A, CorrectionScale::Minor); - config.resynthesis.correction.retune_ms = 20.0; + // 2. Build a patch for the fields that differ from the defaults. + let patch = ProcessorPatch::new().with_resynthesis( + ResynthesisPatch::new().with_correction( + CorrectionPatch::new() + .with_notes(NoteMask::from_key_scale( + PitchClass::A, + CorrectionScale::Minor, + )) + .with_retune_ms(20.0), + ), + ); // 3. Construct the processor. Only this step allocates memory. - let mut processor = Processor::new(preparation, config)?; + let mut processor = Processor::new(preparation, patch)?; // 4. Process blocks. Each input sample gives one stereo frame. let input = [0i16; 1024]; @@ -136,12 +142,12 @@ fn main() -> Result<(), tunelet::Error> { ### TypeScript ```ts -import { loadTunelet, Tunelet, defaultConfig } from "tunelet"; +import { loadTunelet, Tunelet } from "tunelet"; await loadTunelet(); -const config = defaultConfig(); -config.resynthesis.pitchRatio = 1.25; -const processor = new Tunelet(48000, 1024, config); +const processor = new Tunelet(48000, 1024, { + resynthesis: { pitchRatio: 1.25 }, +}); const input = new Int16Array(1024); const left = new Int16Array(1024); @@ -201,11 +207,13 @@ To prepare a processor, do these steps: 1. Use `SampleRate::try_from(hz)` to check the input rate. 2. Use `PrepareConfig::new(rate, max_block_frames)` to set a nonzero block limit. -3. Create a `Processor` with that preparation and a `ProcessorConfig`. +3. Create a `Processor` with that preparation and a `ProcessorConfig` or a + `ProcessorPatch`. -Configuration structures implement `Default`. To select voices and effects, -edit their fields. To change the sample rate or the block limit, make a new -processor. +Configuration structures implement `Default`, and `*Patch` structures change +selected fields. Use `update_config` to merge a `ProcessorPatch`, or use +`set_config` to replace the full `ProcessorConfig`. To change the sample rate +or the block limit, make a new processor. Select the process function for your output layout: @@ -237,8 +245,9 @@ 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. A patch event +(`Patch`, `ResynthesisPatch`, `PunchPatch`, `WarmPatch`, `AlienPatch` or +`ReverbPatch`) merges only `Some` fields onto the active configuration. Harmony MIDI uses `ControlEvent::Midi`. MIDI for the correction keyboard uses `ControlEvent::CorrectionMidi`. For example, this event starts a harmony note @@ -363,7 +372,7 @@ these items: Both environments use the same imports and the same initialization call. An import of the package does not load the binary. Call `loadTunelet()` before -you use `Tunelet` or `defaultConfig()`. +you use `Tunelet` or the helper functions. - Node.js reads the packaged binary from a file URL relative to the module. - Browsers fetch the served Wasm asset. @@ -406,19 +415,21 @@ page that opens the JavaScript. ### TypeScript API -| Operation | TypeScript API | -| --------------------------------- | -------------------------------------------------------- | -| Shared initialization | `loadTunelet(source?)` | -| Mono PCM to planar stereo | `process(input, left, right, events?)` | -| In-place mono downmix | `processMono(audio, events?)` | -| Configuration | `config()`, `setConfig(config)`, `defaultConfig()` | -| Information about the preparation | `sampleRate`, `maxBlockFrames`, `latencyFrames` | -| Feedback | `feedback()`, `takeFeedback()` | -| Telemetry | `telemetry()`, `takeTelemetry()` | -| Formant envelopes | `formantEnvelope(maxFrequencyHz, input, output)` | -| Finite tail | `beginDrain()`, `drain(left, right)`, `drainMono(audio)` | -| Configured tail budget | `tailFrames()` | -| Reset or release memory | `reset()`, `free()` | +| Operation | TypeScript API | +| --------------------------------- | ------------------------------------------------------------------------- | +| Shared initialization | `loadTunelet(source?)` | +| Construct a processor | `new Tunelet(sampleRate, maxBlockFrames, config?)` | +| Mono PCM to planar stereo | `process(input, left, right, events?)` | +| In-place mono downmix | `processMono(audio, events?)` | +| Configuration | `config()`, `setConfig(config)`, `updateConfig(patch)`, `defaultConfig()` | +| Scale and MIDI helpers | `noteMaskFromKeyScale(key, scale)`, `parseMidiBytes(bytes)` | +| Information about the preparation | `sampleRate`, `maxBlockFrames`, `latencyFrames` | +| Feedback | `feedback()`, `takeFeedback()` | +| Telemetry | `telemetry()`, `takeTelemetry()` | +| Formant envelopes | `formantEnvelope(maxFrequencyHz, input, output)` | +| Finite tail | `beginDrain()`, `drain(left, right)`, `drainMono(audio)` | +| Configured tail budget | `tailFrames()` | +| Reset or release memory | `reset()`, `free()` | ### Audio buffers @@ -436,22 +447,27 @@ audio device. ### Configuration objects -Configuration objects contain all required fields. They use camelCase names -and show enums as string literals. To change the configuration, do these steps: - -1. Start from `defaultConfig()` or `config()`. -2. Edit the necessary fields. -3. Call `setConfig()`. - -If a required field is absent or a value is not valid, the call throws a -JavaScript `Error`. The optional `resynthesis.harmony.voices` field defaults -to 4 if it is absent. The conversion ignores extra object properties. The -generated declarations contain the parameter documentation from the Rust +Configuration and patch objects use camelCase names and show enums as string +literals. `new Tunelet(sampleRate, maxBlockFrames, config?)` and +`updateConfig(patch)` accept a `ProcessorPatch`, where every field is +optional. Undefined fields keep their default or active values. + +To replace the entire configuration at one time, start from `defaultConfig()` +or `config()`, edit the fields and call `setConfig(config)`. In `setConfig`, +the optional `resynthesis.harmony.voices` field defaults to 4 if it is absent. +`noteMaskFromKeyScale(key, scale)` builds a 12-flag `NoteMask` for any +`PitchClass` and `CorrectionScale`, which includes all seven harmony modes and +`"chromatic"`. + +If a field is malformed or out of range, the call throws a JavaScript `Error` +before it changes the state. The conversion ignores extra object properties. +The generated declarations contain the parameter documentation from the Rust types. -`resynthesis.randomSeed` and the `processedFrames` field of feedback and -telemetry use `bigint`. Frame offsets, block lengths and latency use -`number`. +All numeric fields use `number`, so `JSON.stringify` works on +`defaultConfig()`, `config()`, `feedback()` and `telemetry()`. +`resynthesis.randomSeed` is an integer in `0..=4294967295`. `processedFrames` +saturates at `Number.MAX_SAFE_INTEGER`. ### Events @@ -463,15 +479,27 @@ example, this event changes the final gain before the first frame: { offset: 0, event: { type: "outputGain", value: 0.5 } } ``` -A harmony Note On event has this form: +Patch events (`patch`, `resynthesisPatch`, `punchPatch`, `warmPatch`, +`alienPatch` and `reverbPatch`) merge defined fields onto the active +configuration without overwrites: + +```ts +{ offset: 128, event: { type: "reverbPatch", value: { mix: 0.8 } } } +``` + +Stage events (`resynthesis`, `punch`, `warm`, `alien` and `reverb`) replace +all fields of that stage. A harmony Note On event has this form: ```ts { offset: 0, event: { type: "midi", value: { type: "noteOn", channel: 0, note: 60, velocity: 100 } } } ``` -Use `correctionMidi` for the separate correction keyboard. The native rules -for event order and for the validation of the whole block also apply to these -bindings. +`parseMidiBytes(bytes)` decodes a three-byte `Uint8Array` or number array into +a `MidiEvent` for Note On, Note Off and controller 123 (All Notes Off). It +returns `undefined` for valid messages that are not supported, and throws a +JavaScript `Error` on invalid bytes. Use `correctionMidi` for the separate +correction keyboard. The native rules for event order and for the validation +of the whole block also apply to these bindings. ### Feedback, telemetry and formant envelopes diff --git a/src/config.rs b/src/config.rs index 75bcd82..1be7ea4 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,10 +1,11 @@ //! Sample rates, block limits and the complete processor configuration. -use crate::effects::alien::AlienConfig; -use crate::effects::punch::PunchConfig; -use crate::effects::reverb::ReverbConfig; -use crate::effects::warm::WarmConfig; +use crate::effects::alien::{AlienConfig, AlienPatch}; +use crate::effects::punch::{PunchConfig, PunchPatch}; +use crate::effects::reverb::{ReverbConfig, ReverbPatch}; +use crate::effects::warm::{WarmConfig, WarmPatch}; use crate::error::{check_range, ConfigProblem}; +use crate::resynthesis::ResynthesisPatch; use crate::Error; use crate::ResynthesisConfig; use std::num::NonZeroUsize; @@ -117,6 +118,18 @@ impl PrepareConfig { max_block_frames, }) } + + /// Returns a copy with `sample_rate` set to the given value. + pub const fn with_sample_rate(mut self, sample_rate: SampleRate) -> Self { + self.sample_rate = sample_rate; + self + } + + /// Returns a copy with `max_block_frames` set to the given nonzero limit. + pub const fn with_max_block_frames(mut self, max_block_frames: NonZeroUsize) -> Self { + self.max_block_frames = max_block_frames; + self + } } /// The settings for the complete signal chain, in the order of the stages. @@ -134,8 +147,7 @@ impl PrepareConfig { #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), derive(serde::Serialize, serde::Deserialize, tsify::Tsify), - serde(rename_all = "camelCase"), - tsify(large_number_types_as_bigints) + serde(rename_all = "camelCase") )] pub struct ProcessorConfig { /// The input dynamics and saturation stage, which applies first. @@ -184,6 +196,68 @@ impl Default for ProcessorConfig { } impl ProcessorConfig { + /// Returns a copy with `punch` set to the given configuration. + pub const fn with_punch(mut self, punch: PunchConfig) -> Self { + self.punch = punch; + self + } + + /// Returns a copy with `warm` set to the given configuration. + pub const fn with_warm(mut self, warm: WarmConfig) -> Self { + self.warm = warm; + self + } + + /// Returns a copy with `resynthesis` set to the given configuration. + pub const fn with_resynthesis(mut self, resynthesis: ResynthesisConfig) -> Self { + self.resynthesis = resynthesis; + self + } + + /// Returns a copy with `alien` set to the given configuration. + pub const fn with_alien(mut self, alien: AlienConfig) -> Self { + self.alien = alien; + self + } + + /// Returns a copy with `reverb` set to the given configuration. + pub const fn with_reverb(mut self, reverb: ReverbConfig) -> Self { + self.reverb = reverb; + self + } + + /// Returns a copy with `output_gain` set to the given value, 0..=64. + pub const fn with_output_gain(mut self, output_gain: f32) -> Self { + self.output_gain = output_gain; + self + } + + /// Merges each present stage patch and gain field of `patch` into this + /// configuration. + /// + /// Fields that are `None` do not change. This method does not validate the + /// result. + pub fn merge_patch(&mut self, patch: ProcessorPatch) { + if let Some(punch) = patch.punch { + self.punch.merge_patch(punch); + } + if let Some(warm) = patch.warm { + self.warm.merge_patch(warm); + } + if let Some(resynthesis) = patch.resynthesis { + self.resynthesis.merge_patch(resynthesis); + } + if let Some(alien) = patch.alien { + self.alien.merge_patch(alien); + } + if let Some(reverb) = patch.reverb { + self.reverb.merge_patch(reverb); + } + if let Some(output_gain) = patch.output_gain { + self.output_gain = output_gain; + } + } + /// Checks all stages and the final gain, and does not change state. /// /// The validation uses the signal order: Punch, Warm, resynthesis, Alien, @@ -205,6 +279,121 @@ impl ProcessorConfig { } } +impl From for ProcessorConfig { + fn from(patch: ProcessorPatch) -> Self { + let mut config = Self::default(); + config.merge_patch(patch); + config + } +} + +/// Partial changes for [`ProcessorConfig`]. +/// +/// Give this structure to [`crate::Processor::new`], +/// [`crate::Processor::update_config`] or [`crate::ControlEvent::Patch`]. Only +/// fields and sub-patches that are `Some` overwrite the target settings in +/// [`ProcessorConfig::merge_patch`]. All fields are `None` by default. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + derive(serde::Serialize, serde::Deserialize, tsify::Tsify), + serde(default, rename_all = "camelCase") +)] +pub struct ProcessorPatch { + /// Partial changes for the Punch input stage. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional) + )] + pub punch: Option, + /// Partial changes for the Warm saturation stage. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional) + )] + pub warm: Option, + /// Partial changes for pitch tracking, correction, voices and formants. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional) + )] + pub resynthesis: Option, + /// Partial changes for the Alien reverse-loop stage. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional) + )] + pub alien: Option, + /// Partial changes for the reverb stage. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional) + )] + 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) + )] + pub output_gain: Option, +} + +impl ProcessorPatch { + /// Returns an empty patch with all fields set to `None`. + pub const fn new() -> Self { + Self { + punch: None, + warm: None, + resynthesis: None, + alien: None, + reverb: None, + output_gain: None, + } + } + + /// Sets `punch` on this patch. + pub const fn with_punch(mut self, punch: PunchPatch) -> Self { + self.punch = Some(punch); + self + } + + /// Sets `warm` on this patch. + pub const fn with_warm(mut self, warm: WarmPatch) -> Self { + self.warm = Some(warm); + self + } + + /// Sets `resynthesis` on this patch. + pub const fn with_resynthesis(mut self, resynthesis: ResynthesisPatch) -> Self { + self.resynthesis = Some(resynthesis); + self + } + + /// Sets `alien` on this patch. + pub const fn with_alien(mut self, alien: AlienPatch) -> Self { + self.alien = Some(alien); + self + } + + /// Sets `reverb` on this patch. + pub const fn with_reverb(mut self, reverb: ReverbPatch) -> Self { + self.reverb = Some(reverb); + self + } + + /// Sets `output_gain` on this patch, 0..=64. + pub const fn with_output_gain(mut self, output_gain: f32) -> Self { + self.output_gain = Some(output_gain); + self + } +} + /// 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 5e1f509..177e4fc 100644 --- a/src/effects/alien.rs +++ b/src/effects/alien.rs @@ -43,6 +43,31 @@ impl Default for AlienConfig { } } impl AlienConfig { + /// Returns a copy with `enabled` set to the given value. + pub const fn with_enabled(mut self, enabled: bool) -> Self { + self.enabled = enabled; + self + } + + /// Returns a copy with `loop_frames` set to the given value, 1..=96000. + pub const fn with_loop_frames(mut self, loop_frames: u32) -> Self { + self.loop_frames = loop_frames; + self + } + + /// Copies each present field of `patch` into this configuration. + /// + /// Fields that are `None` do not change. This method does not validate the + /// result. + pub fn merge_patch(&mut self, patch: AlienPatch) { + if let Some(enabled) = patch.enabled { + self.enabled = enabled; + } + if let Some(loop_frames) = patch.loop_frames { + self.loop_frames = loop_frames; + } + } + /// Validates all fields, also when Alien is disabled. /// /// `loop_frames` must be in its documented inclusive range. Validation @@ -57,6 +82,63 @@ impl AlienConfig { } } +impl From for AlienConfig { + fn from(patch: AlienPatch) -> Self { + let mut config = Self::default(); + config.merge_patch(patch); + config + } +} + +/// Partial changes for [`AlienConfig`]. +/// +/// Only fields that are `Some` overwrite the target fields in +/// [`AlienConfig::merge_patch`]. All fields are `None` by default. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + derive(serde::Serialize, serde::Deserialize, tsify::Tsify), + serde(default, rename_all = "camelCase") +)] +pub struct AlienPatch { + /// Selects reversed playback instead of the direct input. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional) + )] + 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) + )] + pub loop_frames: Option, +} + +impl AlienPatch { + /// Returns an empty patch with all fields set to `None`. + pub const fn new() -> Self { + Self { + enabled: None, + loop_frames: None, + } + } + + /// Sets `enabled` on this patch. + pub const fn with_enabled(mut self, enabled: bool) -> Self { + self.enabled = Some(enabled); + self + } + + /// Sets `loop_frames` on this patch, 1..=96000. + pub const fn with_loop_frames(mut self, loop_frames: u32) -> Self { + self.loop_frames = Some(loop_frames); + self + } +} + /// A stereo ring recorder with a reverse reader and an independent loop /// phase. #[derive(Debug)] diff --git a/src/effects/punch.rs b/src/effects/punch.rs index 867dc09..d1c4ad1 100644 --- a/src/effects/punch.rs +++ b/src/effects/punch.rs @@ -67,6 +67,58 @@ impl Default for PunchConfig { } } impl PunchConfig { + /// Returns a copy with `enabled` set to the given value. + pub const fn with_enabled(mut self, enabled: bool) -> Self { + self.enabled = enabled; + self + } + + /// Returns a copy with `gain_db` set to the given value, -96..=12. + pub const fn with_gain_db(mut self, gain_db: f32) -> Self { + self.gain_db = gain_db; + self + } + + /// Returns a copy with `impact` set to the given value, 0..=1. + pub const fn with_impact(mut self, impact: f32) -> Self { + self.impact = impact; + self + } + + /// Returns a copy with `ceiling_db` set to the given value, -96..=0. + pub const fn with_ceiling_db(mut self, ceiling_db: f32) -> Self { + self.ceiling_db = ceiling_db; + self + } + + /// Returns a copy with `attack_ms` set to the given value, 0.01..=5000. + pub const fn with_attack_ms(mut self, attack_ms: f32) -> Self { + self.attack_ms = attack_ms; + self + } + + /// Copies each present field of `patch` into this configuration. + /// + /// Fields that are `None` do not change. This method does not validate the + /// result. + pub fn merge_patch(&mut self, patch: PunchPatch) { + if let Some(enabled) = patch.enabled { + self.enabled = enabled; + } + if let Some(gain_db) = patch.gain_db { + self.gain_db = gain_db; + } + if let Some(impact) = patch.impact { + self.impact = impact; + } + if let Some(ceiling_db) = patch.ceiling_db { + self.ceiling_db = ceiling_db; + } + if let Some(attack_ms) = patch.attack_ms { + self.attack_ms = attack_ms; + } + } + /// Validates all fields, also when Punch is disabled. /// /// The floating-point controls must be finite and in their documented @@ -85,6 +137,105 @@ impl PunchConfig { } } +impl From for PunchConfig { + fn from(patch: PunchPatch) -> Self { + let mut config = Self::default(); + config.merge_patch(patch); + config + } +} + +/// Partial changes for [`PunchConfig`]. +/// +/// Only fields that are `Some` overwrite the target fields in +/// [`PunchConfig::merge_patch`]. All fields are `None` by default. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + derive(serde::Serialize, serde::Deserialize, tsify::Tsify), + serde(default, rename_all = "camelCase") +)] +pub struct PunchPatch { + /// Enables or disables this input stage. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional) + )] + 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) + )] + 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) + )] + 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) + )] + pub ceiling_db: Option, + /// The attack half-life of the peak follower in milliseconds, 0.01..=5000. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional) + )] + pub attack_ms: Option, +} + +impl PunchPatch { + /// Returns an empty patch with all fields set to `None`. + pub const fn new() -> Self { + Self { + enabled: None, + gain_db: None, + impact: None, + ceiling_db: None, + attack_ms: None, + } + } + + /// Sets `enabled` on this patch. + pub const fn with_enabled(mut self, enabled: bool) -> Self { + self.enabled = Some(enabled); + self + } + + /// Sets `gain_db` on this patch, -96..=12. + pub const fn with_gain_db(mut self, gain_db: f32) -> Self { + self.gain_db = Some(gain_db); + self + } + + /// Sets `impact` on this patch, 0..=1. + pub const fn with_impact(mut self, impact: f32) -> Self { + self.impact = Some(impact); + self + } + + /// Sets `ceiling_db` on this patch, -96..=0. + pub const fn with_ceiling_db(mut self, ceiling_db: f32) -> Self { + self.ceiling_db = Some(ceiling_db); + self + } + + /// Sets `attack_ms` on this patch, 0.01..=5000. + pub const fn with_attack_ms(mut self, attack_ms: f32) -> Self { + self.attack_ms = Some(attack_ms); + self + } +} + /// 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 fe60cd4..aff1bcc 100644 --- a/src/effects/reverb.rs +++ b/src/effects/reverb.rs @@ -96,6 +96,67 @@ impl Default for ReverbConfig { } } impl ReverbConfig { + /// Returns a copy with `enabled` set to the given value. + pub const fn with_enabled(mut self, enabled: bool) -> Self { + self.enabled = enabled; + self + } + + /// Returns a copy with `mode` set to the given value. + pub const fn with_mode(mut self, mode: ReverbMode) -> Self { + self.mode = mode; + self + } + + /// Returns a copy with `mix` set to the given value, 0..=1. + pub const fn with_mix(mut self, mix: f32) -> Self { + self.mix = mix; + self + } + + /// Returns a copy with `diffusion` set to the given value, 0..=1. + pub const fn with_diffusion(mut self, diffusion: f32) -> Self { + self.diffusion = diffusion; + self + } + + /// Returns a copy with `decay` set to the given value, 0..=1. + pub const fn with_decay(mut self, decay: f32) -> Self { + self.decay = decay; + self + } + + /// Returns a copy with `brightness_hz` set to the given value, 80..=20000. + pub const fn with_brightness_hz(mut self, brightness_hz: f32) -> Self { + self.brightness_hz = brightness_hz; + self + } + + /// Copies each present field of `patch` into this configuration. + /// + /// Fields that are `None` do not change. This method does not validate the + /// result. + pub fn merge_patch(&mut self, patch: ReverbPatch) { + if let Some(enabled) = patch.enabled { + self.enabled = enabled; + } + if let Some(mode) = patch.mode { + self.mode = mode; + } + if let Some(mix) = patch.mix { + self.mix = mix; + } + if let Some(diffusion) = patch.diffusion { + self.diffusion = diffusion; + } + if let Some(decay) = patch.decay { + self.decay = decay; + } + if let Some(brightness_hz) = patch.brightness_hz { + self.brightness_hz = brightness_hz; + } + } + /// Validates all fields, also when the stage is disabled or the selected /// mode does not use a field. /// @@ -115,6 +176,119 @@ impl ReverbConfig { } } +impl From for ReverbConfig { + fn from(patch: ReverbPatch) -> Self { + let mut config = Self::default(); + config.merge_patch(patch); + config + } +} + +/// Partial changes for [`ReverbConfig`]. +/// +/// Only fields that are `Some` overwrite the target fields in +/// [`ReverbConfig::merge_patch`]. All fields are `None` by default. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + derive(serde::Serialize, serde::Deserialize, tsify::Tsify), + serde(default, rename_all = "camelCase") +)] +pub struct ReverbPatch { + /// Enables or disables the selected network. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional) + )] + pub enabled: Option, + /// The topology of the delay network. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional) + )] + 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) + )] + 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) + )] + 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) + )] + 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) + )] + pub brightness_hz: Option, +} + +impl ReverbPatch { + /// Returns an empty patch with all fields set to `None`. + pub const fn new() -> Self { + Self { + enabled: None, + mode: None, + mix: None, + diffusion: None, + decay: None, + brightness_hz: None, + } + } + + /// Sets `enabled` on this patch. + pub const fn with_enabled(mut self, enabled: bool) -> Self { + self.enabled = Some(enabled); + self + } + + /// Sets `mode` on this patch. + pub const fn with_mode(mut self, mode: ReverbMode) -> Self { + self.mode = Some(mode); + self + } + + /// Sets `mix` on this patch, 0..=1. + pub const fn with_mix(mut self, mix: f32) -> Self { + self.mix = Some(mix); + self + } + + /// Sets `diffusion` on this patch, 0..=1. + pub const fn with_diffusion(mut self, diffusion: f32) -> Self { + self.diffusion = Some(diffusion); + self + } + + /// Sets `decay` on this patch, 0..=1. + pub const fn with_decay(mut self, decay: f32) -> Self { + self.decay = Some(decay); + self + } + + /// Sets `brightness_hz` on this patch, 80..=20000. + pub const fn with_brightness_hz(mut self, brightness_hz: f32) -> Self { + self.brightness_hz = Some(brightness_hz); + self + } +} + /// 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 9721ced..ae86bcc 100644 --- a/src/effects/warm.rs +++ b/src/effects/warm.rs @@ -40,6 +40,31 @@ impl Default for WarmConfig { } } impl WarmConfig { + /// Returns a copy with `enabled` set to the given value. + pub const fn with_enabled(mut self, enabled: bool) -> Self { + self.enabled = enabled; + self + } + + /// Returns a copy with `drive_db` set to the given value, 0..=6. + pub const fn with_drive_db(mut self, drive_db: f32) -> Self { + self.drive_db = drive_db; + self + } + + /// Copies each present field of `patch` into this configuration. + /// + /// Fields that are `None` do not change. This method does not validate the + /// result. + pub fn merge_patch(&mut self, patch: WarmPatch) { + if let Some(enabled) = patch.enabled { + self.enabled = enabled; + } + if let Some(drive_db) = patch.drive_db { + self.drive_db = drive_db; + } + } + /// Validates all fields, also when Warm is disabled. /// /// `drive_db` must be finite and in its documented inclusive range. @@ -55,6 +80,63 @@ impl WarmConfig { } } +impl From for WarmConfig { + fn from(patch: WarmPatch) -> Self { + let mut config = Self::default(); + config.merge_patch(patch); + config + } +} + +/// Partial changes for [`WarmConfig`]. +/// +/// Only fields that are `Some` overwrite the target fields in +/// [`WarmConfig::merge_patch`]. All fields are `None` by default. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + derive(serde::Serialize, serde::Deserialize, tsify::Tsify), + serde(default, rename_all = "camelCase") +)] +pub struct WarmPatch { + /// Enables or disables the saturation stage. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional) + )] + 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) + )] + pub drive_db: Option, +} + +impl WarmPatch { + /// Returns an empty patch with all fields set to `None`. + pub const fn new() -> Self { + Self { + enabled: None, + drive_db: None, + } + } + + /// Sets `enabled` on this patch. + pub const fn with_enabled(mut self, enabled: bool) -> Self { + self.enabled = Some(enabled); + self + } + + /// Sets `drive_db` on this patch, 0..=6. + pub const fn with_drive_db(mut self, drive_db: f32) -> Self { + self.drive_db = Some(drive_db); + self + } +} + /// An adaptive asymmetric saturator with one persistent high-pass output /// filter. #[derive(Debug)] diff --git a/src/events.rs b/src/events.rs index e1c975c..09f6543 100644 --- a/src/events.rs +++ b/src/events.rs @@ -1,21 +1,21 @@ //! Controls for a block, which the processor validates before any change. 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::alien::{AlienConfig, AlienPatch}; +use crate::effects::punch::{PunchConfig, PunchPatch}; +use crate::effects::reverb::{ReverbConfig, ReverbPatch}; +use crate::effects::warm::{WarmConfig, WarmPatch}; use crate::midi::MidiEvent; -use crate::{Error, EventProblem, ProcessorConfig, ResynthesisConfig}; +use crate::resynthesis::ResynthesisPatch; +use crate::{Error, EventProblem, ProcessorConfig, ProcessorPatch, ResynthesisConfig}; /// 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. Whole-stage events replace all settings of that stage. Patch events +/// merge only their `Some` fields onto the active configuration. Configuration +/// changes have the same effects on state as [`crate::Processor::set_config`]. #[derive(Clone, Copy, Debug, PartialEq)] #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), @@ -25,16 +25,28 @@ use crate::{Error, EventProblem, ProcessorConfig, ResynthesisConfig}; pub enum ControlEvent { /// This event replaces the full configuration. Configure(ProcessorConfig), + /// This event merges partial changes onto the full configuration. + Patch(ProcessorPatch), /// This event replaces the resynthesis configuration. Resynthesis(ResynthesisConfig), + /// This event merges partial changes onto the resynthesis configuration. + ResynthesisPatch(ResynthesisPatch), /// This event replaces the Punch configuration. Punch(PunchConfig), + /// This event merges partial changes onto the Punch configuration. + PunchPatch(PunchPatch), /// This event replaces the Warm configuration. Warm(WarmConfig), + /// This event merges partial changes onto the Warm configuration. + WarmPatch(WarmPatch), /// This event replaces the Alien configuration. Alien(AlienConfig), + /// This event merges partial changes onto the Alien configuration. + AlienPatch(AlienPatch), /// This event replaces the reverb configuration. Reverb(ReverbConfig), + /// This event merges partial changes onto the reverb configuration. + ReverbPatch(ReverbPatch), /// This event sets the final linear gain, 0..=64. /// /// The quantization and the mute behavior are the same as for @@ -66,21 +78,85 @@ impl ControlEvent { /// Checks the configuration or MIDI ranges of the event, and does not /// apply the event. /// + /// For patch variants, this method merges the patch onto + /// [`ProcessorConfig::default`] before validation. During a process call, + /// the block preflight merges each patch onto a copy of the active + /// configuration in slice order. + /// /// # 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, patch 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> { + let mut config = ProcessorConfig::default(); + self.apply_and_validate(&mut config) + } + + /// Simulates the event on `config` and validates the changed stage or MIDI + /// payload. + fn apply_and_validate(self, config: &mut ProcessorConfig) -> Result<(), Error> { match self { - Self::Configure(config) => config.validate(), - Self::Resynthesis(config) => config.validate(), - Self::Punch(config) => config.validate(), - Self::Warm(config) => config.validate(), - Self::Alien(config) => config.validate(), - Self::Reverb(config) => config.validate(), - Self::OutputGain(gain) => validate_output_gain(gain), + Self::Configure(value) => { + value.validate()?; + *config = value; + Ok(()) + } + Self::Patch(patch) => { + config.merge_patch(patch); + config.validate() + } + Self::Resynthesis(value) => { + value.validate()?; + config.resynthesis = value; + Ok(()) + } + Self::ResynthesisPatch(patch) => { + config.resynthesis.merge_patch(patch); + config.resynthesis.validate() + } + Self::Punch(value) => { + value.validate()?; + config.punch = value; + Ok(()) + } + Self::PunchPatch(patch) => { + config.punch.merge_patch(patch); + config.punch.validate() + } + Self::Warm(value) => { + value.validate()?; + config.warm = value; + Ok(()) + } + Self::WarmPatch(patch) => { + config.warm.merge_patch(patch); + config.warm.validate() + } + Self::Alien(value) => { + value.validate()?; + config.alien = value; + Ok(()) + } + Self::AlienPatch(patch) => { + config.alien.merge_patch(patch); + config.alien.validate() + } + Self::Reverb(value) => { + value.validate()?; + config.reverb = value; + Ok(()) + } + Self::ReverbPatch(patch) => { + config.reverb.merge_patch(patch); + config.reverb.validate() + } + Self::OutputGain(gain) => { + validate_output_gain(gain)?; + config.output_gain = gain; + Ok(()) + } Self::Midi(event) | Self::CorrectionMidi(event) => event.validate(), Self::Reset => Ok(()), } @@ -136,11 +212,17 @@ impl ValidatedEvent { impl<'a> ValidatedEvents<'a> { /// Checks the offsets, the order and the payloads, in slice order. /// - /// If an event fails, returns an error with the zero-based index of the - /// 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 { + /// Configuration replacements and patches apply to the stack copy `config` + /// in slice order, so later events validate against earlier changes in the + /// same block. If an event fails, returns an error with the zero-based + /// index of the 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, + mut config: ProcessorConfig, + ) -> Result { let mut previous = 0; for (index, event) in events.iter().enumerate() { let problem = if event.offset >= frames { @@ -148,7 +230,7 @@ impl<'a> ValidatedEvents<'a> { } else if event.offset < previous { Some(EventProblem::OffsetDecreasing) } else { - match event.event.validate() { + match event.event.apply_and_validate(&mut config) { Ok(()) => None, Err(Error::InvalidConfig { field, problem }) => { Some(EventProblem::Config { field, problem }) diff --git a/src/formant.rs b/src/formant.rs index 5072ee1..993a4c6 100644 --- a/src/formant.rs +++ b/src/formant.rs @@ -84,6 +84,59 @@ impl Default for FormantConfig { } } impl FormantConfig { + /// Returns a copy with `enabled` set to the given value. + pub const fn with_enabled(mut self, enabled: bool) -> Self { + self.enabled = enabled; + self + } + + /// Returns a copy with `width` set to the given value, 0.5..=2. + pub const fn with_width(mut self, width: f32) -> Self { + self.width = width; + self + } + + /// Returns a copy with `stretch` set to the given value, 0.5..=2. + pub const fn with_stretch(mut self, stretch: f32) -> Self { + self.stretch = stretch; + self + } + + /// Returns a copy with `aspiration_mix` set to the given value, 0..=1. + pub const fn with_aspiration_mix(mut self, aspiration_mix: f32) -> Self { + self.aspiration_mix = aspiration_mix; + self + } + + /// Returns a copy with `aspiration_cutoff_hz` set to the given value, + /// 500..=10000. + pub const fn with_aspiration_cutoff_hz(mut self, aspiration_cutoff_hz: f32) -> Self { + self.aspiration_cutoff_hz = aspiration_cutoff_hz; + self + } + + /// Copies each present field of `patch` into this configuration. + /// + /// Fields that are `None` do not change. This method does not validate the + /// result. + pub fn merge_patch(&mut self, patch: FormantPatch) { + if let Some(enabled) = patch.enabled { + self.enabled = enabled; + } + if let Some(width) = patch.width { + self.width = width; + } + if let Some(stretch) = patch.stretch { + self.stretch = stretch; + } + if let Some(aspiration_mix) = patch.aspiration_mix { + self.aspiration_mix = aspiration_mix; + } + if let Some(aspiration_cutoff_hz) = patch.aspiration_cutoff_hz { + self.aspiration_cutoff_hz = aspiration_cutoff_hz; + } + } + /// Validates all fields, also if the formant stage is disabled. /// /// Each floating-point control must be finite and in its documented @@ -104,6 +157,105 @@ impl FormantConfig { } } +impl From for FormantConfig { + fn from(patch: FormantPatch) -> Self { + let mut config = Self::default(); + config.merge_patch(patch); + config + } +} + +/// Partial changes for [`FormantConfig`]. +/// +/// Only fields that are `Some` overwrite the target fields in +/// [`FormantConfig::merge_patch`]. All fields are `None` by default. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + derive(serde::Serialize, serde::Deserialize, tsify::Tsify), + serde(default, rename_all = "camelCase") +)] +pub struct FormantPatch { + /// Enables or disables formant analysis and synthesis. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional) + )] + 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) + )] + 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) + )] + 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) + )] + 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) + )] + pub aspiration_cutoff_hz: Option, +} + +impl FormantPatch { + /// Returns an empty patch with all fields set to `None`. + pub const fn new() -> Self { + Self { + enabled: None, + width: None, + stretch: None, + aspiration_mix: None, + aspiration_cutoff_hz: None, + } + } + + /// Sets `enabled` on this patch. + pub const fn with_enabled(mut self, enabled: bool) -> Self { + self.enabled = Some(enabled); + self + } + + /// Sets `width` on this patch, 0.5..=2. + pub const fn with_width(mut self, width: f32) -> Self { + self.width = Some(width); + self + } + + /// Sets `stretch` on this patch, 0.5..=2. + pub const fn with_stretch(mut self, stretch: f32) -> Self { + self.stretch = Some(stretch); + self + } + + /// Sets `aspiration_mix` on this patch, 0..=1. + pub const fn with_aspiration_mix(mut self, aspiration_mix: f32) -> Self { + self.aspiration_mix = Some(aspiration_mix); + self + } + + /// Sets `aspiration_cutoff_hz` on this patch, 500..=10000. + pub const fn with_aspiration_cutoff_hz(mut self, aspiration_cutoff_hz: f32) -> Self { + self.aspiration_cutoff_hz = Some(aspiration_cutoff_hz); + self + } +} + /// The number of frames of input history for analysis and synthesis. The /// value is equal to the resynthesis history length. pub(crate) const HISTORY_FRAMES: usize = 11568; diff --git a/src/harmony.rs b/src/harmony.rs index 67b7111..aae29a9 100644 --- a/src/harmony.rs +++ b/src/harmony.rs @@ -9,7 +9,7 @@ mod chords; use crate::error::{check_count, check_range}; use crate::midi::{note_period, velocity_gain, MidiEvent}; use crate::numeric::fixed::{Q12, Q14, Q6}; -use crate::scale::PitchClass; +use crate::scale::{NoteMask, PitchClass}; use crate::{Error, SampleRate}; use chords::SCALE_TONES; @@ -111,6 +111,25 @@ pub enum HarmonyScale { MinorMajorSeventh, } +impl HarmonyScale { + /// Returns the pitch classes of this scale, with `key` as the tonic. + /// + /// Each entry in the scale table enables one pitch class relative to + /// `key`. [`Self::MajorWithoutSeventh`] repeats its sixth degree, so the + /// returned mask enables six pitch classes. + pub const fn note_mask(self, key: PitchClass) -> NoteMask { + let mut notes = [false; 12]; + let tones = SCALE_TONES[self as usize]; + let root = key.semitone() as usize; + let mut i = 0; + while i < tones.len() { + notes[(root + tones[i] as usize) % 12] = true; + i += 1; + } + NoteMask::new(notes) + } +} + /// A named chord for [`HarmonySource::ChordByName`]. /// /// Each variant lists the semitones above the root. These values do not @@ -356,6 +375,131 @@ impl Default for HarmonyConfig { } impl HarmonyConfig { + /// Returns a copy with `source` set to the given value. + pub const fn with_source(mut self, source: HarmonySource) -> Self { + self.source = source; + self + } + + /// Returns a copy with `key` set to the given value. + pub const fn with_key(mut self, key: PitchClass) -> Self { + self.key = key; + self + } + + /// Returns a copy with `scale` set to the given value. + pub const fn with_scale(mut self, scale: HarmonyScale) -> Self { + self.scale = scale; + self + } + + /// Returns a copy with `chromatic_intervals` set to the given array, each + /// element in -24..=24. + pub const fn with_chromatic_intervals( + mut self, + chromatic_intervals: [i8; HARMONY_VOICES], + ) -> Self { + self.chromatic_intervals = chromatic_intervals; + self + } + + /// Returns a copy with `diatonic_intervals` set to the given array, each + /// element in -14..=14. + pub const fn with_diatonic_intervals( + mut self, + diatonic_intervals: [i8; HARMONY_VOICES], + ) -> Self { + self.diatonic_intervals = diatonic_intervals; + self + } + + /// Returns a copy with `chord` set to the given value. + pub const fn with_chord(mut self, chord: ChordName) -> Self { + self.chord = chord; + self + } + + /// Returns a copy with `degree` set to the given value. + pub const fn with_degree(mut self, degree: ChordDegree) -> Self { + self.degree = degree; + self + } + + /// Returns a copy with `inversion` set to the given value. + pub const fn with_inversion(mut self, inversion: Inversion) -> Self { + self.inversion = inversion; + self + } + + /// Returns a copy with `register_percent` set to the given value, + /// 0..=100%. + pub const fn with_register_percent(mut self, register_percent: f32) -> Self { + self.register_percent = register_percent; + self + } + + /// Returns a copy with `voicing_spread_percent` set to the given value, + /// 0..=100%. + pub const fn with_voicing_spread_percent(mut self, voicing_spread_percent: f32) -> Self { + self.voicing_spread_percent = voicing_spread_percent; + self + } + + /// Returns a copy with `portamento_ms` set to the given value, 0..=10000. + pub const fn with_portamento_ms(mut self, portamento_ms: f32) -> Self { + self.portamento_ms = portamento_ms; + self + } + + /// Returns a copy with `voices` set to the given value, 0..=4. + pub const fn with_voices(mut self, voices: u8) -> Self { + self.voices = voices; + self + } + + /// Copies each present field of `patch` into this configuration. + /// + /// Fields that are `None` do not change. An interval array that is `Some` + /// replaces all four entries. This method does not validate the result. + pub fn merge_patch(&mut self, patch: HarmonyPatch) { + if let Some(source) = patch.source { + self.source = source; + } + if let Some(key) = patch.key { + self.key = key; + } + if let Some(scale) = patch.scale { + self.scale = scale; + } + if let Some(chromatic_intervals) = patch.chromatic_intervals { + self.chromatic_intervals = chromatic_intervals; + } + if let Some(diatonic_intervals) = patch.diatonic_intervals { + self.diatonic_intervals = diatonic_intervals; + } + if let Some(chord) = patch.chord { + self.chord = chord; + } + if let Some(degree) = patch.degree { + self.degree = degree; + } + if let Some(inversion) = patch.inversion { + self.inversion = inversion; + } + if let Some(register_percent) = patch.register_percent { + self.register_percent = register_percent; + } + if let Some(voicing_spread_percent) = patch.voicing_spread_percent { + self.voicing_spread_percent = voicing_spread_percent; + } + if let Some(portamento_ms) = patch.portamento_ms { + self.portamento_ms = portamento_ms; + } + if let Some(voices) = patch.voices { + self.voices = voices; + } + } + /// Validates all fields, which includes the fields that the selected /// source does not use. /// @@ -393,6 +537,210 @@ impl HarmonyConfig { } } +impl From for HarmonyConfig { + fn from(patch: HarmonyPatch) -> Self { + let mut config = Self::default(); + config.merge_patch(patch); + config + } +} + +/// Partial changes for [`HarmonyConfig`]. +/// +/// Only fields that are `Some` overwrite the target fields in +/// [`HarmonyConfig::merge_patch`]. All fields are `None` by default. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + derive(serde::Serialize, serde::Deserialize, tsify::Tsify), + serde(default, rename_all = "camelCase") +)] +pub struct HarmonyPatch { + /// The pitch source for the four harmony voices. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional) + )] + pub source: Option, + /// The pitch class of the tonic. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional) + )] + pub key: Option, + /// The scale for smart intervals and degree chords. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional) + )] + 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]") + )] + 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]") + )] + pub diatonic_intervals: Option<[i8; HARMONY_VOICES]>, + /// The named chord for [`HarmonySource::ChordByName`]. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional) + )] + pub chord: Option, + /// The chord on a scale degree for [`HarmonySource::ChordByDegree`]. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional) + )] + pub degree: Option, + /// The inversion for named chords and degree chords. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional) + )] + 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) + )] + pub register_percent: Option, + /// The chord voicing from close to open, 0..=100%. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional) + )] + pub voicing_spread_percent: Option, + /// The half-life of the target-period smoothing in milliseconds, + /// 0..=10000. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional) + )] + 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) + )] + pub voices: Option, +} + +impl HarmonyPatch { + /// Returns an empty patch with all fields set to `None`. + pub const fn new() -> Self { + Self { + source: None, + key: None, + scale: None, + chromatic_intervals: None, + diatonic_intervals: None, + chord: None, + degree: None, + inversion: None, + register_percent: None, + voicing_spread_percent: None, + portamento_ms: None, + voices: None, + } + } + + /// Sets `source` on this patch. + pub const fn with_source(mut self, source: HarmonySource) -> Self { + self.source = Some(source); + self + } + + /// Sets `key` on this patch. + pub const fn with_key(mut self, key: PitchClass) -> Self { + self.key = Some(key); + self + } + + /// Sets `scale` on this patch. + pub const fn with_scale(mut self, scale: HarmonyScale) -> Self { + self.scale = Some(scale); + self + } + + /// Sets `chromatic_intervals` on this patch, each element in -24..=24. + pub const fn with_chromatic_intervals( + mut self, + chromatic_intervals: [i8; HARMONY_VOICES], + ) -> Self { + self.chromatic_intervals = Some(chromatic_intervals); + self + } + + /// Sets `diatonic_intervals` on this patch, each element in -14..=14. + pub const fn with_diatonic_intervals( + mut self, + diatonic_intervals: [i8; HARMONY_VOICES], + ) -> Self { + self.diatonic_intervals = Some(diatonic_intervals); + self + } + + /// Sets `chord` on this patch. + pub const fn with_chord(mut self, chord: ChordName) -> Self { + self.chord = Some(chord); + self + } + + /// Sets `degree` on this patch. + pub const fn with_degree(mut self, degree: ChordDegree) -> Self { + self.degree = Some(degree); + self + } + + /// Sets `inversion` on this patch. + pub const fn with_inversion(mut self, inversion: Inversion) -> Self { + self.inversion = Some(inversion); + self + } + + /// Sets `register_percent` on this patch, 0..=100%. + pub const fn with_register_percent(mut self, register_percent: f32) -> Self { + self.register_percent = Some(register_percent); + self + } + + /// Sets `voicing_spread_percent` on this patch, 0..=100%. + pub const fn with_voicing_spread_percent(mut self, voicing_spread_percent: f32) -> Self { + self.voicing_spread_percent = Some(voicing_spread_percent); + self + } + + /// Sets `portamento_ms` on this patch, 0..=10000. + pub const fn with_portamento_ms(mut self, portamento_ms: f32) -> Self { + self.portamento_ms = Some(portamento_ms); + self + } + + /// Sets `voices` on this patch, 0..=4. + pub const fn with_voices(mut self, voices: u8) -> Self { + self.voices = Some(voices); + self + } +} + /// The prepared controller of periods and gains, and the MIDI allocator, for /// four voices. /// diff --git a/src/index.ts b/src/index.ts index da35a57..d949954 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,15 +1,29 @@ /** * The shared ESM entry point for browsers and Node.js. * - * Call `loadTunelet()` before you construct processors or read the default - * configuration. Both environments use the same generated bindings and the - * same Wasm binary. This module re-exports all named exports of the module - * that wasm-bindgen generates, which include `Tunelet`, `defaultConfig`, - * `initSync` and the configuration, event and feedback types. + * Call `loadTunelet()` before you construct processors or call the helper + * functions. Both environments use the same generated bindings and the same + * Wasm binary. This module re-exports all named exports of the module that + * wasm-bindgen generates, which include `Tunelet`, `defaultConfig`, + * `noteMaskFromKeyScale`, `parseMidiBytes`, `initSync` and the configuration, + * patch, event and feedback types. */ -import init, { initSync } from "../pkg/tunelet.js"; +import init, { + Tunelet, + defaultConfig, + initSync, + noteMaskFromKeyScale, + parseMidiBytes, +} from "../pkg/tunelet.js"; import type { InitInput, InitOutput } from "../pkg/tunelet.js"; +export { + Tunelet, + defaultConfig, + initSync, + noteMaskFromKeyScale, + parseMidiBytes, +}; export * from "../pkg/tunelet.js"; /** The shared initialization promise, which a failure clears. */ diff --git a/src/lib.rs b/src/lib.rs index 0e29119..033dd71 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -9,20 +9,20 @@ //! # Preparing and configuring //! //! [`PrepareConfig`] sets the sample rate. It also sets the maximum number of -//! frames for one process call or one drain call. To make a -//! [`ProcessorConfig`], start from its default value and change its public -//! stage fields. Then give it to [`Processor::new`]. All configuration ranges -//! are inclusive, unless the documentation tells you differently. -//! Floating-point controls must be finite. +//! frames for one process call or one drain call. To configure a processor, +//! give a [`ProcessorConfig`] or a partial [`ProcessorPatch`] to +//! [`Processor::new`]. Each `*Config` and `*Patch` type provides `with_*` +//! builders. All configuration ranges are inclusive, unless the documentation +//! tells you differently. Floating-point controls must be finite. //! //! Validation also examines disabled stages and the controls of voice modes //! 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. -//! 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. +//! change until [`Processor::set_config`], [`Processor::update_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. //! //! # Audio and timed controls //! @@ -121,19 +121,22 @@ mod scale; #[cfg(all(feature = "wasm", target_arch = "wasm32"))] pub mod wasm; -pub use config::{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::{PrepareConfig, ProcessorConfig, ProcessorPatch, SampleRate}; +pub use effects::alien::{AlienConfig, AlienPatch}; +pub use effects::punch::{PunchConfig, PunchPatch}; +pub use effects::reverb::{ReverbConfig, ReverbMode, ReverbPatch}; +pub use effects::warm::{WarmConfig, WarmPatch}; pub use error::{ConfigProblem, Error, EventProblem}; pub use events::{ControlEvent, TimedEvent}; -pub use formant::FormantConfig; +pub use formant::{FormantConfig, FormantPatch}; pub use harmony::{ - ChordDegree, ChordName, HarmonyConfig, HarmonyScale, HarmonySource, Inversion, HARMONY_VOICES, + ChordDegree, ChordName, HarmonyConfig, HarmonyPatch, HarmonyScale, HarmonySource, Inversion, + HARMONY_VOICES, }; pub use midi::MidiEvent; -pub use pitch::PitchConfig; +pub use pitch::{PitchConfig, PitchPatch}; pub use processor::{Feedback, Processor, Telemetry}; -pub use resynthesis::{CorrectionConfig, MultiVoiceMode, ResynthesisConfig}; +pub use resynthesis::{ + CorrectionConfig, CorrectionPatch, MultiVoiceMode, ResynthesisConfig, ResynthesisPatch, +}; pub use scale::{CorrectionScale, NoteMask, PitchClass}; diff --git a/src/pitch.rs b/src/pitch.rs index 6b682ca..0688eec 100644 --- a/src/pitch.rs +++ b/src/pitch.rs @@ -52,6 +52,42 @@ impl Default for PitchConfig { } impl PitchConfig { + /// Returns a copy with `threshold` set to the given value, 0.002..=0.2. + pub const fn with_threshold(mut self, threshold: f32) -> Self { + self.threshold = threshold; + self + } + + /// Returns a copy with `min_frequency_hz` set to the given value, + /// 40..=2000. + pub const fn with_min_frequency_hz(mut self, min_frequency_hz: f32) -> Self { + self.min_frequency_hz = min_frequency_hz; + self + } + + /// Returns a copy with `max_frequency_hz` set to the given value, + /// 40..=2000. + pub const fn with_max_frequency_hz(mut self, max_frequency_hz: f32) -> Self { + self.max_frequency_hz = max_frequency_hz; + self + } + + /// Copies each present field of `patch` into this configuration. + /// + /// Fields that are `None` do not change. This method does not validate the + /// result. + pub fn merge_patch(&mut self, patch: PitchPatch) { + if let Some(threshold) = patch.threshold { + self.threshold = threshold; + } + if let Some(min_frequency_hz) = patch.min_frequency_hz { + self.min_frequency_hz = min_frequency_hz; + } + if let Some(max_frequency_hz) = patch.max_frequency_hz { + self.max_frequency_hz = max_frequency_hz; + } + } + /// Applies only the bounds for host reports to a kept estimate. /// /// If the estimate is not voiced or is out of range, the result is the @@ -93,6 +129,81 @@ impl PitchConfig { } } +impl From for PitchConfig { + fn from(patch: PitchPatch) -> Self { + let mut config = Self::default(); + config.merge_patch(patch); + config + } +} + +/// Partial changes for [`PitchConfig`]. +/// +/// Only fields that are `Some` overwrite the target fields in +/// [`PitchConfig::merge_patch`]. All fields are `None` by default. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + derive(serde::Serialize, serde::Deserialize, tsify::Tsify), + serde(default, rename_all = "camelCase") +)] +pub struct PitchPatch { + /// 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) + )] + pub threshold: Option, + /// The lower bound of the feedback in hertz (inclusive), 40..=2000. + /// + /// After the merge, it must be strictly less than `max_frequency_hz`. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional) + )] + pub min_frequency_hz: Option, + /// The upper bound of the feedback in hertz (inclusive), 40..=2000. + /// + /// After the merge, it must be strictly greater than `min_frequency_hz`. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional) + )] + pub max_frequency_hz: Option, +} + +impl PitchPatch { + /// Returns an empty patch with all fields set to `None`. + pub const fn new() -> Self { + Self { + threshold: None, + min_frequency_hz: None, + max_frequency_hz: None, + } + } + + /// Sets `threshold` on this patch, 0.002..=0.2. + pub const fn with_threshold(mut self, threshold: f32) -> Self { + self.threshold = Some(threshold); + self + } + + /// Sets `min_frequency_hz` on this patch, 40..=2000. + pub const fn with_min_frequency_hz(mut self, min_frequency_hz: f32) -> Self { + self.min_frequency_hz = Some(min_frequency_hz); + self + } + + /// Sets `max_frequency_hz` on this patch, 40..=2000. + pub const fn with_max_frequency_hz(mut self, max_frequency_hz: f32) -> Self { + self.max_frequency_hz = Some(max_frequency_hz); + self + } +} + /// 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 cc910f4..8c7d186 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -8,7 +8,7 @@ use crate::events::{ValidatedEvent, ValidatedEvents}; use crate::numeric::rng::RandomStream; use crate::numeric::NumericContext; use crate::resynthesis::{self, Resynthesis}; -use crate::{ControlEvent, Error, PrepareConfig, ProcessorConfig, TimedEvent}; +use crate::{ControlEvent, Error, PrepareConfig, ProcessorConfig, ProcessorPatch, TimedEvent}; /// A prepared vocal processor with state, mono input and stereo synthesis. /// @@ -85,10 +85,11 @@ impl Processor { /// Validates the settings, allocates histories and makes a new processor. /// /// Each processor is independent. `preparation` fixes the rate and the - /// block limit for each call. After construction, the audio, control, - /// feedback, reset and drain calls do not allocate, do not lock and do no - /// I/O. Audio histories, pitch reports and meters start clear. The random - /// stream starts from the low 32 bits of `random_seed`. + /// block limit for each call. `config` can be a [`ProcessorConfig`] or a + /// [`ProcessorPatch`] that merges onto [`ProcessorConfig::default`]. After + /// construction, the audio, control, feedback, reset and drain calls do + /// not allocate, do not lock and do no I/O. Audio histories, pitch reports + /// and meters start clear. The random stream starts from `random_seed`. /// /// Punch uses its default cached drive until the first window of 100 /// frames with Punch enabled. The initial note table of correction has the @@ -100,7 +101,15 @@ impl Processor { /// not valid. This check occurs before the allocation of the histories. /// The types of `preparation` already make sure that the block limit is /// not zero and that the sample rate is supported. - pub fn new(preparation: PrepareConfig, config: ProcessorConfig) -> Result { + pub fn new( + preparation: PrepareConfig, + config: impl Into, + ) -> Result { + Self::new_from_config(preparation, config.into()) + } + + /// Allocates a processor from a concrete configuration after validation. + fn new_from_config(preparation: PrepareConfig, config: ProcessorConfig) -> Result { config.validate()?; let rate = preparation.sample_rate; // Drive uses the default gain until the first 100-frame peak window. @@ -114,7 +123,7 @@ impl Processor { resynthesis: Box::new(Resynthesis::new(rate, config.resynthesis)), alien: Alien::new(config.alien), reverb: Reverb::new(rate, config.reverb), - numeric: NumericContext::new(config.resynthesis.random_seed as u32), + numeric: NumericContext::new(config.resynthesis.random_seed), peak: 0, input_peak: 0, output_peaks: [0; 2], @@ -467,8 +476,7 @@ impl Processor { /// Each successful call cancels a drain, also for an identical /// configuration. A change of reverb mode keeps the delay contents. If you /// disable Punch, Warm or reverb, the history of that stage stops. Alien - /// continues to record. A change in either half of the `u64` seed starts - /// the stream again, but the new sequence uses only the low 32 bits. + /// continues to record. /// /// # Errors /// @@ -480,6 +488,23 @@ impl Processor { Ok(()) } + /// Merges `patch` onto a copy of the active configuration, validates the + /// result and applies it. + /// + /// Fields that are `None` keep their current values. State retention and + /// drain cancellation follow [`set_config`](Self::set_config). + /// + /// # Errors + /// + /// Returns [`Error::InvalidConfig`] if a merged field is not valid. The + /// method returns this error before it changes any state, also an active + /// drain. + pub fn update_config(&mut self, patch: ProcessorPatch) -> Result<(), Error> { + let mut config = self.config; + config.merge_patch(patch); + self.set_config(config) + } + /// Applies a configuration that the public setter or the preflight checked. fn apply_config(&mut self, config: ProcessorConfig) { if self.config.punch != config.punch { @@ -500,7 +525,7 @@ impl Processor { self.last_resample_ratio = 0.0; } if self.config.resynthesis.random_seed != config.resynthesis.random_seed { - self.numeric.random = RandomStream::new(config.resynthesis.random_seed as u32); + self.numeric.random = RandomStream::new(config.resynthesis.random_seed); } if self.config.alien != config.alien { self.alien.set_config(config.alien); @@ -557,7 +582,7 @@ impl Processor { events: &'a [TimedEvent], ) -> Result, Error> { self.check_block(input.len())?; - ValidatedEvents::new(events, input.len()) + ValidatedEvents::new(events, input.len(), self.config) } /// Enforces the prepared block limit for each call. @@ -573,18 +598,24 @@ 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. + /// Whole-stage events replace one stage in the active configuration, and + /// patch events merge only their `Some` fields. 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::Patch(patch) => config.merge_patch(patch), ControlEvent::Resynthesis(value) => config.resynthesis = value, + ControlEvent::ResynthesisPatch(patch) => config.resynthesis.merge_patch(patch), ControlEvent::Punch(value) => config.punch = value, + ControlEvent::PunchPatch(patch) => config.punch.merge_patch(patch), ControlEvent::Warm(value) => config.warm = value, + ControlEvent::WarmPatch(patch) => config.warm.merge_patch(patch), ControlEvent::Alien(value) => config.alien = value, + ControlEvent::AlienPatch(patch) => config.alien.merge_patch(patch), ControlEvent::Reverb(value) => config.reverb = value, + ControlEvent::ReverbPatch(patch) => config.reverb.merge_patch(patch), ControlEvent::OutputGain(value) => config.output_gain = value, ControlEvent::Midi(event) => { self.resynthesis.apply_midi(event); @@ -707,8 +738,7 @@ impl Processor { #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), derive(serde::Serialize, serde::Deserialize, tsify::Tsify), - serde(rename_all = "camelCase"), - tsify(large_number_types_as_bigints) + serde(rename_all = "camelCase") )] pub struct Feedback { /// The pitch-correction ratio from the last processed frame, where 1 is @@ -765,13 +795,12 @@ pub struct Feedback { /// /// The count saturates at `u64::MAX`. Drain completion resets it in the /// last drain call. - pub processed_frames: u64, - /// The nominal resynthesis latency, as [`Processor::latency_frames`] gives. #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), - serde(serialize_with = "crate::wasm::serialize_frame_count"), - tsify(type = "number") + serde(serialize_with = "crate::wasm::serialize_frame_count") )] + pub processed_frames: u64, + /// The nominal resynthesis latency, as [`Processor::latency_frames`] gives. pub latency_frames: usize, } @@ -790,12 +819,15 @@ pub struct Feedback { #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), derive(serde::Serialize, serde::Deserialize, tsify::Tsify), - serde(rename_all = "camelCase"), - tsify(large_number_types_as_bigints) + serde(rename_all = "camelCase") )] pub struct Telemetry { /// The number of frames processed since construction or the last reset, /// as [`Feedback::processed_frames`] gives. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(serialize_with = "crate::wasm::serialize_frame_count") + )] pub processed_frames: u64, /// The largest absolute input sample in the window, divided by 32768. /// diff --git a/src/resynthesis.rs b/src/resynthesis.rs index 34e98fa..7944d2c 100644 --- a/src/resynthesis.rs +++ b/src/resynthesis.rs @@ -31,13 +31,13 @@ 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, FormantPatch, ANALYSIS_FRAMES}; +use crate::harmony::{HarmonyConfig, HarmonyPatch, HarmonyState, HARMONY_VOICES}; use crate::midi::MidiEvent; use crate::numeric::fixed::{Q12, Q14, Q6, Q8}; use crate::numeric::{ring, NumericContext, HISTORY}; use crate::pitch::tracker::PitchTracker; -use crate::pitch::{PitchConfig, PitchEstimate}; +use crate::pitch::{PitchConfig, PitchEstimate, PitchPatch}; use crate::scale::{CorrectionTable, NoteMask}; use crate::{Error, SampleRate}; use history::prepare_history; @@ -119,6 +119,41 @@ impl Default for CorrectionConfig { } impl CorrectionConfig { + /// Returns a copy with `enabled` set to the given value. + pub const fn with_enabled(mut self, enabled: bool) -> Self { + self.enabled = enabled; + self + } + + /// Returns a copy with `notes` set to the given mask. + pub const fn with_notes(mut self, notes: NoteMask) -> Self { + self.notes = notes; + self + } + + /// Returns a copy with `retune_ms` set to the given value, 0..=400. + pub const fn with_retune_ms(mut self, retune_ms: f32) -> Self { + self.retune_ms = retune_ms; + self + } + + /// Copies each present field of `patch` into this configuration. + /// + /// Fields that are `None` do not change. A `notes` mask that is `Some` + /// replaces all twelve pitch-class flags. This method does not validate + /// the result. + pub fn merge_patch(&mut self, patch: CorrectionPatch) { + if let Some(enabled) = patch.enabled { + self.enabled = enabled; + } + if let Some(notes) = patch.notes { + self.notes = notes; + } + if let Some(retune_ms) = patch.retune_ms { + self.retune_ms = retune_ms; + } + } + /// Validates all fields, also if correction is disabled. /// /// All values of `enabled` and `notes` are valid. `retune_ms` must be @@ -139,6 +174,77 @@ impl CorrectionConfig { } } +impl From for CorrectionConfig { + fn from(patch: CorrectionPatch) -> Self { + let mut config = Self::default(); + config.merge_patch(patch); + config + } +} + +/// Partial changes for [`CorrectionConfig`]. +/// +/// Only fields that are `Some` overwrite the target fields in +/// [`CorrectionConfig::merge_patch`]. All fields are `None` by default. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + derive(serde::Serialize, serde::Deserialize, tsify::Tsify), + serde(default, rename_all = "camelCase") +)] +pub struct CorrectionPatch { + /// Enables or disables the selection of correction targets. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional) + )] + pub enabled: Option, + /// The configured target pitch classes. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional) + )] + pub notes: Option, + /// The half-life of the smoothing in milliseconds, 0..=400. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional) + )] + pub retune_ms: Option, +} + +impl CorrectionPatch { + /// Returns an empty patch with all fields set to `None`. + pub const fn new() -> Self { + Self { + enabled: None, + notes: None, + retune_ms: None, + } + } + + /// Sets `enabled` on this patch. + pub const fn with_enabled(mut self, enabled: bool) -> Self { + self.enabled = Some(enabled); + self + } + + /// Sets `notes` on this patch. + pub const fn with_notes(mut self, notes: NoteMask) -> Self { + self.notes = Some(notes); + self + } + + /// Sets `retune_ms` on this patch, 0..=400. + pub const fn with_retune_ms(mut self, retune_ms: f32) -> Self { + self.retune_ms = Some(retune_ms); + self + } +} + /// The controls for pitch correction, pitch shift, voice arrangement and /// formants. /// @@ -162,8 +268,7 @@ impl CorrectionConfig { #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), derive(serde::Serialize, serde::Deserialize, tsify::Tsify), - serde(rename_all = "camelCase"), - tsify(large_number_types_as_bigints) + serde(rename_all = "camelCase") )] pub struct ResynthesisConfig { /// The acquisition sensitivity and the reporting bounds. The @@ -242,15 +347,14 @@ pub struct ResynthesisConfig { /// delay of 1,543 frames. Alien, reverb and the output gain still occur /// after this stage. pub dry_mix: f32, - /// The seed for choir drift and aspiration, which use the same stream. - /// The default is `0x1234_abcd`. + /// The seed for choir drift and aspiration, 0..=4294967295. The default is + /// `0x1234_abcd`. /// - /// Only the low 32 bits select the sequence. If a configuration change - /// gives a different 64-bit value, the processor starts the stream again - /// from the low 32 bits. This is also true for a change to only the high - /// bits. Reset keeps the current position in the stream. The enabled - /// stages set the number of random values that the code reads. - pub random_seed: u64, + /// Choir drift and aspiration use the same stream. If a configuration + /// change gives a different seed, the processor starts the stream again + /// from the new seed. Reset keeps the current position in the stream. The + /// enabled stages set the number of random values that the code reads. + pub random_seed: u32, } impl Default for ResynthesisConfig { @@ -276,6 +380,152 @@ impl Default for ResynthesisConfig { } impl ResynthesisConfig { + /// Returns a copy with `pitch` set to the given configuration. + pub const fn with_pitch(mut self, pitch: PitchConfig) -> Self { + self.pitch = pitch; + self + } + + /// Returns a copy with `correction` set to the given configuration. + pub const fn with_correction(mut self, correction: CorrectionConfig) -> Self { + self.correction = correction; + self + } + + /// Returns a copy with `pitch_ratio` set to the given value, 0.25..=4. + pub const fn with_pitch_ratio(mut self, pitch_ratio: f32) -> Self { + self.pitch_ratio = pitch_ratio; + self + } + + /// Returns a copy with `formant` set to the given configuration. + pub const fn with_formant(mut self, formant: FormantConfig) -> Self { + self.formant = formant; + self + } + + /// Returns a copy with `mode` set to the given value. + pub const fn with_mode(mut self, mode: MultiVoiceMode) -> Self { + self.mode = mode; + self + } + + /// Returns a copy with `choir_voices` set to the given value, 1..=16. + pub const fn with_choir_voices(mut self, choir_voices: u8) -> Self { + self.choir_voices = choir_voices; + self + } + + /// Returns a copy with `choir_detune` set to the given value, 10..=100. + pub const fn with_choir_detune(mut self, choir_detune: f32) -> Self { + self.choir_detune = choir_detune; + self + } + + /// Returns a copy with `choir_delay` set to the given value, 20..=200. + pub const fn with_choir_delay(mut self, choir_delay: f32) -> Self { + self.choir_delay = choir_delay; + self + } + + /// Returns a copy with `choir_spread_percent` set to the given value, + /// 0..=100%. + pub const fn with_choir_spread_percent(mut self, choir_spread_percent: f32) -> Self { + self.choir_spread_percent = choir_spread_percent; + self + } + + /// Returns a copy with `stereo_output` set to the given value. + pub const fn with_stereo_output(mut self, stereo_output: bool) -> Self { + self.stereo_output = stereo_output; + self + } + + /// Returns a copy with `harmony` set to the given configuration. + pub const fn with_harmony(mut self, harmony: HarmonyConfig) -> Self { + self.harmony = harmony; + self + } + + /// Returns a copy with `harmony_gain` set to the given value, 0..=1. + pub const fn with_harmony_gain(mut self, harmony_gain: f32) -> Self { + self.harmony_gain = harmony_gain; + self + } + + /// Returns a copy with `harmonic_modulation` set to the given value, + /// 0..=24. + pub const fn with_harmonic_modulation(mut self, harmonic_modulation: f32) -> Self { + self.harmonic_modulation = harmonic_modulation; + self + } + + /// Returns a copy with `dry_mix` set to the given value, 0..=1. + pub const fn with_dry_mix(mut self, dry_mix: f32) -> Self { + self.dry_mix = dry_mix; + self + } + + /// Returns a copy with `random_seed` set to the given value, + /// 0..=4294967295. + pub const fn with_random_seed(mut self, random_seed: u32) -> Self { + self.random_seed = random_seed; + self + } + + /// Merges each present field and sub-patch of `patch` into this + /// configuration. + /// + /// Fields that are `None` do not change. This method does not validate the + /// result. + pub fn merge_patch(&mut self, patch: ResynthesisPatch) { + if let Some(pitch) = patch.pitch { + self.pitch.merge_patch(pitch); + } + if let Some(correction) = patch.correction { + self.correction.merge_patch(correction); + } + if let Some(pitch_ratio) = patch.pitch_ratio { + self.pitch_ratio = pitch_ratio; + } + if let Some(formant) = patch.formant { + self.formant.merge_patch(formant); + } + if let Some(mode) = patch.mode { + self.mode = mode; + } + if let Some(choir_voices) = patch.choir_voices { + self.choir_voices = choir_voices; + } + if let Some(choir_detune) = patch.choir_detune { + self.choir_detune = choir_detune; + } + if let Some(choir_delay) = patch.choir_delay { + self.choir_delay = choir_delay; + } + if let Some(choir_spread_percent) = patch.choir_spread_percent { + self.choir_spread_percent = choir_spread_percent; + } + if let Some(stereo_output) = patch.stereo_output { + self.stereo_output = stereo_output; + } + if let Some(harmony) = patch.harmony { + self.harmony.merge_patch(harmony); + } + if let Some(harmony_gain) = patch.harmony_gain { + self.harmony_gain = harmony_gain; + } + if let Some(harmonic_modulation) = patch.harmonic_modulation { + self.harmonic_modulation = harmonic_modulation; + } + if let Some(dry_mix) = patch.dry_mix { + self.dry_mix = dry_mix; + } + if let Some(random_seed) = patch.random_seed { + self.random_seed = random_seed; + } + } + /// Validates all fields, also the settings for stages that are disabled /// or not active. /// @@ -311,6 +561,245 @@ impl ResynthesisConfig { } } +impl From for ResynthesisConfig { + fn from(patch: ResynthesisPatch) -> Self { + let mut config = Self::default(); + config.merge_patch(patch); + config + } +} + +/// Partial changes for [`ResynthesisConfig`]. +/// +/// Only fields and sub-patches that are `Some` apply in +/// [`ResynthesisConfig::merge_patch`]. All fields are `None` by default. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + derive(serde::Serialize, serde::Deserialize, tsify::Tsify), + serde(default, rename_all = "camelCase") +)] +pub struct ResynthesisPatch { + /// Partial changes for pitch acquisition and reporting bounds. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional) + )] + pub pitch: Option, + /// Partial changes for target notes and retune smoothing. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional) + )] + 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) + )] + pub pitch_ratio: Option, + /// Partial changes for vocal-tract controls and aspiration. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional) + )] + pub formant: Option, + /// The voice arrangement. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional) + )] + 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) + )] + 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) + )] + 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) + )] + 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) + )] + pub choir_spread_percent: Option, + /// Enables or disables a stereo pan for each voice. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional) + )] + pub stereo_output: Option, + /// Partial changes for the four harmony voices. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional) + )] + pub harmony: Option, + /// The pan gain of the harmony voices, 0..=1. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional) + )] + 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) + )] + 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) + )] + pub dry_mix: Option, + /// The seed for choir drift and aspiration, 0..=4294967295. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(skip_serializing_if = "Option::is_none"), + tsify(optional) + )] + pub random_seed: Option, +} + +impl ResynthesisPatch { + /// Returns an empty patch with all fields set to `None`. + pub const fn new() -> Self { + Self { + pitch: None, + correction: None, + pitch_ratio: None, + formant: None, + mode: None, + choir_voices: None, + choir_detune: None, + choir_delay: None, + choir_spread_percent: None, + stereo_output: None, + harmony: None, + harmony_gain: None, + harmonic_modulation: None, + dry_mix: None, + random_seed: None, + } + } + + /// Sets `pitch` on this patch. + pub const fn with_pitch(mut self, pitch: PitchPatch) -> Self { + self.pitch = Some(pitch); + self + } + + /// Sets `correction` on this patch. + pub const fn with_correction(mut self, correction: CorrectionPatch) -> Self { + self.correction = Some(correction); + self + } + + /// Sets `pitch_ratio` on this patch, 0.25..=4. + pub const fn with_pitch_ratio(mut self, pitch_ratio: f32) -> Self { + self.pitch_ratio = Some(pitch_ratio); + self + } + + /// Sets `formant` on this patch. + pub const fn with_formant(mut self, formant: FormantPatch) -> Self { + self.formant = Some(formant); + self + } + + /// Sets `mode` on this patch. + pub const fn with_mode(mut self, mode: MultiVoiceMode) -> Self { + self.mode = Some(mode); + self + } + + /// Sets `choir_voices` on this patch, 1..=16. + pub const fn with_choir_voices(mut self, choir_voices: u8) -> Self { + self.choir_voices = Some(choir_voices); + self + } + + /// Sets `choir_detune` on this patch, 10..=100. + pub const fn with_choir_detune(mut self, choir_detune: f32) -> Self { + self.choir_detune = Some(choir_detune); + self + } + + /// Sets `choir_delay` on this patch, 20..=200. + pub const fn with_choir_delay(mut self, choir_delay: f32) -> Self { + self.choir_delay = Some(choir_delay); + self + } + + /// Sets `choir_spread_percent` on this patch, 0..=100%. + pub const fn with_choir_spread_percent(mut self, choir_spread_percent: f32) -> Self { + self.choir_spread_percent = Some(choir_spread_percent); + self + } + + /// Sets `stereo_output` on this patch. + pub const fn with_stereo_output(mut self, stereo_output: bool) -> Self { + self.stereo_output = Some(stereo_output); + self + } + + /// Sets `harmony` on this patch. + pub const fn with_harmony(mut self, harmony: HarmonyPatch) -> Self { + self.harmony = Some(harmony); + self + } + + /// Sets `harmony_gain` on this patch, 0..=1. + pub const fn with_harmony_gain(mut self, harmony_gain: f32) -> Self { + self.harmony_gain = Some(harmony_gain); + self + } + + /// Sets `harmonic_modulation` on this patch, 0..=24. + pub const fn with_harmonic_modulation(mut self, harmonic_modulation: f32) -> Self { + self.harmonic_modulation = Some(harmonic_modulation); + self + } + + /// Sets `dry_mix` on this patch, 0..=1. + pub const fn with_dry_mix(mut self, dry_mix: f32) -> Self { + self.dry_mix = Some(dry_mix); + self + } + + /// Sets `random_seed` on this patch, 0..=4294967295. + pub const fn with_random_seed(mut self, random_seed: u32) -> Self { + self.random_seed = Some(random_seed); + self + } +} + /// The fixed choir delay offsets in frames, before the scale by /// `choir_delay / 200`. /// diff --git a/src/scale.rs b/src/scale.rs index 01c4f94..e14aeb2 100644 --- a/src/scale.rs +++ b/src/scale.rs @@ -1,5 +1,6 @@ //! Pitch classes and correction tables, made from scales or held MIDI notes. +use crate::harmony::HarmonyScale; use crate::midi::MidiEvent; use crate::SampleRate; @@ -65,6 +66,8 @@ impl PitchClass { } /// A scale for [`NoteMask::from_key_scale`]. +/// +/// It includes all seven modes of [`HarmonyScale`] and [`Self::Chromatic`]. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), @@ -72,15 +75,41 @@ impl PitchClass { serde(rename_all = "camelCase") )] pub enum CorrectionScale { - /// The major scale. + /// Major (ionian): semitone offsets 0, 2, 4, 5, 7, 9, 11. Major, - /// The natural minor scale. + /// Major without the seventh degree: semitone offsets 0, 2, 4, 5, 7, 9. + MajorWithoutSeventh, + /// Major with a flat seventh (mixolydian): semitone offsets 0, 2, 4, 5, 7, + /// 9, 10. + MajorFlatSeventh, + /// Natural minor (aeolian): semitone offsets 0, 2, 3, 5, 7, 8, 10. Minor, - /// The chromatic scale with all notes. + /// Harmonic minor: semitone offsets 0, 2, 3, 5, 7, 8, 11. + HarmonicMinor, + /// Minor with a natural sixth (dorian): semitone offsets 0, 2, 3, 5, 7, 9, + /// 10. + MinorNaturalSixth, + /// Minor with a major seventh: semitone offsets 0, 2, 3, 5, 7, 9, 11. + MinorMajorSeventh, + /// The chromatic scale with all twelve notes. #[default] Chromatic, } +impl From for CorrectionScale { + fn from(scale: HarmonyScale) -> Self { + match scale { + HarmonyScale::Major => Self::Major, + HarmonyScale::MajorWithoutSeventh => Self::MajorWithoutSeventh, + HarmonyScale::MajorFlatSeventh => Self::MajorFlatSeventh, + HarmonyScale::Minor => Self::Minor, + HarmonyScale::HarmonicMinor => Self::HarmonicMinor, + HarmonyScale::MinorNaturalSixth => Self::MinorNaturalSixth, + HarmonyScale::MinorMajorSeventh => Self::MinorMajorSeventh, + } + } +} + /// The permitted correction pitch classes, in the order C, C♯, D, D♯, E, F, /// F♯, G, G♯, A, A♯, B. /// @@ -119,24 +148,22 @@ impl NoteMask { /// Returns the pitch classes of `scale`, with `key` as the tonic. /// - /// Major uses the semitone offsets 0, 2, 4, 5, 7, 9, 11. Natural minor - /// uses 0, 2, 3, 5, 7, 8, 10. Chromatic permits all classes for all keys. - /// This function only makes a value. To apply the value, use the - /// correction configuration. - pub fn from_key_scale(key: PitchClass, scale: CorrectionScale) -> Self { - if scale == CorrectionScale::Chromatic { - return Self::CHROMATIC; - } - let offset = usize::from(key.semitone()) - + if scale == CorrectionScale::Minor { - 3 - } else { - 0 - }; - let major = [ - true, false, true, false, true, true, false, true, false, true, false, true, - ]; - Self(std::array::from_fn(|i| major[(i + 24 - offset) % 12])) + /// Each heptatonic or hexatonic variant uses the same semitone offsets as + /// the equivalent [`HarmonyScale`] variant. [`CorrectionScale::Chromatic`] + /// permits all classes for all keys. This function only makes a value. To + /// apply the value, use the correction configuration. + pub const fn from_key_scale(key: PitchClass, scale: CorrectionScale) -> Self { + let harmony = match scale { + CorrectionScale::Major => HarmonyScale::Major, + CorrectionScale::MajorWithoutSeventh => HarmonyScale::MajorWithoutSeventh, + CorrectionScale::MajorFlatSeventh => HarmonyScale::MajorFlatSeventh, + CorrectionScale::Minor => HarmonyScale::Minor, + CorrectionScale::HarmonicMinor => HarmonyScale::HarmonicMinor, + CorrectionScale::MinorNaturalSixth => HarmonyScale::MinorNaturalSixth, + CorrectionScale::MinorMajorSeventh => HarmonyScale::MinorMajorSeventh, + CorrectionScale::Chromatic => return Self::CHROMATIC, + }; + harmony.note_mask(key) } } diff --git a/src/wasm.rs b/src/wasm.rs index c9cec08..455ebc0 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -14,15 +14,18 @@ //! PCM API does not give buffer pointers or long-lived memory views to //! JavaScript. The class copies the input before it writes the output. //! -//! Configuration objects obey these rules: +//! Configuration and patch objects obey these rules: //! //! - Field names use camelCase. //! - Enum values are strings. -//! - Each object must contain all required fields. -//! - The optional harmony `voices` field defaults to 4. +//! - Complete configuration objects contain all fields, except that the +//! optional harmony `voices` field defaults to 4. +//! - Patch objects make all fields optional and merge only defined fields. //! -//! [`default_config`] gives a configuration to start from. Control events use -//! `{ type, value }`, and the reset control has no `value`. MIDI messages use +//! [`default_config`] gives a complete configuration. [`note_mask_from_key_scale`] +//! makes a correction mask from a key and a scale, and [`parse_midi_bytes`] +//! decodes a three-byte MIDI packet. 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. @@ -42,9 +45,10 @@ //! `free()` method. use crate::{ - Error, Feedback, PrepareConfig, Processor, ProcessorConfig, SampleRate, Telemetry, TimedEvent, + CorrectionScale, Error, Feedback, MidiEvent, NoteMask, PitchClass, PrepareConfig, Processor, + ProcessorConfig, ProcessorPatch, SampleRate, Telemetry, TimedEvent, }; -use js_sys::{Float32Array, Int16Array}; +use js_sys::{Array, Float32Array, Int16Array, Number, Uint8Array}; use serde::{Deserialize, Serialize}; use tsify::{Ts, Tsify}; use wasm_bindgen::prelude::*; @@ -60,12 +64,17 @@ use wasm_bindgen::prelude::*; #[serde(transparent)] pub struct BlockEvents(Vec); +/// A three-byte MIDI packet (`Uint8Array | readonly number[]` in TypeScript). +#[derive(Serialize, Deserialize, Tsify)] +#[serde(transparent)] +#[tsify(type = "Uint8Array | readonly number[]")] +pub struct MidiBytes([u8; 3]); + /// Returns a complete, independent default configuration for JavaScript. /// -/// Change its fields and give it to `Tunelet` or to `setConfig`. The -/// `randomSeed` field is a JavaScript `bigint`, so it keeps all 64 bits. After -/// the binding decodes them, floating-point controls have the precision of the -/// Rust `f32` type. +/// Change its fields and give it to `Tunelet`, `setConfig` or `updateConfig`. +/// All numeric fields use JavaScript `number`. After the binding decodes them, +/// floating-point controls have the precision of the Rust `f32` type. /// /// # Errors /// @@ -76,6 +85,43 @@ pub fn default_config() -> Result, JsError> { Ok(ProcessorConfig::default().into_ts()?) } +/// Returns the correction pitch-class mask for `key` and `scale`. +/// +/// Each scale mode enables the same pitch classes as in native Rust. +/// `"chromatic"` enables all twelve pitch classes for every key. +/// +/// # Errors +/// +/// Throws a JavaScript `Error` if `key` or `scale` is not a valid enum string. +#[wasm_bindgen(js_name = noteMaskFromKeyScale)] +pub fn note_mask_from_key_scale( + key: Ts, + scale: Ts, +) -> Result, JsError> { + Ok(NoteMask::from_key_scale(key.to_rust()?, scale.to_rust()?).into_ts()?) +} + +/// Decodes one three-byte MIDI message into a `MidiEvent`, or `undefined` if +/// the message is valid but not supported. +/// +/// Accepts Note On, Note Off and controller 123 (All Notes Off) with the +/// validation rules of [`MidiEvent::from_bytes`]. A Note On with velocity zero +/// returns a `noteOff` event. +/// +/// # Errors +/// +/// Throws a JavaScript `Error` if `bytes` does not have three integer bytes in +/// `0..=255`, if the status byte is below `0x80` or if a data byte is above +/// 127. +#[wasm_bindgen(js_name = parseMidiBytes)] +pub fn parse_midi_bytes(bytes: Ts) -> Result>, JsError> { + let raw = decode_midi_bytes(&bytes.js_value())?; + match MidiEvent::from_bytes(raw)? { + Some(event) => Ok(Some(event.into_ts()?)), + None => Ok(None), + } +} + /// A stateful PCM processor that JavaScript uses as the `Tunelet` class. /// /// The input is signed 16-bit mono PCM. The output is planar stereo or an @@ -121,10 +167,12 @@ impl WasmProcessor { /// /// `sample_rate` must be 44100 or 48000. `max_block_frames` must be an /// integer in 1..=4294967295. It is a limit for each call, and smaller - /// blocks and empty blocks are also valid. If you omit `config`, the - /// processor uses the default configuration. The constructor validates - /// the settings before it allocates the processor or the PCM buffers. In - /// TypeScript, use `new Tunelet(sampleRate, maxBlockFrames, config)`. + /// blocks and empty blocks are also valid. `config` accepts a partial + /// `ProcessorPatch` or a complete `ProcessorConfig` and merges defined + /// fields onto the defaults. If you omit `config`, the processor uses the + /// default configuration. The constructor validates the settings before it + /// allocates the processor or the PCM buffers. In TypeScript, use + /// `new Tunelet(sampleRate, maxBlockFrames, config)`. /// /// # Errors /// @@ -132,8 +180,8 @@ impl WasmProcessor { /// /// - The rate is not 44100 or 48000. /// - The block limit is not an integer or is out of range. - /// - The configuration object is malformed or a field is missing. - /// - The configuration is not valid. + /// - The configuration object is malformed. + /// - The merged configuration is not valid. /// - The reservation of a PCM buffer fails. /// /// The available Wasm memory must also have sufficient space for the DSP @@ -142,7 +190,7 @@ impl WasmProcessor { pub fn new( sample_rate: f64, max_block_frames: f64, - config: Option>, + config: Option>, ) -> Result { // Accept JavaScript numbers without the u32 coercion of wasm-bindgen. // That coercion silently truncates fractions and wraps large values. @@ -161,7 +209,7 @@ impl WasmProcessor { let max_block_frames = max_block_frames as usize; let preparation = PrepareConfig::new(rate, max_block_frames)?; let config = match config { - Some(value) => value.to_rust()?, + Some(value) => ProcessorConfig::from(value.to_rust()?), None => ProcessorConfig::default(), }; let processor = Processor::new(preparation, config)?; @@ -202,8 +250,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`, `updateConfig` + /// or a timed event applies it. /// /// # Errors /// @@ -228,6 +276,24 @@ impl WasmProcessor { Ok(()) } + /// Decodes a partial configuration patch, validates the merged settings + /// and applies them. + /// + /// Undefined fields keep their active values. State retention and drain + /// cancellation follow `setConfig`. The conversion ignores additional + /// properties of the JavaScript object. + /// + /// # Errors + /// + /// The method throws if the patch object is malformed or if a merged field + /// is out of range. After an error, all processor state and any active + /// drain stay the same. + #[wasm_bindgen(js_name = updateConfig)] + pub fn update_config(&mut self, patch: Ts) -> Result<(), JsError> { + self.processor.update_config(patch.to_rust()?)?; + Ok(()) + } + /// Processes mono input into left and right `Int16Array` buffers of equal /// length. /// @@ -356,8 +422,9 @@ impl WasmProcessor { /// Returns a new feedback object and does not clear the peak window. /// - /// `processedFrames` is a `bigint`, so its 64-bit count stays exact. - /// `latencyFrames` is a number. See `Feedback` for each measurement. + /// `processedFrames` and `latencyFrames` are JavaScript numbers. + /// `processedFrames` saturates at `Number.MAX_SAFE_INTEGER`. See `Feedback` + /// for each measurement. /// /// `targetMidiNote` is `undefined` in these cases, which are also the /// cases where `voiced` is `false`: @@ -394,8 +461,9 @@ impl WasmProcessor { /// /// The telemetry is for meters and displays. It gives the ratio and the /// gain of each voice, the input and output peaks, the pitch clarity and - /// the state of the effects. `processedFrames` is a `bigint`. See - /// `Telemetry` for each measurement. + /// the state of the effects. `processedFrames` is a JavaScript number that + /// saturates at `Number.MAX_SAFE_INTEGER`. See `Telemetry` for each + /// measurement. /// /// # Errors /// @@ -522,14 +590,42 @@ fn pcm_buffer(frames: usize) -> Result, JsError> { Ok(buffer) } -/// Serializes the bounded Wasm frame count as a JavaScript number. -/// -/// The serializer of the feedback structure keeps its other counter, a `u64`, -/// as a `bigint`. This module compiles only for wasm32, where every `usize` -/// fits in a `u32`. +/// Decodes a three-byte MIDI packet from a `Uint8Array` or a three-element +/// JavaScript array without integer wrap. +fn decode_midi_bytes(value: &JsValue) -> Result<[u8; 3], Error> { + if let Some(bytes) = value.dyn_ref::() { + if bytes.length() != 3 { + return Err(Error::InvalidMidi); + } + let mut packet = [0; 3]; + bytes.copy_to(&mut packet); + return Ok(packet); + } + if let Some(array) = value.dyn_ref::() { + if array.length() != 3 { + return Err(Error::InvalidMidi); + } + let mut packet = [0; 3]; + for (slot, item) in packet.iter_mut().zip(array.iter()) { + let Some(number) = item.as_f64() else { + return Err(Error::InvalidMidi); + }; + if !Number::is_safe_integer(&item) || !(0.0..=255.0).contains(&number) { + return Err(Error::InvalidMidi); + } + *slot = number as u8; + } + return Ok(packet); + } + Err(Error::InvalidMidi) +} + +/// Serializes a 64-bit frame count as a JavaScript number, saturated at +/// `Number.MAX_SAFE_INTEGER`. pub(crate) fn serialize_frame_count( - frames: &usize, + frames: &u64, serializer: S, ) -> Result { - serializer.serialize_u32(*frames as u32) + const MAX_SAFE_INTEGER: u64 = (1 << f64::MANTISSA_DIGITS) - 1; + serializer.serialize_f64((*frames).min(MAX_SAFE_INTEGER) as f64) }