From a210db77bab7f9186f3bd76977111b1d42256eff 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:56:54 +0000 Subject: [PATCH] feat: add partial configuration updates and scalar events - Add Processor::update_config for atomic configuration updates. - Add serde default deserialization for all configuration structs. - Export the DeepPartial type from the Wasm and TypeScript APIs. - Accept partial configurations in Tunelet and updateConfig. - Add RetuneMs, PitchRatio, FormantShift, DryMix and ReverbMix events. - Document the new APIs and scalar events in rustdoc and README.md. --- README.md | 44 ++-- src/config.rs | 9 +- src/effects/alien.rs | 2 +- src/effects/punch.rs | 2 +- src/effects/reverb.rs | 11 +- src/effects/warm.rs | 2 +- src/events.rs | 44 +++- src/formant.rs | 13 +- src/harmony.rs | 14 +- src/index.ts | 3 +- src/lib.rs | 8 +- src/pitch.rs | 2 +- src/processor.rs | 40 +++- src/resynthesis.rs | 36 ++- src/wasm.rs | 499 ++++++++++++++++++++++++++++++++++++++++-- 15 files changed, 644 insertions(+), 85 deletions(-) diff --git a/README.md b/README.md index d2993dc..4c87f47 100644 --- a/README.md +++ b/README.md @@ -237,8 +237,10 @@ These rules apply to the offsets: - An offset must not be less than the offset before it. Events with equal offsets execute in slice order. An empty block accepts no -events. A stage event replaces all settings of that stage. To change one -field, start from `processor.config()`. +events. A stage event replaces all settings of that stage. Scalar events +(`RetuneMs`, `PitchRatio`, `FormantShift`, `DryMix`, `ReverbMix` and +`OutputGain`) change only their target fields. Between blocks, use +`processor.update_config` or `processor.set_config`. Harmony MIDI uses `ControlEvent::Midi`. MIDI for the correction keyboard uses `ControlEvent::CorrectionMidi`. For example, this event starts a harmony note @@ -411,7 +413,7 @@ page that opens the JavaScript. | 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()` | +| Configuration | `config()`, `setConfig(config)`, `updateConfig(patch)`, `defaultConfig()` | | Information about the preparation | `sampleRate`, `maxBlockFrames`, `latencyFrames` | | Feedback | `feedback()`, `takeFeedback()` | | Telemetry | `telemetry()`, `takeTelemetry()` | @@ -436,18 +438,23 @@ 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: +`config()` and `defaultConfig()` return a complete `ProcessorConfig` object. +Field names use camelCase, and enums use string literals. The constructor and +`updateConfig(patch)` accept a `DeepPartial`: -1. Start from `defaultConfig()` or `config()`. -2. Edit the necessary fields. -3. Call `setConfig()`. +- In `new Tunelet(sampleRate, maxBlockFrames, config?)`, omitted or + `undefined` fields use their default values. +- In `updateConfig(patch)`, omitted or `undefined` fields keep their active + values from `config()`. +- `setConfig(config)` replaces the full configuration, and omitted or + `undefined` fields use their default values. +- Fixed-size arrays (`notes`, `chromaticIntervals` and `diatonicIntervals`) + replace the full array. -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 -types. +If a field is `null`, has the wrong type or is out of range, the call throws a +JavaScript `Error` before the state changes. 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 @@ -456,14 +463,19 @@ telemetry use `bigint`. Frame offsets, block lengths and latency use ### Events The optional event argument is a `TimedEvent[]`. Controls use a `type` -discriminant and a `value` payload. The reset control has no payload. For -example, this event changes the final gain before the first frame: +discriminant and a `value` payload. The reset control has no payload. Scalar +controls (`retuneMs`, `pitchRatio`, `formantShift`, `dryMix`, `reverbMix` and +`outputGain`) change only their target fields. For example, these events +change the final gain and the formant shape before the first frame: ```ts { offset: 0, event: { type: "outputGain", value: 0.5 } } +{ offset: 0, event: { type: "formantShift", value: { width: 1.1, stretch: 0.9 } } } ``` -A harmony Note On event has this form: +A stage control (`configure`, `resynthesis`, `punch`, `warm`, `alien` or +`reverb`) replaces that stage, and omitted fields use the stage defaults. A +harmony Note On event has this form: ```ts { offset: 0, event: { type: "midi", value: { type: "noteOn", channel: 0, note: 60, velocity: 100 } } } diff --git a/src/config.rs b/src/config.rs index 75bcd82..6b35cbe 100644 --- a/src/config.rs +++ b/src/config.rs @@ -126,14 +126,15 @@ impl PrepareConfig { /// configuration does active pitch processing. It is not a bypass with zero /// latency. /// -/// Change a copy, then apply it with [`crate::Processor::set_config`] or -/// [`crate::ControlEvent::Configure`]. The validation examines all fields -/// before a change has an effect. This includes the fields of disabled stages. +/// Change a copy, then apply it with [`crate::Processor::set_config`], +/// [`crate::Processor::update_config`] or [`crate::ControlEvent::Configure`]. +/// The validation examines all fields before a change has an effect. This +/// includes the fields of disabled stages. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), - derive(serde::Serialize, serde::Deserialize, tsify::Tsify), + derive(serde::Serialize, tsify::Tsify), serde(rename_all = "camelCase"), tsify(large_number_types_as_bigints) )] diff --git a/src/effects/alien.rs b/src/effects/alien.rs index 5e1f509..f8b2974 100644 --- a/src/effects/alien.rs +++ b/src/effects/alien.rs @@ -20,7 +20,7 @@ const FADE_FRAMES: usize = 200; #[non_exhaustive] #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), - derive(serde::Serialize, serde::Deserialize, tsify::Tsify), + derive(serde::Serialize, tsify::Tsify), serde(rename_all = "camelCase") )] pub struct AlienConfig { diff --git a/src/effects/punch.rs b/src/effects/punch.rs index 867dc09..f3d5a64 100644 --- a/src/effects/punch.rs +++ b/src/effects/punch.rs @@ -27,7 +27,7 @@ const TWO_OVER_PI: Q14 = Q14::from_bits(10430); #[non_exhaustive] #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), - derive(serde::Serialize, serde::Deserialize, tsify::Tsify), + derive(serde::Serialize, tsify::Tsify), serde(rename_all = "camelCase") )] pub struct PunchConfig { diff --git a/src/effects/reverb.rs b/src/effects/reverb.rs index fe60cd4..f66d5bf 100644 --- a/src/effects/reverb.rs +++ b/src/effects/reverb.rs @@ -46,7 +46,7 @@ pub enum ReverbMode { #[non_exhaustive] #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), - derive(serde::Serialize, serde::Deserialize, tsify::Tsify), + derive(serde::Serialize, tsify::Tsify), serde(rename_all = "camelCase") )] pub struct ReverbConfig { @@ -108,13 +108,20 @@ impl ReverbConfig { /// Returns the first [`Error::InvalidConfig`] with its dotted field path /// and the problem. pub fn validate(self) -> Result<(), Error> { - check_range("reverb.mix", self.mix, 0.0, 1.0)?; + validate_reverb_mix(self.mix)?; check_range("reverb.diffusion", self.diffusion, 0.0, 1.0)?; check_range("reverb.decay", self.decay, 0.0, 1.0)?; check_range("reverb.brightness_hz", self.brightness_hz, 80.0, 20000.0) } } +/// Checks the wet fraction range of the reverb. +/// +/// `ReverbConfig` and `ControlEvent::ReverbMix` use the same range. +pub(crate) fn validate_reverb_mix(mix: f32) -> Result<(), Error> { + check_range("reverb.mix", mix, 0.0, 1.0) +} + /// 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..d05717b 100644 --- a/src/effects/warm.rs +++ b/src/effects/warm.rs @@ -20,7 +20,7 @@ const WINDOW_FRAMES: usize = 100; #[non_exhaustive] #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), - derive(serde::Serialize, serde::Deserialize, tsify::Tsify), + derive(serde::Serialize, tsify::Tsify), serde(rename_all = "camelCase") )] pub struct WarmConfig { diff --git a/src/events.rs b/src/events.rs index e1c975c..03cd9d2 100644 --- a/src/events.rs +++ b/src/events.rs @@ -3,17 +3,19 @@ use crate::config::validate_output_gain; use crate::effects::alien::AlienConfig; use crate::effects::punch::PunchConfig; -use crate::effects::reverb::ReverbConfig; +use crate::effects::reverb::{validate_reverb_mix, ReverbConfig}; use crate::effects::warm::WarmConfig; +use crate::formant::validate_formant_shift; use crate::midi::MidiEvent; +use crate::resynthesis::{validate_dry_mix, validate_pitch_ratio, validate_retune_ms}; use crate::{Error, EventProblem, ProcessorConfig, 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. +/// queue. A stage event replaces all settings of that stage. Scalar events +/// change only their target fields in the active configuration. /// Configuration changes have the same effects on state as /// [`crate::Processor::set_config`]. #[derive(Clone, Copy, Debug, PartialEq)] @@ -35,6 +37,37 @@ pub enum ControlEvent { Alien(AlienConfig), /// This event replaces the reverb configuration. Reverb(ReverbConfig), + /// This event sets the retune half-life in milliseconds, 0..=400. + /// + /// The target behavior is the same as for + /// [`CorrectionConfig::retune_ms`](crate::CorrectionConfig::retune_ms). + /// The value must be finite. + RetuneMs(f32), + /// This event sets the pitch multiplier, 0.25..=4. + /// + /// The filter and voice behavior is the same as for + /// [`ResynthesisConfig::pitch_ratio`]. The value must be finite. + PitchRatio(f32), + /// This event sets the vocal-tract width and length factors. + /// + /// The synthesis behavior is the same as for + /// [`FormantConfig`](crate::FormantConfig). Both values must be finite. + FormantShift { + /// The vocal-tract width factor, 0.5..=2. + width: f32, + /// The vocal-tract length factor, 0.5..=2. + stretch: f32, + }, + /// This event sets the dry fraction at the resynthesis stage, 0..=1. + /// + /// The quantization and the delay are the same as for + /// [`ResynthesisConfig::dry_mix`]. The value must be finite. + DryMix(f32), + /// This event sets the wet fraction of the reverb stage, 0..=1. + /// + /// The quantization and the dry weight are the same as for + /// [`ReverbConfig::mix`]. The value must be finite. + ReverbMix(f32), /// This event sets the final linear gain, 0..=64. /// /// The quantization and the mute behavior are the same as for @@ -80,6 +113,11 @@ impl ControlEvent { Self::Warm(config) => config.validate(), Self::Alien(config) => config.validate(), Self::Reverb(config) => config.validate(), + Self::RetuneMs(retune_ms) => validate_retune_ms(retune_ms), + Self::PitchRatio(pitch_ratio) => validate_pitch_ratio(pitch_ratio), + Self::FormantShift { width, stretch } => validate_formant_shift(width, stretch), + Self::DryMix(dry_mix) => validate_dry_mix(dry_mix), + Self::ReverbMix(mix) => validate_reverb_mix(mix), Self::OutputGain(gain) => validate_output_gain(gain), Self::Midi(event) | Self::CorrectionMidi(event) => event.validate(), Self::Reset => Ok(()), diff --git a/src/formant.rs b/src/formant.rs index 5072ee1..33dfc98 100644 --- a/src/formant.rs +++ b/src/formant.rs @@ -40,7 +40,7 @@ use crate::{Error, SampleRate}; #[non_exhaustive] #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), - derive(serde::Serialize, serde::Deserialize, tsify::Tsify), + derive(serde::Serialize, tsify::Tsify), serde(rename_all = "camelCase") )] pub struct FormantConfig { @@ -95,8 +95,7 @@ impl FormantConfig { /// Returns the first [`Error::InvalidConfig`], with the dotted path of the /// field and the problem. pub fn validate(self) -> Result<(), Error> { - check_range("resynthesis.formant.width", self.width, 0.5, 2.0)?; - check_range("resynthesis.formant.stretch", self.stretch, 0.5, 2.0)?; + validate_formant_shift(self.width, self.stretch)?; let field = "resynthesis.formant.aspiration_mix"; check_range(field, self.aspiration_mix, 0.0, 1.0)?; let field = "resynthesis.formant.aspiration_cutoff_hz"; @@ -104,6 +103,14 @@ impl FormantConfig { } } +/// Checks the formant width and stretch ranges. +/// +/// `FormantConfig` and `ControlEvent::FormantShift` use the same ranges. +pub(crate) fn validate_formant_shift(width: f32, stretch: f32) -> Result<(), Error> { + check_range("resynthesis.formant.width", width, 0.5, 2.0)?; + check_range("resynthesis.formant.stretch", stretch, 0.5, 2.0) +} + /// The number of frames of input history for analysis and synthesis. The /// value is equal to the resynthesis history length. pub(crate) const HISTORY_FRAMES: usize = 11568; diff --git a/src/harmony.rs b/src/harmony.rs index 67b7111..5ba75ba 100644 --- a/src/harmony.rs +++ b/src/harmony.rs @@ -257,7 +257,7 @@ pub enum Inversion { #[non_exhaustive] #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), - derive(serde::Serialize, serde::Deserialize, tsify::Tsify), + derive(serde::Serialize, tsify::Tsify), serde(rename_all = "camelCase") )] pub struct HarmonyConfig { @@ -322,20 +322,10 @@ pub struct HarmonyConfig { /// other voices release with the usual gain envelope. The chord and MIDI /// sources ignore this field. In JavaScript, the field is optional and /// a missing value gives the default. - #[cfg_attr( - all(feature = "wasm", target_arch = "wasm32"), - serde(default = "default_voices"), - tsify(optional) - )] + #[cfg_attr(all(feature = "wasm", target_arch = "wasm32"), tsify(optional))] pub voices: u8, } -/// The default count of interval voices: all of them. -#[cfg(all(feature = "wasm", target_arch = "wasm32"))] -fn default_voices() -> u8 { - HARMONY_VOICES as u8 -} - impl Default for HarmonyConfig { fn default() -> Self { Self { diff --git a/src/index.ts b/src/index.ts index da35a57..56016f0 100644 --- a/src/index.ts +++ b/src/index.ts @@ -8,9 +8,10 @@ * `initSync` and the configuration, event and feedback types. */ import init, { initSync } from "../pkg/tunelet.js"; -import type { InitInput, InitOutput } from "../pkg/tunelet.js"; +import type { DeepPartial, InitInput, InitOutput } from "../pkg/tunelet.js"; export * from "../pkg/tunelet.js"; +export type { DeepPartial }; /** The shared initialization promise, which a failure clears. */ let initialization: Promise | undefined; diff --git a/src/lib.rs b/src/lib.rs index 0e29119..29e0b46 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -19,10 +19,10 @@ //! 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 //! diff --git a/src/pitch.rs b/src/pitch.rs index 6b682ca..ab45995 100644 --- a/src/pitch.rs +++ b/src/pitch.rs @@ -16,7 +16,7 @@ use crate::Error; #[non_exhaustive] #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), - derive(serde::Serialize, serde::Deserialize, tsify::Tsify), + derive(serde::Serialize, tsify::Tsify), serde(rename_all = "camelCase") )] pub struct PitchConfig { diff --git a/src/processor.rs b/src/processor.rs index cc910f4..dcc3ca7 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -315,9 +315,9 @@ impl Processor { /// Returns a copy of the current settings and does not change state. /// /// If you edit the copy, nothing changes until - /// [`set_config`](Self::set_config) or a configuration event applies it. - /// The temporary aspiration mute of a drain does not change the settings - /// that this method returns. + /// [`set_config`](Self::set_config), [`update_config`](Self::update_config) + /// or a configuration event applies it. The temporary aspiration mute of a + /// drain does not change the settings that this method returns. pub fn config(&self) -> ProcessorConfig { self.config } @@ -480,6 +480,26 @@ impl Processor { Ok(()) } + /// Copies the active configuration, passes it to `update`, validates all + /// fields and applies the result. + /// + /// This method does not allocate memory. State retention, validation of + /// disabled stages and drain cancellation are the same as in + /// [`set_config`](Self::set_config). + /// + /// # Errors + /// + /// Returns [`Error::InvalidConfig`] if a field is not valid. The method + /// returns this error before it changes any state, also an active drain. + pub fn update_config( + &mut self, + update: impl FnOnce(&mut ProcessorConfig), + ) -> Result<(), Error> { + let mut config = self.config; + update(&mut config); + 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 { @@ -573,9 +593,9 @@ 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. + /// Stage and scalar configuration events update the active configuration. + /// 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() { @@ -585,6 +605,14 @@ impl Processor { ControlEvent::Warm(value) => config.warm = value, ControlEvent::Alien(value) => config.alien = value, ControlEvent::Reverb(value) => config.reverb = value, + ControlEvent::RetuneMs(value) => config.resynthesis.correction.retune_ms = value, + ControlEvent::PitchRatio(value) => config.resynthesis.pitch_ratio = value, + ControlEvent::FormantShift { width, stretch } => { + config.resynthesis.formant.width = width; + config.resynthesis.formant.stretch = stretch; + } + ControlEvent::DryMix(value) => config.resynthesis.dry_mix = value, + ControlEvent::ReverbMix(value) => config.reverb.mix = value, ControlEvent::OutputGain(value) => config.output_gain = value, ControlEvent::Midi(event) => { self.resynthesis.apply_midi(event); diff --git a/src/resynthesis.rs b/src/resynthesis.rs index 34e98fa..2754951 100644 --- a/src/resynthesis.rs +++ b/src/resynthesis.rs @@ -83,7 +83,7 @@ pub enum MultiVoiceMode { #[non_exhaustive] #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), - derive(serde::Serialize, serde::Deserialize, tsify::Tsify), + derive(serde::Serialize, tsify::Tsify), serde(rename_all = "camelCase") )] pub struct CorrectionConfig { @@ -130,15 +130,17 @@ impl CorrectionConfig { /// Returns [`Error::InvalidConfig`], with the dotted path of the field and /// the problem, if `retune_ms` is not valid. pub fn validate(self) -> Result<(), Error> { - check_range( - "resynthesis.correction.retune_ms", - self.retune_ms, - 0.0, - 400.0, - ) + validate_retune_ms(self.retune_ms) } } +/// Checks the correction retune half-life range. +/// +/// `CorrectionConfig` and `ControlEvent::RetuneMs` use the same range. +pub(crate) fn validate_retune_ms(retune_ms: f32) -> Result<(), Error> { + check_range("resynthesis.correction.retune_ms", retune_ms, 0.0, 400.0) +} + /// The controls for pitch correction, pitch shift, voice arrangement and /// formants. /// @@ -161,7 +163,7 @@ impl CorrectionConfig { #[non_exhaustive] #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), - derive(serde::Serialize, serde::Deserialize, tsify::Tsify), + derive(serde::Serialize, tsify::Tsify), serde(rename_all = "camelCase"), tsify(large_number_types_as_bigints) )] @@ -293,7 +295,7 @@ impl ResynthesisConfig { self.correction.validate()?; self.formant.validate()?; self.harmony.validate()?; - check_range("resynthesis.pitch_ratio", self.pitch_ratio, 0.25, 4.0)?; + validate_pitch_ratio(self.pitch_ratio)?; check_range("resynthesis.choir_detune", self.choir_detune, 10.0, 100.0)?; check_range("resynthesis.choir_delay", self.choir_delay, 20.0, 200.0)?; let field = "resynthesis.choir_spread_percent"; @@ -301,7 +303,7 @@ impl ResynthesisConfig { check_range("resynthesis.harmony_gain", self.harmony_gain, 0.0, 1.0)?; let field = "resynthesis.harmonic_modulation"; check_range(field, self.harmonic_modulation, 0.0, 24.0)?; - check_range("resynthesis.dry_mix", self.dry_mix, 0.0, 1.0)?; + validate_dry_mix(self.dry_mix)?; check_count( "resynthesis.choir_voices", i64::from(self.choir_voices), @@ -311,6 +313,20 @@ impl ResynthesisConfig { } } +/// Checks the pitch multiplier range. +/// +/// `ResynthesisConfig` and `ControlEvent::PitchRatio` use the same range. +pub(crate) fn validate_pitch_ratio(pitch_ratio: f32) -> Result<(), Error> { + check_range("resynthesis.pitch_ratio", pitch_ratio, 0.25, 4.0) +} + +/// Checks the dry fraction range at the resynthesis stage. +/// +/// `ResynthesisConfig` and `ControlEvent::DryMix` use the same range. +pub(crate) fn validate_dry_mix(dry_mix: f32) -> Result<(), Error> { + check_range("resynthesis.dry_mix", dry_mix, 0.0, 1.0) +} + /// The fixed choir delay offsets in frames, before the scale by /// `choir_delay / 200`. /// diff --git a/src/wasm.rs b/src/wasm.rs index c9cec08..d78d089 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -18,8 +18,14 @@ //! //! - Field names use camelCase. //! - Enum values are strings. -//! - Each object must contain all required fields. -//! - The optional harmony `voices` field defaults to 4. +//! - `config` and [`default_config`] return complete objects. +//! - The constructor and `updateConfig` accept `DeepPartial`. +//! - Fixed-size arrays replace the full array. +//! +//! In the constructor and in `setConfig`, omitted or `undefined` fields use +//! their defaults. In `updateConfig`, omitted or `undefined` fields keep the +//! active values from `config`. A `null` field or a wrong field type throws a +//! JavaScript `Error` before the state changes. //! //! [`default_config`] gives a configuration to start from. Control events use //! `{ type, value }`, and the reset control has no `value`. MIDI messages use @@ -42,13 +48,40 @@ //! `free()` method. use crate::{ - Error, Feedback, PrepareConfig, Processor, ProcessorConfig, SampleRate, Telemetry, TimedEvent, + AlienConfig, ChordDegree, ChordName, CorrectionConfig, Error, Feedback, FormantConfig, + HarmonyConfig, HarmonyScale, HarmonySource, Inversion, MultiVoiceMode, NoteMask, PitchClass, + PitchConfig, PrepareConfig, Processor, ProcessorConfig, PunchConfig, ResynthesisConfig, + ReverbConfig, ReverbMode, SampleRate, Telemetry, TimedEvent, WarmConfig, HARMONY_VOICES, +}; +use js_sys::{ + Array, ArrayBuffer, Boolean, Date, Float32Array, Int16Array, Number, Reflect, RegExp, Symbol, }; -use js_sys::{Float32Array, Int16Array}; -use serde::{Deserialize, Serialize}; +use serde::{de::DeserializeOwned, Deserialize, Deserializer, Serialize}; use tsify::{Ts, Tsify}; use wasm_bindgen::prelude::*; +#[wasm_bindgen(typescript_custom_section)] +const DEEP_PARTIAL_DECL: &'static str = r#"/** + * Makes each object property in `T` optional at all levels. + * + * Functions and fixed-size arrays or tuples stay complete. + */ +export type DeepPartial = T extends (...args: never[]) => unknown + ? T + : T extends readonly unknown[] + ? T + : T extends object + ? { [K in keyof T]?: DeepPartial } + : T; +"#; + +#[wasm_bindgen] +extern "C" { + /// A partial processor configuration object from JavaScript. + #[wasm_bindgen(typescript_type = "DeepPartial")] + pub type PartialProcessorConfig; +} + /// The events for one call that processes audio (`TimedEvent[]` in TypeScript). /// /// Each offset is a zero-based frame index in the current block. Each offset @@ -122,8 +155,9 @@ 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 + /// processor uses the default configuration. Omitted or `undefined` fields + /// in `config` also use their defaults. The constructor validates the + /// settings before it allocates the processor or the PCM buffers. In /// TypeScript, use `new Tunelet(sampleRate, maxBlockFrames, config)`. /// /// # Errors @@ -132,7 +166,7 @@ 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 object is malformed or a field is `null`. /// - The configuration is not valid. /// - The reservation of a PCM buffer fails. /// @@ -142,7 +176,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. @@ -160,11 +194,11 @@ 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()?, - None => ProcessorConfig::default(), - }; - let processor = Processor::new(preparation, config)?; + let mut resolved = ProcessorConfig::default(); + if let Some(patch) = config { + merge_processor_config(&mut resolved, &patch)?; + } + let processor = Processor::new(preparation, resolved)?; Ok(Self { processor, input: pcm_buffer(max_block_frames)?, @@ -202,8 +236,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 /// @@ -215,16 +249,40 @@ impl WasmProcessor { /// Decodes and validates a configuration, then replaces the complete /// configuration with it. /// - /// State retention and drain cancellation follow the native processor. - /// The conversion ignores additional properties of the JavaScript object. + /// Omitted or `undefined` fields use their defaults. State retention and + /// drain cancellation follow the native processor. The conversion ignores + /// additional properties of the JavaScript object. /// /// # Errors /// - /// The method throws if an object is not valid or a field is missing. + /// The method throws if an object is not valid or a field is `null`. /// After an error, all processor state and any active drain stay the same. #[wasm_bindgen(js_name = setConfig)] pub fn set_config(&mut self, config: Ts) -> Result<(), JsError> { - self.processor.set_config(config.to_rust()?)?; + let mut next = ProcessorConfig::default(); + merge_processor_config(&mut next, &config.js_value())?; + self.processor.set_config(next)?; + Ok(()) + } + + /// Combines the defined fields of `patch` with the active configuration, + /// validates all fields and applies the result. + /// + /// Omitted or `undefined` fields keep their active values from `config`. + /// Fixed-size arrays replace the full array. State retention and drain + /// cancellation follow the native processor. The conversion ignores + /// additional properties of the JavaScript object. + /// + /// # Errors + /// + /// If `patch` is not an object, a field is `null` or a value is not valid, + /// this method throws. 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: PartialProcessorConfig) -> Result<(), JsError> { + let mut next = self.processor.config(); + merge_processor_config(&mut next, &patch)?; + self.processor.set_config(next)?; Ok(()) } @@ -533,3 +591,404 @@ pub(crate) fn serialize_frame_count( ) -> Result { serializer.serialize_u32(*frames as u32) } + +/// Converts a JavaScript error from property access to a `JsError`. +fn js_error(error: JsValue) -> JsError { + if let Some(err) = error.dyn_ref::() { + JsError::new(&String::from(err.message())) + } else if let Some(text) = error.as_string() { + JsError::new(&text) + } else { + JsError::new("failed to read configuration property") + } +} + +/// Rejects `null`, primitives, functions, arrays and non-record objects. +fn ensure_config_object(value: &JsValue) -> Result<(), JsError> { + if value.is_null() + || !value.is_object() + || value.is_function() + || Array::is_array(value) + || ArrayBuffer::is_view(value) + || value.is_instance_of::() + || value.is_instance_of::() + || value.is_instance_of::() + || value.is_instance_of::() + || value.is_instance_of::() + || Reflect::has(value, &Symbol::iterator()).unwrap_or(true) + { + return Err(JsError::new("expected a configuration object")); + } + Ok(()) +} + +/// Reads one property and treats an omitted or `undefined` value as `None`. +fn get_property(object: &JsValue, key: &str) -> Result, JsError> { + let value = Reflect::get(object, &JsValue::from_str(key)).map_err(js_error)?; + if value.is_undefined() { + Ok(None) + } else { + Ok(Some(value)) + } +} + +/// If the property is defined, decodes one leaf field. +fn merge_field( + object: &JsValue, + key: &str, + target: &mut T, +) -> Result<(), JsError> { + if let Some(value) = get_property(object, key)? { + *target = tsify::serde_wasm_bindgen::from_value(value)?; + } + Ok(()) +} + +/// If the property is defined, applies `merge` to a nested stage object. +fn merge_nested( + object: &JsValue, + key: &str, + merge: impl FnOnce(&JsValue) -> Result<(), JsError>, +) -> Result<(), JsError> { + if let Some(value) = get_property(object, key)? { + ensure_config_object(&value)?; + merge(&value)?; + } + Ok(()) +} + +/// Copies defined fields from a JavaScript patch onto `config`. +fn merge_processor_config(config: &mut ProcessorConfig, patch: &JsValue) -> Result<(), JsError> { + ensure_config_object(patch)?; + merge_nested(patch, "punch", |sub| { + merge_punch_config(&mut config.punch, sub) + })?; + merge_nested(patch, "warm", |sub| { + merge_warm_config(&mut config.warm, sub) + })?; + merge_nested(patch, "resynthesis", |sub| { + merge_resynthesis_config(&mut config.resynthesis, sub) + })?; + merge_nested(patch, "alien", |sub| { + merge_alien_config(&mut config.alien, sub) + })?; + merge_nested(patch, "reverb", |sub| { + merge_reverb_config(&mut config.reverb, sub) + })?; + merge_field(patch, "outputGain", &mut config.output_gain) +} + +fn merge_punch_config(config: &mut PunchConfig, patch: &JsValue) -> Result<(), JsError> { + merge_field(patch, "enabled", &mut config.enabled)?; + merge_field(patch, "gainDb", &mut config.gain_db)?; + merge_field(patch, "impact", &mut config.impact)?; + merge_field(patch, "ceilingDb", &mut config.ceiling_db)?; + merge_field(patch, "attackMs", &mut config.attack_ms) +} + +fn merge_warm_config(config: &mut WarmConfig, patch: &JsValue) -> Result<(), JsError> { + merge_field(patch, "enabled", &mut config.enabled)?; + merge_field(patch, "driveDb", &mut config.drive_db) +} + +fn merge_alien_config(config: &mut AlienConfig, patch: &JsValue) -> Result<(), JsError> { + merge_field(patch, "enabled", &mut config.enabled)?; + merge_field(patch, "loopFrames", &mut config.loop_frames) +} + +fn merge_reverb_config(config: &mut ReverbConfig, patch: &JsValue) -> Result<(), JsError> { + merge_field(patch, "enabled", &mut config.enabled)?; + merge_field(patch, "mode", &mut config.mode)?; + merge_field(patch, "mix", &mut config.mix)?; + merge_field(patch, "diffusion", &mut config.diffusion)?; + merge_field(patch, "decay", &mut config.decay)?; + merge_field(patch, "brightnessHz", &mut config.brightness_hz) +} + +fn merge_pitch_config(config: &mut PitchConfig, patch: &JsValue) -> Result<(), JsError> { + merge_field(patch, "threshold", &mut config.threshold)?; + merge_field(patch, "minFrequencyHz", &mut config.min_frequency_hz)?; + merge_field(patch, "maxFrequencyHz", &mut config.max_frequency_hz) +} + +fn merge_correction_config(config: &mut CorrectionConfig, patch: &JsValue) -> Result<(), JsError> { + merge_field(patch, "enabled", &mut config.enabled)?; + merge_field(patch, "notes", &mut config.notes)?; + merge_field(patch, "retuneMs", &mut config.retune_ms) +} + +fn merge_formant_config(config: &mut FormantConfig, patch: &JsValue) -> Result<(), JsError> { + merge_field(patch, "enabled", &mut config.enabled)?; + merge_field(patch, "width", &mut config.width)?; + merge_field(patch, "stretch", &mut config.stretch)?; + merge_field(patch, "aspirationMix", &mut config.aspiration_mix)?; + merge_field( + patch, + "aspirationCutoffHz", + &mut config.aspiration_cutoff_hz, + ) +} + +fn merge_harmony_config(config: &mut HarmonyConfig, patch: &JsValue) -> Result<(), JsError> { + merge_field(patch, "source", &mut config.source)?; + merge_field(patch, "key", &mut config.key)?; + merge_field(patch, "scale", &mut config.scale)?; + merge_field(patch, "chromaticIntervals", &mut config.chromatic_intervals)?; + merge_field(patch, "diatonicIntervals", &mut config.diatonic_intervals)?; + merge_field(patch, "chord", &mut config.chord)?; + merge_field(patch, "degree", &mut config.degree)?; + merge_field(patch, "inversion", &mut config.inversion)?; + merge_field(patch, "registerPercent", &mut config.register_percent)?; + merge_field( + patch, + "voicingSpreadPercent", + &mut config.voicing_spread_percent, + )?; + merge_field(patch, "portamentoMs", &mut config.portamento_ms)?; + merge_field(patch, "voices", &mut config.voices) +} + +fn merge_resynthesis_config( + config: &mut ResynthesisConfig, + patch: &JsValue, +) -> Result<(), JsError> { + merge_nested(patch, "pitch", |sub| { + merge_pitch_config(&mut config.pitch, sub) + })?; + merge_nested(patch, "correction", |sub| { + merge_correction_config(&mut config.correction, sub) + })?; + merge_field(patch, "pitchRatio", &mut config.pitch_ratio)?; + merge_nested(patch, "formant", |sub| { + merge_formant_config(&mut config.formant, sub) + })?; + merge_field(patch, "mode", &mut config.mode)?; + merge_field(patch, "choirVoices", &mut config.choir_voices)?; + merge_field(patch, "choirDetune", &mut config.choir_detune)?; + merge_field(patch, "choirDelay", &mut config.choir_delay)?; + merge_field( + patch, + "choirSpreadPercent", + &mut config.choir_spread_percent, + )?; + merge_field(patch, "stereoOutput", &mut config.stereo_output)?; + merge_nested(patch, "harmony", |sub| { + merge_harmony_config(&mut config.harmony, sub) + })?; + merge_field(patch, "harmonyGain", &mut config.harmony_gain)?; + merge_field(patch, "harmonicModulation", &mut config.harmonic_modulation)?; + merge_field(patch, "dryMix", &mut config.dry_mix)?; + merge_field(patch, "randomSeed", &mut config.random_seed) +} + +// Remote serde definitions keep `serde(default)` out of the `Tsify` derive so +// `ProcessorConfig` and its stage types stay complete in `pkg/tunelet.d.ts`. + +#[derive(Deserialize)] +#[serde( + default = "ProcessorConfig::default", + remote = "ProcessorConfig", + rename_all = "camelCase" +)] +struct ProcessorConfigDef { + punch: PunchConfig, + warm: WarmConfig, + resynthesis: ResynthesisConfig, + alien: AlienConfig, + reverb: ReverbConfig, + output_gain: f32, +} + +impl<'de> Deserialize<'de> for ProcessorConfig { + fn deserialize>(deserializer: D) -> Result { + ProcessorConfigDef::deserialize(deserializer) + } +} + +#[derive(Deserialize)] +#[serde( + default = "PunchConfig::default", + remote = "PunchConfig", + rename_all = "camelCase" +)] +struct PunchConfigDef { + enabled: bool, + gain_db: f32, + impact: f32, + ceiling_db: f32, + attack_ms: f32, +} + +impl<'de> Deserialize<'de> for PunchConfig { + fn deserialize>(deserializer: D) -> Result { + PunchConfigDef::deserialize(deserializer) + } +} + +#[derive(Deserialize)] +#[serde( + default = "WarmConfig::default", + remote = "WarmConfig", + rename_all = "camelCase" +)] +struct WarmConfigDef { + enabled: bool, + drive_db: f32, +} + +impl<'de> Deserialize<'de> for WarmConfig { + fn deserialize>(deserializer: D) -> Result { + WarmConfigDef::deserialize(deserializer) + } +} + +#[derive(Deserialize)] +#[serde( + default = "AlienConfig::default", + remote = "AlienConfig", + rename_all = "camelCase" +)] +struct AlienConfigDef { + enabled: bool, + loop_frames: u32, +} + +impl<'de> Deserialize<'de> for AlienConfig { + fn deserialize>(deserializer: D) -> Result { + AlienConfigDef::deserialize(deserializer) + } +} + +#[derive(Deserialize)] +#[serde( + default = "ReverbConfig::default", + remote = "ReverbConfig", + rename_all = "camelCase" +)] +struct ReverbConfigDef { + enabled: bool, + mode: ReverbMode, + mix: f32, + diffusion: f32, + decay: f32, + brightness_hz: f32, +} + +impl<'de> Deserialize<'de> for ReverbConfig { + fn deserialize>(deserializer: D) -> Result { + ReverbConfigDef::deserialize(deserializer) + } +} + +#[derive(Deserialize)] +#[serde( + default = "PitchConfig::default", + remote = "PitchConfig", + rename_all = "camelCase" +)] +struct PitchConfigDef { + threshold: f32, + min_frequency_hz: f32, + max_frequency_hz: f32, +} + +impl<'de> Deserialize<'de> for PitchConfig { + fn deserialize>(deserializer: D) -> Result { + PitchConfigDef::deserialize(deserializer) + } +} + +#[derive(Deserialize)] +#[serde( + default = "CorrectionConfig::default", + remote = "CorrectionConfig", + rename_all = "camelCase" +)] +struct CorrectionConfigDef { + enabled: bool, + notes: NoteMask, + retune_ms: f32, +} + +impl<'de> Deserialize<'de> for CorrectionConfig { + fn deserialize>(deserializer: D) -> Result { + CorrectionConfigDef::deserialize(deserializer) + } +} + +#[derive(Deserialize)] +#[serde( + default = "FormantConfig::default", + remote = "FormantConfig", + rename_all = "camelCase" +)] +struct FormantConfigDef { + enabled: bool, + width: f32, + stretch: f32, + aspiration_mix: f32, + aspiration_cutoff_hz: f32, +} + +impl<'de> Deserialize<'de> for FormantConfig { + fn deserialize>(deserializer: D) -> Result { + FormantConfigDef::deserialize(deserializer) + } +} + +#[derive(Deserialize)] +#[serde( + default = "HarmonyConfig::default", + remote = "HarmonyConfig", + rename_all = "camelCase" +)] +struct HarmonyConfigDef { + source: HarmonySource, + key: PitchClass, + scale: HarmonyScale, + chromatic_intervals: [i8; HARMONY_VOICES], + diatonic_intervals: [i8; HARMONY_VOICES], + chord: ChordName, + degree: ChordDegree, + inversion: Inversion, + register_percent: f32, + voicing_spread_percent: f32, + portamento_ms: f32, + voices: u8, +} + +impl<'de> Deserialize<'de> for HarmonyConfig { + fn deserialize>(deserializer: D) -> Result { + HarmonyConfigDef::deserialize(deserializer) + } +} + +#[derive(Deserialize)] +#[serde( + default = "ResynthesisConfig::default", + remote = "ResynthesisConfig", + rename_all = "camelCase" +)] +struct ResynthesisConfigDef { + pitch: PitchConfig, + correction: CorrectionConfig, + pitch_ratio: f32, + formant: FormantConfig, + mode: MultiVoiceMode, + choir_voices: u8, + choir_detune: f32, + choir_delay: f32, + choir_spread_percent: f32, + stereo_output: bool, + harmony: HarmonyConfig, + harmony_gain: f32, + harmonic_modulation: f32, + dry_mix: f32, + random_seed: u64, +} + +impl<'de> Deserialize<'de> for ResynthesisConfig { + fn deserialize>(deserializer: D) -> Result { + ResynthesisConfigDef::deserialize(deserializer) + } +}