From 6a14bc068bfb04bae14f0e8faaf497ca577ce968 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 02:11:56 +0000 Subject: [PATCH] feat!: add builders, parameter events and Wasm helpers - Add with_* builders and presets to all configuration types. - Add Processor::update_config for validated configuration edits. - Narrow ResynthesisConfig::random_seed from u64 to u32. - Serialize processedFrames as a number in Wasm snapshots. - Add sub-stage controls and ParameterControl to ControlEvent. - Validate timed configuration edits sequentially on the stack. - Unify CorrectionScale and NoteMask with all HarmonyScale modes. - Accept DeepPartial in Tunelet and updateConfig. - Export noteMaskFromKeyScale and parseMidiBytes from Wasm. - Update the crate documentation, TypeScript exports and README. --- README.md | 98 ++++++------ src/config.rs | 53 ++++++- src/effects/alien.rs | 29 +++- src/effects/punch.rs | 49 +++++- src/effects/reverb.rs | 58 +++++++- src/effects/warm.rs | 28 +++- src/events.rs | 336 ++++++++++++++++++++++++++++++++++++++++-- src/formant.rs | 50 ++++++- src/harmony.rs | 182 +++++++++++++++++++++-- src/harmony/chords.rs | 2 +- src/index.ts | 8 +- src/lib.rs | 19 +-- src/pitch.rs | 51 ++++++- src/processor.rs | 84 ++++++----- src/resynthesis.rs | 196 +++++++++++++++++++++--- src/scale.rs | 61 +++++--- src/wasm.rs | 203 +++++++++++++++++++++---- 17 files changed, 1302 insertions(+), 205 deletions(-) diff --git a/README.md b/README.md index d2993dc..7872f3f 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, + CorrectionConfig, CorrectionScale, PitchClass, PrepareConfig, Processor, ProcessorConfig, + ResynthesisConfig, SampleRate, }; fn main() -> Result<(), tunelet::Error> { @@ -106,11 +106,11 @@ 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 configuration from presets and builders. + let correction = + CorrectionConfig::from_key_scale(PitchClass::A, CorrectionScale::Minor).with_retune_ms(20.0); + let config = ProcessorConfig::default() + .with_resynthesis(ResynthesisConfig::default().with_correction(correction)); // 3. Construct the processor. Only this step allocates memory. let mut processor = Processor::new(preparation, config)?; @@ -136,12 +136,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); @@ -203,9 +203,10 @@ To prepare a processor, do these steps: limit. 3. Create a `Processor` with that preparation and a `ProcessorConfig`. -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`, `with_*` builders and stage +presets. To change active settings between blocks, call +`Processor::update_config` or `Processor::set_config`. To change the sample +rate or the block limit, make a new processor. Select the process function for your output layout: @@ -237,8 +238,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 or sub-stage event replaces all settings of that section. +`ControlEvent::Parameter` changes one parameter and keeps all other active +settings. Harmony MIDI uses `ControlEvent::Midi`. MIDI for the correction keyboard uses `ControlEvent::CorrectionMidi`. For example, this event starts a harmony note @@ -406,19 +408,20 @@ 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?)` | +| Mono PCM to planar stereo | `process(input, left, right, events?)` | +| In-place mono downmix | `processMono(audio, events?)` | +| Configuration | `config()`, `setConfig(config)`, `updateConfig(config)`, `defaultConfig()` | +| Scale masks and MIDI decode | `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,34 +439,37 @@ 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: +Configuration objects use camelCase names and show enums as string literals. +`new Tunelet` and `updateConfig` accept `DeepPartial`: -1. Start from `defaultConfig()` or `config()`. -2. Edit the necessary fields. -3. Call `setConfig()`. +- In `new Tunelet` and `setConfig`, omitted fields use their defaults. +- In `updateConfig`, omitted fields keep their active values. +- `defaultConfig()` and `config()` return complete configuration snapshots. -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. +`noteMaskFromKeyScale(key, scale)` builds a 12-boolean `NoteMask` for any +`CorrectionScale` or `HarmonyScale` mode. If a field value is not valid, the +call throws a JavaScript `Error` before 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 -`number`. +All numeric fields, `resynthesis.randomSeed` and `processedFrames` in feedback +and telemetry use `number`. Thus, `defaultConfig()`, `config()`, `feedback()` +and `telemetry()` work directly with `JSON.stringify`. ### 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. Stage and +sub-stage events replace that section, and `parameter` events update one field +without a `config()` copy: ```ts -{ offset: 0, event: { type: "outputGain", value: 0.5 } } +{ offset: 0, event: { type: "parameter", value: { type: "pitchRatio", value: 1.25 } } } ``` -A harmony Note On event has this form: +`parseMidiBytes(bytes)` decodes a 3-byte `Uint8Array` into a `MidiEvent` or +`undefined` for unsupported valid messages, and throws an `Error` for invalid +bytes. 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..d9d00bd 100644 --- a/src/config.rs +++ b/src/config.rs @@ -117,6 +117,19 @@ impl PrepareConfig { max_block_frames, }) } + + /// Sets the `sample_rate` and returns the preparation limits. + pub const fn with_sample_rate(mut self, sample_rate: SampleRate) -> Self { + self.sample_rate = sample_rate; + self + } + + /// Sets the nonzero `max_block_frames` limit and returns the preparation + /// limits. + 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(default, rename_all = "camelCase") )] pub struct ProcessorConfig { /// The input dynamics and saturation stage, which applies first. @@ -184,6 +196,43 @@ impl Default for ProcessorConfig { } impl ProcessorConfig { + /// Sets the `punch` stage configuration and returns the configuration. + pub const fn with_punch(mut self, punch: PunchConfig) -> Self { + self.punch = punch; + self + } + + /// Sets the `warm` stage configuration and returns the configuration. + pub const fn with_warm(mut self, warm: WarmConfig) -> Self { + self.warm = warm; + self + } + + /// Sets the `resynthesis` stage configuration and returns the + /// configuration. + pub const fn with_resynthesis(mut self, resynthesis: ResynthesisConfig) -> Self { + self.resynthesis = resynthesis; + self + } + + /// Sets the `alien` stage configuration and returns the configuration. + pub const fn with_alien(mut self, alien: AlienConfig) -> Self { + self.alien = alien; + self + } + + /// Sets the `reverb` stage configuration and returns the configuration. + pub const fn with_reverb(mut self, reverb: ReverbConfig) -> Self { + self.reverb = reverb; + self + } + + /// Sets the final linear gain, 0..=64, and returns the configuration. + pub const fn with_output_gain(mut self, output_gain: f32) -> Self { + self.output_gain = output_gain; + self + } + /// Checks all stages and the final gain, and does not change state. /// /// The validation uses the signal order: Punch, Warm, resynthesis, Alien, diff --git a/src/effects/alien.rs b/src/effects/alien.rs index 5e1f509..49b069c 100644 --- a/src/effects/alien.rs +++ b/src/effects/alien.rs @@ -21,7 +21,7 @@ const FADE_FRAMES: usize = 200; #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), derive(serde::Serialize, serde::Deserialize, tsify::Tsify), - serde(rename_all = "camelCase") + serde(default, rename_all = "camelCase") )] pub struct AlienConfig { /// Selects reversed playback instead of the direct input. The default is @@ -36,13 +36,36 @@ pub struct AlienConfig { } impl Default for AlienConfig { fn default() -> Self { + Self::new() + } +} +impl AlienConfig { + /// Returns the default disabled Alien settings. + const fn new() -> Self { Self { enabled: false, loop_frames: 95_999, } } -} -impl AlienConfig { + + /// Returns enabled Alien settings with the default loop length. + pub const fn enabled() -> Self { + Self::new().with_enabled(true) + } + + /// Sets `enabled` and returns the configuration. + pub const fn with_enabled(mut self, enabled: bool) -> Self { + self.enabled = enabled; + self + } + + /// Sets the loop length in frames, 1..=96000, and returns the + /// configuration. + pub const fn with_loop_frames(mut self, loop_frames: u32) -> Self { + self.loop_frames = loop_frames; + self + } + /// Validates all fields, also when Alien is disabled. /// /// `loop_frames` must be in its documented inclusive range. Validation diff --git a/src/effects/punch.rs b/src/effects/punch.rs index 867dc09..c159ce5 100644 --- a/src/effects/punch.rs +++ b/src/effects/punch.rs @@ -28,7 +28,7 @@ const TWO_OVER_PI: Q14 = Q14::from_bits(10430); #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), derive(serde::Serialize, serde::Deserialize, tsify::Tsify), - serde(rename_all = "camelCase") + serde(default, rename_all = "camelCase") )] pub struct PunchConfig { /// Enables this input stage. The default is `false`. @@ -57,6 +57,12 @@ pub struct PunchConfig { } impl Default for PunchConfig { fn default() -> Self { + Self::new() + } +} +impl PunchConfig { + /// Returns the default disabled Punch settings. + const fn new() -> Self { Self { enabled: false, gain_db: 0.0, @@ -65,8 +71,45 @@ impl Default for PunchConfig { attack_ms: 10.0, } } -} -impl PunchConfig { + + /// Returns enabled Punch settings with default controls. + pub const fn enabled() -> Self { + Self::new().with_enabled(true) + } + + /// Sets `enabled` and returns the configuration. + pub const fn with_enabled(mut self, enabled: bool) -> Self { + self.enabled = enabled; + self + } + + /// Sets the input gain in decibels, -96..=12, and returns the + /// configuration. + pub const fn with_gain_db(mut self, gain_db: f32) -> Self { + self.gain_db = gain_db; + self + } + + /// Sets the transient emphasis, 0..=1, and returns the configuration. + pub const fn with_impact(mut self, impact: f32) -> Self { + self.impact = impact; + self + } + + /// Sets the output ceiling in dBFS, -96..=0, and returns the + /// configuration. + pub const fn with_ceiling_db(mut self, ceiling_db: f32) -> Self { + self.ceiling_db = ceiling_db; + self + } + + /// Sets the attack half-life in milliseconds, 0.01..=5000, and returns the + /// configuration. + pub const fn with_attack_ms(mut self, attack_ms: f32) -> Self { + self.attack_ms = attack_ms; + self + } + /// Validates all fields, also when Punch is disabled. /// /// The floating-point controls must be finite and in their documented diff --git a/src/effects/reverb.rs b/src/effects/reverb.rs index fe60cd4..5c3d362 100644 --- a/src/effects/reverb.rs +++ b/src/effects/reverb.rs @@ -47,7 +47,7 @@ pub enum ReverbMode { #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), derive(serde::Serialize, serde::Deserialize, tsify::Tsify), - serde(rename_all = "camelCase") + serde(default, rename_all = "camelCase") )] pub struct ReverbConfig { /// Enables the selected network. The default is `false`. In bypass, the @@ -85,6 +85,12 @@ pub struct ReverbConfig { } impl Default for ReverbConfig { fn default() -> Self { + Self::new() + } +} +impl ReverbConfig { + /// Returns the default disabled reverb settings. + const fn new() -> Self { Self { enabled: false, mode: ReverbMode::Echo, @@ -94,8 +100,54 @@ impl Default for ReverbConfig { brightness_hz: 4000.0, } } -} -impl ReverbConfig { + + /// Returns enabled reverb settings with [`ReverbMode::Echo`]. + pub const fn enabled() -> Self { + Self::new().with_enabled(true) + } + + /// Returns enabled reverb settings with `mode` and default controls. + pub const fn from_mode(mode: ReverbMode) -> Self { + Self::enabled().with_mode(mode) + } + + /// Sets `enabled` and returns the configuration. + pub const fn with_enabled(mut self, enabled: bool) -> Self { + self.enabled = enabled; + self + } + + /// Sets the reverb network `mode` and returns the configuration. + pub const fn with_mode(mut self, mode: ReverbMode) -> Self { + self.mode = mode; + self + } + + /// Sets the wet fraction, 0..=1, and returns the configuration. + pub const fn with_mix(mut self, mix: f32) -> Self { + self.mix = mix; + self + } + + /// Sets the diffusion control, 0..=1, and returns the configuration. + pub const fn with_diffusion(mut self, diffusion: f32) -> Self { + self.diffusion = diffusion; + self + } + + /// Sets the feedback control, 0..=1, and returns the configuration. + pub const fn with_decay(mut self, decay: f32) -> Self { + self.decay = decay; + self + } + + /// Sets the low-pass cutoff in hertz, 80..=20000, and returns the + /// configuration. + pub const fn with_brightness_hz(mut self, brightness_hz: f32) -> Self { + self.brightness_hz = brightness_hz; + self + } + /// Validates all fields, also when the stage is disabled or the selected /// mode does not use a field. /// diff --git a/src/effects/warm.rs b/src/effects/warm.rs index 9721ced..67e1b46 100644 --- a/src/effects/warm.rs +++ b/src/effects/warm.rs @@ -21,7 +21,7 @@ const WINDOW_FRAMES: usize = 100; #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), derive(serde::Serialize, serde::Deserialize, tsify::Tsify), - serde(rename_all = "camelCase") + serde(default, rename_all = "camelCase") )] pub struct WarmConfig { /// Enables the saturation stage. The default is `false`. @@ -33,13 +33,35 @@ pub struct WarmConfig { } impl Default for WarmConfig { fn default() -> Self { + Self::new() + } +} +impl WarmConfig { + /// Returns the default disabled Warm settings. + const fn new() -> Self { Self { enabled: false, drive_db: 3.0, } } -} -impl WarmConfig { + + /// Returns enabled Warm settings with default drive. + pub const fn enabled() -> Self { + Self::new().with_enabled(true) + } + + /// Sets `enabled` and returns the configuration. + pub const fn with_enabled(mut self, enabled: bool) -> Self { + self.enabled = enabled; + self + } + + /// Sets the drive in decibels, 0..=6, and returns the configuration. + pub const fn with_drive_db(mut self, drive_db: f32) -> Self { + self.drive_db = drive_db; + self + } + /// Validates all fields, also when Warm is disabled. /// /// `drive_db` must be finite and in its documented inclusive range. diff --git a/src/events.rs b/src/events.rs index e1c975c..ba2217b 100644 --- a/src/events.rs +++ b/src/events.rs @@ -3,17 +3,283 @@ 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::{ReverbConfig, ReverbMode}; use crate::effects::warm::WarmConfig; +use crate::error::check_range; +use crate::formant::FormantConfig; +use crate::harmony::{ + ChordDegree, ChordName, HarmonyConfig, HarmonyScale, HarmonySource, Inversion, HARMONY_VOICES, +}; use crate::midi::MidiEvent; +use crate::pitch::PitchConfig; +use crate::resynthesis::{CorrectionConfig, MultiVoiceMode}; +use crate::scale::{NoteMask, PitchClass}; use crate::{Error, EventProblem, ProcessorConfig, ResynthesisConfig}; +/// A single parameter change inside [`ProcessorConfig`]. +/// +/// Use [`ControlEvent::Parameter`] to change one control at a frame offset and +/// keep all other active controls. Range and order checks match +/// [`ProcessorConfig::validate`]. +#[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + derive(serde::Serialize, serde::Deserialize, tsify::Tsify), + serde(rename_all = "camelCase", tag = "type", content = "value") +)] +pub enum ParameterControl { + /// Enables or disables Punch (`punch.enabled`). + PunchEnabled(bool), + /// Sets the Punch input gain in decibels (`punch.gain_db`), -96..=12. + PunchGainDb(f32), + /// Sets the Punch transient emphasis (`punch.impact`), 0..=1. + PunchImpact(f32), + /// Sets the Punch output ceiling in dBFS (`punch.ceiling_db`), -96..=0. + PunchCeilingDb(f32), + /// Sets the Punch attack half-life in milliseconds (`punch.attack_ms`), + /// 0.01..=5000. + PunchAttackMs(f32), + /// Enables or disables Warm (`warm.enabled`). + WarmEnabled(bool), + /// Sets the Warm drive in decibels (`warm.drive_db`), 0..=6. + WarmDriveDb(f32), + /// Sets the pitch acquisition threshold (`resynthesis.pitch.threshold`), + /// 0.002..=0.2. + PitchThreshold(f32), + /// Sets the lower pitch report bound in hertz + /// (`resynthesis.pitch.min_frequency_hz`), 40..=2000. + /// + /// Validation requires a value strictly below `max_frequency_hz`. + PitchMinFrequencyHz(f32), + /// Sets the upper pitch report bound in hertz + /// (`resynthesis.pitch.max_frequency_hz`), 40..=2000. + /// + /// Validation requires a value strictly above `min_frequency_hz`. + PitchMaxFrequencyHz(f32), + /// Enables or disables pitch correction + /// (`resynthesis.correction.enabled`). + CorrectionEnabled(bool), + /// Sets the correction pitch-class mask (`resynthesis.correction.notes`). + CorrectionNotes(NoteMask), + /// Sets the correction smoothing half-life in milliseconds + /// (`resynthesis.correction.retune_ms`), 0..=400. + CorrectionRetuneMs(f32), + /// Sets the global pitch multiplier (`resynthesis.pitch_ratio`), + /// 0.25..=4. + PitchRatio(f32), + /// Enables or disables formant analysis and synthesis + /// (`resynthesis.formant.enabled`). + FormantEnabled(bool), + /// Sets the vocal-tract width factor (`resynthesis.formant.width`), + /// 0.5..=2. + FormantWidth(f32), + /// Sets the vocal-tract length factor (`resynthesis.formant.stretch`), + /// 0.5..=2. + FormantStretch(f32), + /// Sets the aspiration level (`resynthesis.formant.aspiration_mix`), + /// 0..=1. + FormantAspirationMix(f32), + /// Sets the aspiration high-pass cutoff in hertz + /// (`resynthesis.formant.aspiration_cutoff_hz`), 500..=10000. + FormantAspirationCutoffHz(f32), + /// Sets the voice arrangement (`resynthesis.mode`). + ResynthesisMode(MultiVoiceMode), + /// Sets the total choir voice count (`resynthesis.choir_voices`), 1..=16. + ChoirVoices(u8), + /// Sets the secondary choir drift control (`resynthesis.choir_detune`), + /// 10..=100. + ChoirDetune(f32), + /// Sets the choir delay scale (`resynthesis.choir_delay`), 20..=200. + ChoirDelay(f32), + /// Sets the choir stereo width percentage + /// (`resynthesis.choir_spread_percent`), 0..=100. + ChoirSpreadPercent(f32), + /// Enables or disables a stereo pan for each voice + /// (`resynthesis.stereo_output`). + StereoOutput(bool), + /// Sets the harmony pitch source (`resynthesis.harmony.source`). + HarmonySource(HarmonySource), + /// Sets the harmony tonic key (`resynthesis.harmony.key`). + HarmonyKey(PitchClass), + /// Sets the harmony scale (`resynthesis.harmony.scale`). + HarmonyScale(HarmonyScale), + /// Sets the four chromatic semitone offsets + /// (`resynthesis.harmony.chromatic_intervals`), each in -24..=24. + HarmonyChromaticIntervals( + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + tsify(type = "[number, number, number, number]") + )] + [i8; HARMONY_VOICES], + ), + /// Sets the four diatonic scale-step offsets + /// (`resynthesis.harmony.diatonic_intervals`), each in -14..=14. + HarmonyDiatonicIntervals( + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + tsify(type = "[number, number, number, number]") + )] + [i8; HARMONY_VOICES], + ), + /// Sets the named harmony chord (`resynthesis.harmony.chord`). + HarmonyChord(ChordName), + /// Sets the scale-degree harmony chord (`resynthesis.harmony.degree`). + HarmonyDegree(ChordDegree), + /// Sets the harmony chord inversion (`resynthesis.harmony.inversion`). + HarmonyInversion(Inversion), + /// Sets the harmony chord register percentage + /// (`resynthesis.harmony.register_percent`), 0..=100. + HarmonyRegisterPercent(f32), + /// Sets the harmony voicing spread percentage + /// (`resynthesis.harmony.voicing_spread_percent`), 0..=100. + HarmonyVoicingSpreadPercent(f32), + /// Sets the harmony portamento half-life in milliseconds + /// (`resynthesis.harmony.portamento_ms`), 0..=10000. + HarmonyPortamentoMs(f32), + /// Sets the interval harmony voice count (`resynthesis.harmony.voices`), + /// 0..=4. + HarmonyVoices(u8), + /// Sets the stereo harmony pan gain (`resynthesis.harmony_gain`), 0..=1. + HarmonyGain(f32), + /// Sets the harmonic modulation depth (`resynthesis.harmonic_modulation`), + /// 0..=24. + HarmonicModulation(f32), + /// Sets the resynthesis dry fraction (`resynthesis.dry_mix`), 0..=1. + DryMix(f32), + /// Sets the 32-bit random seed (`resynthesis.random_seed`). + RandomSeed(u32), + /// Enables or disables Alien (`alien.enabled`). + AlienEnabled(bool), + /// Sets the Alien loop length in frames (`alien.loop_frames`), 1..=96000. + AlienLoopFrames(u32), + /// Enables or disables reverb (`reverb.enabled`). + ReverbEnabled(bool), + /// Sets the reverb network (`reverb.mode`). + ReverbMode(ReverbMode), + /// Sets the reverb wet fraction (`reverb.mix`), 0..=1. + ReverbMix(f32), + /// Sets the reverb diffusion control (`reverb.diffusion`), 0..=1. + ReverbDiffusion(f32), + /// Sets the reverb feedback control (`reverb.decay`), 0..=1. + ReverbDecay(f32), + /// Sets the reverb low-pass cutoff in hertz (`reverb.brightness_hz`), + /// 80..=20000. + ReverbBrightnessHz(f32), + /// Sets the final linear gain (`output_gain`), 0..=64. + OutputGain(f32), +} + +impl ParameterControl { + /// Writes this parameter value into `config`. + pub(crate) fn apply(self, config: &mut ProcessorConfig) { + match self { + Self::PunchEnabled(value) => config.punch.enabled = value, + Self::PunchGainDb(value) => config.punch.gain_db = value, + Self::PunchImpact(value) => config.punch.impact = value, + Self::PunchCeilingDb(value) => config.punch.ceiling_db = value, + Self::PunchAttackMs(value) => config.punch.attack_ms = value, + Self::WarmEnabled(value) => config.warm.enabled = value, + Self::WarmDriveDb(value) => config.warm.drive_db = value, + Self::PitchThreshold(value) => config.resynthesis.pitch.threshold = value, + Self::PitchMinFrequencyHz(value) => { + config.resynthesis.pitch.min_frequency_hz = value; + } + Self::PitchMaxFrequencyHz(value) => { + config.resynthesis.pitch.max_frequency_hz = value; + } + Self::CorrectionEnabled(value) => config.resynthesis.correction.enabled = value, + Self::CorrectionNotes(value) => config.resynthesis.correction.notes = value, + Self::CorrectionRetuneMs(value) => config.resynthesis.correction.retune_ms = value, + Self::PitchRatio(value) => config.resynthesis.pitch_ratio = value, + Self::FormantEnabled(value) => config.resynthesis.formant.enabled = value, + Self::FormantWidth(value) => config.resynthesis.formant.width = value, + Self::FormantStretch(value) => config.resynthesis.formant.stretch = value, + Self::FormantAspirationMix(value) => { + config.resynthesis.formant.aspiration_mix = value; + } + Self::FormantAspirationCutoffHz(value) => { + config.resynthesis.formant.aspiration_cutoff_hz = value; + } + Self::ResynthesisMode(value) => config.resynthesis.mode = value, + Self::ChoirVoices(value) => config.resynthesis.choir_voices = value, + Self::ChoirDetune(value) => config.resynthesis.choir_detune = value, + Self::ChoirDelay(value) => config.resynthesis.choir_delay = value, + Self::ChoirSpreadPercent(value) => { + config.resynthesis.choir_spread_percent = value; + } + Self::StereoOutput(value) => config.resynthesis.stereo_output = value, + Self::HarmonySource(value) => config.resynthesis.harmony.source = value, + Self::HarmonyKey(value) => config.resynthesis.harmony.key = value, + Self::HarmonyScale(value) => config.resynthesis.harmony.scale = value, + Self::HarmonyChromaticIntervals(value) => { + config.resynthesis.harmony.chromatic_intervals = value; + } + Self::HarmonyDiatonicIntervals(value) => { + config.resynthesis.harmony.diatonic_intervals = value; + } + Self::HarmonyChord(value) => config.resynthesis.harmony.chord = value, + Self::HarmonyDegree(value) => config.resynthesis.harmony.degree = value, + Self::HarmonyInversion(value) => config.resynthesis.harmony.inversion = value, + Self::HarmonyRegisterPercent(value) => { + config.resynthesis.harmony.register_percent = value; + } + Self::HarmonyVoicingSpreadPercent(value) => { + config.resynthesis.harmony.voicing_spread_percent = value; + } + Self::HarmonyPortamentoMs(value) => { + config.resynthesis.harmony.portamento_ms = value; + } + Self::HarmonyVoices(value) => config.resynthesis.harmony.voices = value, + Self::HarmonyGain(value) => config.resynthesis.harmony_gain = value, + Self::HarmonicModulation(value) => { + config.resynthesis.harmonic_modulation = value; + } + Self::DryMix(value) => config.resynthesis.dry_mix = value, + Self::RandomSeed(value) => config.resynthesis.random_seed = value, + Self::AlienEnabled(value) => config.alien.enabled = value, + Self::AlienLoopFrames(value) => config.alien.loop_frames = value, + Self::ReverbEnabled(value) => config.reverb.enabled = value, + Self::ReverbMode(value) => config.reverb.mode = value, + Self::ReverbMix(value) => config.reverb.mix = value, + Self::ReverbDiffusion(value) => config.reverb.diffusion = value, + Self::ReverbDecay(value) => config.reverb.decay = value, + Self::ReverbBrightnessHz(value) => config.reverb.brightness_hz = value, + Self::OutputGain(value) => config.output_gain = value, + } + } + + /// Checks the range of this parameter without a processor context. + /// + /// A block preflight also checks frequency-bound order against the active + /// configuration. + /// + /// # Errors + /// + /// Returns [`Error::InvalidConfig`] if the value is not finite or is out + /// of range. + pub fn validate(self) -> Result<(), Error> { + match self { + Self::PitchMinFrequencyHz(value) => { + check_range("resynthesis.pitch.min_frequency_hz", value, 40.0, 2000.0) + } + Self::PitchMaxFrequencyHz(value) => { + check_range("resynthesis.pitch.max_frequency_hz", value, 40.0, 2000.0) + } + other => { + let mut config = ProcessorConfig::default(); + other.apply(&mut config); + config.validate() + } + } + } +} + /// 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 or sub-stage event replaces all settings of that section. +/// [`Self::Parameter`] changes one field and keeps all other active settings. /// Configuration changes have the same effects on state as /// [`crate::Processor::set_config`]. #[derive(Clone, Copy, Debug, PartialEq)] @@ -27,6 +293,14 @@ pub enum ControlEvent { Configure(ProcessorConfig), /// This event replaces the resynthesis configuration. Resynthesis(ResynthesisConfig), + /// This event replaces the pitch configuration. + Pitch(PitchConfig), + /// This event replaces the pitch-correction configuration. + Correction(CorrectionConfig), + /// This event replaces the formant configuration. + Formant(FormantConfig), + /// This event replaces the harmony configuration. + Harmony(HarmonyConfig), /// This event replaces the Punch configuration. Punch(PunchConfig), /// This event replaces the Warm configuration. @@ -40,6 +314,9 @@ pub enum ControlEvent { /// The quantization and the mute behavior are the same as for /// [`ProcessorConfig::output_gain`]. The value must be finite. OutputGain(f32), + /// This event changes one configuration parameter and keeps all other + /// active settings. + Parameter(ParameterControl), /// This event sends a note control to the harmony source that /// [`crate::HarmonyConfig`] selects. /// @@ -66,25 +343,53 @@ impl ControlEvent { /// Checks the configuration or MIDI ranges of the event, and does not /// apply the event. /// + /// A process call also checks the offset, the slice order and cross-field + /// configuration invariants against the active settings. + /// /// # 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, + /// parameter or gain. Returns [`Error::InvalidMidi`] for invalid MIDI + /// fields. Reset is always valid. pub fn validate(self) -> Result<(), Error> { match self { Self::Configure(config) => config.validate(), Self::Resynthesis(config) => config.validate(), + Self::Pitch(config) => config.validate(), + Self::Correction(config) => config.validate(), + Self::Formant(config) => config.validate(), + Self::Harmony(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::Parameter(parameter) => parameter.validate(), Self::Midi(event) | Self::CorrectionMidi(event) => event.validate(), Self::Reset => Ok(()), } } + + /// Writes a configuration change into `config` and returns `true`, or + /// returns `false` for MIDI and reset events. + pub(crate) fn apply_to_config(self, config: &mut ProcessorConfig) -> bool { + match self { + Self::Configure(value) => *config = value, + Self::Resynthesis(value) => config.resynthesis = value, + Self::Pitch(value) => config.resynthesis.pitch = value, + Self::Correction(value) => config.resynthesis.correction = value, + Self::Formant(value) => config.resynthesis.formant = value, + Self::Harmony(value) => config.resynthesis.harmony = value, + Self::Punch(value) => config.punch = value, + Self::Warm(value) => config.warm = value, + Self::Alien(value) => config.alien = value, + Self::Reverb(value) => config.reverb = value, + Self::OutputGain(value) => config.output_gain = value, + Self::Parameter(parameter) => parameter.apply(config), + Self::Midi(_) | Self::CorrectionMidi(_) | Self::Reset => return false, + } + true + } } /// A control that applies immediately before the zero-based input frame @@ -134,19 +439,32 @@ impl ValidatedEvent { } impl<'a> ValidatedEvents<'a> { - /// Checks the offsets, the order and the payloads, in slice order. + /// Checks the offsets, the order and the payloads on a stack copy of + /// `config`, 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 { + pub(crate) fn new( + mut config: ProcessorConfig, + events: &'a [TimedEvent], + frames: usize, + ) -> Result { let mut previous = 0; for (index, event) in events.iter().enumerate() { let problem = if event.offset >= frames { Some(EventProblem::OffsetOutsideBlock) } else if event.offset < previous { Some(EventProblem::OffsetDecreasing) + } else if event.event.apply_to_config(&mut config) { + match config.validate() { + Ok(()) => None, + Err(Error::InvalidConfig { field, problem }) => { + Some(EventProblem::Config { field, problem }) + } + Err(_) => Some(EventProblem::Midi), + } } else { match event.event.validate() { Ok(()) => None, diff --git a/src/formant.rs b/src/formant.rs index 5072ee1..18f7825 100644 --- a/src/formant.rs +++ b/src/formant.rs @@ -41,7 +41,7 @@ use crate::{Error, SampleRate}; #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), derive(serde::Serialize, serde::Deserialize, tsify::Tsify), - serde(rename_all = "camelCase") + serde(default, rename_all = "camelCase") )] pub struct FormantConfig { /// Enables formant analysis and synthesis. The default is `false`. @@ -74,6 +74,12 @@ pub struct FormantConfig { } impl Default for FormantConfig { fn default() -> Self { + Self::new() + } +} +impl FormantConfig { + /// Returns the default disabled formant configuration. + const fn new() -> Self { Self { enabled: false, width: 1.0, @@ -82,8 +88,46 @@ impl Default for FormantConfig { aspiration_cutoff_hz: 4000.0, } } -} -impl FormantConfig { + + /// Returns enabled formant settings with unity width, unity stretch and no + /// aspiration. + pub const fn enabled() -> Self { + Self::new().with_enabled(true) + } + + /// Sets `enabled` and returns the configuration. + pub const fn with_enabled(mut self, enabled: bool) -> Self { + self.enabled = enabled; + self + } + + /// Sets the vocal-tract width factor, 0.5..=2, and returns the + /// configuration. + pub const fn with_width(mut self, width: f32) -> Self { + self.width = width; + self + } + + /// Sets the vocal-tract length factor, 0.5..=2, and returns the + /// configuration. + pub const fn with_stretch(mut self, stretch: f32) -> Self { + self.stretch = stretch; + self + } + + /// Sets the aspiration level, 0..=1, and returns the configuration. + pub const fn with_aspiration_mix(mut self, aspiration_mix: f32) -> Self { + self.aspiration_mix = aspiration_mix; + self + } + + /// Sets the high-pass cutoff for aspiration in hertz, 500..=10000, and + /// returns the configuration. + pub const fn with_aspiration_cutoff_hz(mut self, aspiration_cutoff_hz: f32) -> Self { + self.aspiration_cutoff_hz = aspiration_cutoff_hz; + self + } + /// Validates all fields, also if the formant stage is disabled. /// /// Each floating-point control must be finite and in its documented diff --git a/src/harmony.rs b/src/harmony.rs index 67b7111..a1c07ec 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-class mask of this scale with `key` as the tonic. + /// + /// The active pitch classes come from the semitone offsets of this scale. + /// [`Self::MajorWithoutSeventh`] enables six pitch classes, and the other + /// scales enable seven. + pub const fn note_mask(self, key: PitchClass) -> NoteMask { + let mut notes = [false; 12]; + let root = key.semitone() as usize; + let tones = &SCALE_TONES[self as usize]; + let mut index = 0; + while index < tones.len() { + notes[(root + tones[index] as usize) % 12] = true; + index += 1; + } + NoteMask(notes) + } +} + /// A named chord for [`HarmonySource::ChordByName`]. /// /// Each variant lists the semitones above the root. These values do not @@ -258,7 +277,7 @@ pub enum Inversion { #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), derive(serde::Serialize, serde::Deserialize, tsify::Tsify), - serde(rename_all = "camelCase") + serde(default, rename_all = "camelCase") )] pub struct HarmonyConfig { /// The pitch source. The default is [`HarmonySource::MidiChannels`]. @@ -322,22 +341,19 @@ 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) - )] 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::midi_channels() + } +} + +impl HarmonyConfig { + /// Returns harmony settings for [`HarmonySource::MidiChannels`], which is + /// the default. + pub const fn midi_channels() -> Self { Self { source: HarmonySource::MidiChannels, key: PitchClass::C, @@ -353,9 +369,145 @@ impl Default for HarmonyConfig { voices: HARMONY_VOICES as u8, } } -} -impl HarmonyConfig { + /// Returns harmony settings for [`HarmonySource::MidiOmni`]. + pub const fn midi_omni() -> Self { + Self::midi_channels().with_source(HarmonySource::MidiOmni) + } + + /// Returns harmony settings for [`HarmonySource::ChordViaMidi`]. + pub const fn chord_via_midi() -> Self { + Self::midi_channels().with_source(HarmonySource::ChordViaMidi) + } + + /// Returns harmony settings for [`HarmonySource::FixedInterval`] with four + /// semitone offsets, each in -24..=24. + pub const fn fixed_intervals(chromatic_intervals: [i8; HARMONY_VOICES]) -> Self { + Self::midi_channels() + .with_source(HarmonySource::FixedInterval) + .with_chromatic_intervals(chromatic_intervals) + } + + /// Returns harmony settings for [`HarmonySource::SmartInterval`] in `key` + /// and `scale` with four scale-step offsets, each in -14..=14. + pub const fn smart_intervals( + key: PitchClass, + scale: HarmonyScale, + diatonic_intervals: [i8; HARMONY_VOICES], + ) -> Self { + Self::midi_channels() + .with_source(HarmonySource::SmartInterval) + .with_key(key) + .with_scale(scale) + .with_diatonic_intervals(diatonic_intervals) + } + + /// Returns harmony settings for [`HarmonySource::ChordByDegree`] on + /// `degree` in `key` and `scale`. + pub const fn chord_by_degree( + key: PitchClass, + scale: HarmonyScale, + degree: ChordDegree, + ) -> Self { + Self::midi_channels() + .with_source(HarmonySource::ChordByDegree) + .with_key(key) + .with_scale(scale) + .with_degree(degree) + } + + /// Returns harmony settings for [`HarmonySource::ChordByName`] with root + /// `key` and chord `chord`. + pub const fn chord_by_name(key: PitchClass, chord: ChordName) -> Self { + Self::midi_channels() + .with_source(HarmonySource::ChordByName) + .with_key(key) + .with_chord(chord) + } + + /// Sets the harmony pitch `source` and returns the configuration. + pub const fn with_source(mut self, source: HarmonySource) -> Self { + self.source = source; + self + } + + /// Sets the tonic `key` and returns the configuration. + pub const fn with_key(mut self, key: PitchClass) -> Self { + self.key = key; + self + } + + /// Sets the harmony `scale` and returns the configuration. + pub const fn with_scale(mut self, scale: HarmonyScale) -> Self { + self.scale = scale; + self + } + + /// Sets the four chromatic semitone offsets, each in -24..=24, and returns + /// the configuration. + pub const fn with_chromatic_intervals( + mut self, + chromatic_intervals: [i8; HARMONY_VOICES], + ) -> Self { + self.chromatic_intervals = chromatic_intervals; + self + } + + /// Sets the four diatonic scale-step offsets, each in -14..=14, and + /// returns the configuration. + pub const fn with_diatonic_intervals( + mut self, + diatonic_intervals: [i8; HARMONY_VOICES], + ) -> Self { + self.diatonic_intervals = diatonic_intervals; + self + } + + /// Sets the named `chord` and returns the configuration. + pub const fn with_chord(mut self, chord: ChordName) -> Self { + self.chord = chord; + self + } + + /// Sets the scale `degree` chord and returns the configuration. + pub const fn with_degree(mut self, degree: ChordDegree) -> Self { + self.degree = degree; + self + } + + /// Sets the chord `inversion` and returns the configuration. + pub const fn with_inversion(mut self, inversion: Inversion) -> Self { + self.inversion = inversion; + self + } + + /// Sets the chord register percentage, 0..=100, and returns the + /// configuration. + pub const fn with_register_percent(mut self, register_percent: f32) -> Self { + self.register_percent = register_percent; + self + } + + /// Sets the voicing spread percentage, 0..=100, and returns the + /// configuration. + pub const fn with_voicing_spread_percent(mut self, voicing_spread_percent: f32) -> Self { + self.voicing_spread_percent = voicing_spread_percent; + self + } + + /// Sets the portamento half-life in milliseconds, 0..=10000, and returns + /// the configuration. + pub const fn with_portamento_ms(mut self, portamento_ms: f32) -> Self { + self.portamento_ms = portamento_ms; + self + } + + /// Sets the interval voice count, 0..=4, and returns the configuration. + pub const fn with_voices(mut self, voices: u8) -> Self { + self.voices = voices; + self + } + /// Validates all fields, which includes the fields that the selected /// source does not use. /// diff --git a/src/harmony/chords.rs b/src/harmony/chords.rs index 45c38f6..94652e1 100644 --- a/src/harmony/chords.rs +++ b/src/harmony/chords.rs @@ -13,7 +13,7 @@ use crate::numeric::fixed::{Q12, Q6}; /// Seven semitone offsets of the degrees for each `HarmonyScale`. /// `MajorWithoutSeventh` repeats its sixth in the last slot to keep seven /// degrees. -pub(super) const SCALE_TONES: [[i32; 7]; 7] = [ +pub(crate) const SCALE_TONES: [[i32; 7]; 7] = [ [0, 2, 4, 5, 7, 9, 11], [0, 2, 4, 5, 7, 9, 9], [0, 2, 4, 5, 7, 9, 10], diff --git a/src/index.ts b/src/index.ts index da35a57..8ace398 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,16 +1,18 @@ /** * 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 + * Call `loadTunelet()` before you construct processors or call the exported + * 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`, - * `initSync` and the configuration, event and feedback types. + * `noteMaskFromKeyScale`, `parseMidiBytes`, `initSync`, `DeepPartial` and the + * configuration, event and feedback types. */ import init, { initSync } from "../pkg/tunelet.js"; import type { InitInput, InitOutput } from "../pkg/tunelet.js"; export * from "../pkg/tunelet.js"; +export type { DeepPartial } from "../pkg/tunelet.js"; /** The shared initialization promise, which a failure clears. */ let initialization: Promise | undefined; diff --git a/src/lib.rs b/src/lib.rs index 0e29119..37d30d4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -10,19 +10,20 @@ //! //! [`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. +//! [`ProcessorConfig`], start from its default value and use its `with_*` +//! builders or stage presets, or edit 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. //! //! 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`] and [`ParameterControl`]. To change +//! the sample rate or the block limit, you must make a new processor. //! //! # Audio and timed controls //! @@ -127,7 +128,7 @@ pub use effects::punch::PunchConfig; pub use effects::reverb::{ReverbConfig, ReverbMode}; pub use effects::warm::WarmConfig; pub use error::{ConfigProblem, Error, EventProblem}; -pub use events::{ControlEvent, TimedEvent}; +pub use events::{ControlEvent, ParameterControl, TimedEvent}; pub use formant::FormantConfig; pub use harmony::{ ChordDegree, ChordName, HarmonyConfig, HarmonyScale, HarmonySource, Inversion, HARMONY_VOICES, diff --git a/src/pitch.rs b/src/pitch.rs index 6b682ca..98f20f7 100644 --- a/src/pitch.rs +++ b/src/pitch.rs @@ -17,7 +17,7 @@ use crate::Error; #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), derive(serde::Serialize, serde::Deserialize, tsify::Tsify), - serde(rename_all = "camelCase") + serde(default, rename_all = "camelCase") )] pub struct PitchConfig { /// The normalized cycle-difference threshold for acquisition, 0.002..=0.2. @@ -43,15 +43,60 @@ pub struct PitchConfig { impl Default for PitchConfig { fn default() -> Self { + Self::new() + } +} + +impl PitchConfig { + /// Returns the default pitch configuration. + const fn new() -> Self { Self { threshold: 0.1, min_frequency_hz: 40.0, max_frequency_hz: 1100.0, } } -} -impl PitchConfig { + /// Sets the acquisition threshold, 0.002..=0.2, and returns the + /// configuration. + pub const fn with_threshold(mut self, threshold: f32) -> Self { + self.threshold = threshold; + self + } + + /// Sets the lower frequency bound in hertz, 40..=2000, and returns the + /// configuration. + /// + /// Validation requires a value strictly below `max_frequency_hz`. + pub const fn with_min_frequency_hz(mut self, min_frequency_hz: f32) -> Self { + self.min_frequency_hz = min_frequency_hz; + self + } + + /// Sets the upper frequency bound in hertz, 40..=2000, and returns the + /// configuration. + /// + /// Validation requires a value strictly above `min_frequency_hz`. + pub const fn with_max_frequency_hz(mut self, max_frequency_hz: f32) -> Self { + self.max_frequency_hz = max_frequency_hz; + self + } + + /// Sets the lower and upper frequency bounds in hertz, each in 40..=2000, + /// and returns the configuration. + /// + /// Validation requires `min_frequency_hz` strictly below + /// `max_frequency_hz`. + pub const fn with_frequency_range_hz( + mut self, + min_frequency_hz: f32, + max_frequency_hz: f32, + ) -> Self { + self.min_frequency_hz = min_frequency_hz; + self.max_frequency_hz = max_frequency_hz; + self + } + /// 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 diff --git a/src/processor.rs b/src/processor.rs index cc910f4..a685006 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -88,7 +88,7 @@ impl Processor { /// 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`. + /// 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 @@ -114,7 +114,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 +467,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 +479,26 @@ impl Processor { Ok(()) } + /// Edits a stack copy of the active configuration, validates the result + /// and applies it. + /// + /// State retention, drain cancellation and validation follow + /// [`set_config`](Self::set_config). + /// + /// # Errors + /// + /// Returns [`Error::InvalidConfig`] if a field is not valid after + /// `update`. On error, all processor state and any active drain stay the + /// same. + 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 { @@ -500,7 +519,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 +576,7 @@ impl Processor { events: &'a [TimedEvent], ) -> Result, Error> { self.check_block(input.len())?; - ValidatedEvents::new(events, input.len()) + ValidatedEvents::new(self.config, events, input.len()) } /// Enforces the prepared block limit for each call. @@ -573,33 +592,22 @@ impl Processor { /// Applies a validated control immediately before its frame is rendered. /// - /// A partial configuration event replaces one stage in the active - /// configuration. MIDI and reset events act directly. A reset does not - /// discard later events in the block. + /// A configuration, stage, sub-stage or parameter event updates a copy of + /// the active settings and applies the result. MIDI and reset events act + /// directly. A reset does not discard later events in the block. fn apply(&mut self, event: ValidatedEvent) { + let inner = event.into_inner(); let mut config = self.config; - match event.into_inner() { - ControlEvent::Configure(value) => config = value, - ControlEvent::Resynthesis(value) => config.resynthesis = value, - ControlEvent::Punch(value) => config.punch = value, - ControlEvent::Warm(value) => config.warm = value, - ControlEvent::Alien(value) => config.alien = value, - ControlEvent::Reverb(value) => config.reverb = value, - ControlEvent::OutputGain(value) => config.output_gain = value, - ControlEvent::Midi(event) => { - self.resynthesis.apply_midi(event); - return; - } - ControlEvent::CorrectionMidi(event) => { - self.resynthesis.apply_correction_midi(event); - return; - } - ControlEvent::Reset => { - self.reset(); - return; - } + if inner.apply_to_config(&mut config) { + self.apply_config(config); + return; + } + match inner { + ControlEvent::Midi(event) => self.resynthesis.apply_midi(event), + ControlEvent::CorrectionMidi(event) => self.resynthesis.apply_correction_midi(event), + ControlEvent::Reset => self.reset(), + _ => {} } - self.apply_config(config); } /// Renders one frame through the full chain and updates stereo feedback. @@ -707,8 +715,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,6 +772,11 @@ pub struct Feedback { /// /// The count saturates at `u64::MAX`. Drain completion resets it in the /// last drain call. + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + serde(serialize_with = "crate::wasm::serialize_processed_frames"), + tsify(type = "number") + )] pub processed_frames: u64, /// The nominal resynthesis latency, as [`Processor::latency_frames`] gives. #[cfg_attr( @@ -790,12 +802,16 @@ 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_processed_frames"), + tsify(type = "number") + )] 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..cd0bca1 100644 --- a/src/resynthesis.rs +++ b/src/resynthesis.rs @@ -38,7 +38,7 @@ 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::scale::{CorrectionTable, NoteMask}; +use crate::scale::{CorrectionScale, CorrectionTable, NoteMask, PitchClass}; use crate::{Error, SampleRate}; use history::prepare_history; @@ -84,7 +84,7 @@ pub enum MultiVoiceMode { #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), derive(serde::Serialize, serde::Deserialize, tsify::Tsify), - serde(rename_all = "camelCase") + serde(default, rename_all = "camelCase") )] pub struct CorrectionConfig { /// Enables the selection of correction targets. The default is `true`. @@ -110,15 +110,50 @@ pub struct CorrectionConfig { impl Default for CorrectionConfig { fn default() -> Self { + Self::new() + } +} + +impl CorrectionConfig { + /// Returns the default chromatic correction settings. + const fn new() -> Self { Self { enabled: true, - notes: NoteMask::default(), + notes: NoteMask::CHROMATIC, retune_ms: 0.0, } } -} -impl CorrectionConfig { + /// Returns disabled correction settings with chromatic target notes. + pub const fn disabled() -> Self { + Self::new().with_enabled(false) + } + + /// Returns enabled correction settings for `key` and `scale`, with a + /// retune time of zero. + pub const fn from_key_scale(key: PitchClass, scale: CorrectionScale) -> Self { + Self::new().with_notes(NoteMask::from_key_scale(key, scale)) + } + + /// Sets `enabled` and returns the configuration. + pub const fn with_enabled(mut self, enabled: bool) -> Self { + self.enabled = enabled; + self + } + + /// Sets the target pitch-class `notes` and returns the configuration. + pub const fn with_notes(mut self, notes: NoteMask) -> Self { + self.notes = notes; + self + } + + /// Sets the smoothing half-life in milliseconds, 0..=400, and returns the + /// configuration. + pub const fn with_retune_ms(mut self, retune_ms: f32) -> Self { + self.retune_ms = retune_ms; + self + } + /// Validates all fields, also if correction is disabled. /// /// All values of `enabled` and `notes` are valid. `retune_ms` must be @@ -162,8 +197,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(default, rename_all = "camelCase") )] pub struct ResynthesisConfig { /// The acquisition sensitivity and the reporting bounds. The @@ -245,37 +279,161 @@ pub struct ResynthesisConfig { /// The seed for choir drift and aspiration, which use the same stream. /// 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, + /// 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 { fn default() -> Self { + Self::new() + } +} + +impl ResynthesisConfig { + /// Returns the default resynthesis settings. + const fn new() -> Self { Self { - pitch: PitchConfig::default(), - correction: CorrectionConfig::default(), + pitch: PitchConfig { + threshold: 0.1, + min_frequency_hz: 40.0, + max_frequency_hz: 1100.0, + }, + correction: CorrectionConfig::new(), pitch_ratio: 1.0, - formant: FormantConfig::default(), + formant: FormantConfig { + enabled: false, + width: 1.0, + stretch: 1.0, + aspiration_mix: 0.0, + aspiration_cutoff_hz: 4000.0, + }, mode: MultiVoiceMode::Choir, choir_voices: 1, choir_detune: 50.0, choir_delay: 60.0, choir_spread_percent: 100.0, stereo_output: false, - harmony: HarmonyConfig::default(), + harmony: HarmonyConfig::midi_channels(), harmony_gain: 0.5, harmonic_modulation: 0.0, dry_mix: 0.0, random_seed: 0x1234_abcd, } } -} -impl ResynthesisConfig { + /// Returns resynthesis settings in [`MultiVoiceMode::Choir`] with `voices` + /// total voices, 1..=16. + pub const fn choir(voices: u8) -> Self { + Self::new() + .with_mode(MultiVoiceMode::Choir) + .with_choir_voices(voices) + } + + /// Returns resynthesis settings in [`MultiVoiceMode::Harmony`] with + /// `harmony`. + pub const fn harmony(harmony: HarmonyConfig) -> Self { + Self::new() + .with_mode(MultiVoiceMode::Harmony) + .with_harmony(harmony) + } + + /// Sets the `pitch` configuration and returns the configuration. + pub const fn with_pitch(mut self, pitch: PitchConfig) -> Self { + self.pitch = pitch; + self + } + + /// Sets the `correction` configuration and returns the configuration. + pub const fn with_correction(mut self, correction: CorrectionConfig) -> Self { + self.correction = correction; + self + } + + /// Sets the pitch multiplier, 0.25..=4, and returns the configuration. + pub const fn with_pitch_ratio(mut self, pitch_ratio: f32) -> Self { + self.pitch_ratio = pitch_ratio; + self + } + + /// Sets the `formant` configuration and returns the configuration. + pub const fn with_formant(mut self, formant: FormantConfig) -> Self { + self.formant = formant; + self + } + + /// Sets the voice arrangement `mode` and returns the configuration. + pub const fn with_mode(mut self, mode: MultiVoiceMode) -> Self { + self.mode = mode; + self + } + + /// Sets the total choir voice count, 1..=16, and returns the + /// configuration. + pub const fn with_choir_voices(mut self, choir_voices: u8) -> Self { + self.choir_voices = choir_voices; + self + } + + /// Sets the secondary choir drift control, 10..=100, and returns the + /// configuration. + pub const fn with_choir_detune(mut self, choir_detune: f32) -> Self { + self.choir_detune = choir_detune; + self + } + + /// Sets the choir delay scale, 20..=200, and returns the configuration. + pub const fn with_choir_delay(mut self, choir_delay: f32) -> Self { + self.choir_delay = choir_delay; + self + } + + /// Sets the choir stereo width percentage, 0..=100, and returns the + /// configuration. + pub const fn with_choir_spread_percent(mut self, choir_spread_percent: f32) -> Self { + self.choir_spread_percent = choir_spread_percent; + self + } + + /// Sets `stereo_output` and returns the configuration. + pub const fn with_stereo_output(mut self, stereo_output: bool) -> Self { + self.stereo_output = stereo_output; + self + } + + /// Sets the `harmony` configuration and returns the configuration. + pub const fn with_harmony(mut self, harmony: HarmonyConfig) -> Self { + self.harmony = harmony; + self + } + + /// Sets the stereo harmony pan gain, 0..=1, and returns the configuration. + pub const fn with_harmony_gain(mut self, harmony_gain: f32) -> Self { + self.harmony_gain = harmony_gain; + self + } + + /// Sets the harmonic modulation depth, 0..=24, and returns the + /// configuration. + pub const fn with_harmonic_modulation(mut self, harmonic_modulation: f32) -> Self { + self.harmonic_modulation = harmonic_modulation; + self + } + + /// Sets the dry fraction, 0..=1, and returns the configuration. + pub const fn with_dry_mix(mut self, dry_mix: f32) -> Self { + self.dry_mix = dry_mix; + self + } + + /// Sets the 32-bit `random_seed` and returns the configuration. + pub const fn with_random_seed(mut self, random_seed: u32) -> Self { + self.random_seed = random_seed; + self + } + /// Validates all fields, also the settings for stages that are disabled /// or not active. /// diff --git a/src/scale.rs b/src/scale.rs index 01c4f94..664c003 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; @@ -72,15 +73,39 @@ 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: semitone offsets 0, 2, 4, 5, 7, 9. + MajorWithoutSeventh, + /// Major with a flat seventh (mixolydian): 0, 2, 4, 5, 7, 9, 10. + MajorFlatSeventh, + /// Natural minor (aeolian): 0, 2, 3, 5, 7, 8, 10. Minor, + /// Harmonic minor: 0, 2, 3, 5, 7, 8, 11. + HarmonicMinor, + /// Minor with a natural sixth (dorian): 0, 2, 3, 5, 7, 9, 10. + MinorNaturalSixth, + /// Minor with a major seventh: 0, 2, 3, 5, 7, 9, 11. + MinorMajorSeventh, /// The chromatic scale with all 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 +144,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; + /// Each modal variant uses the semitone offsets of [`HarmonyScale`]. + /// Chromatic permits all classes for all keys. This function only makes a + /// value. To apply the value, use [`crate::CorrectionConfig`]. + pub const fn from_key_scale(key: PitchClass, scale: CorrectionScale) -> Self { + match scale { + CorrectionScale::Major => HarmonyScale::Major.note_mask(key), + CorrectionScale::MajorWithoutSeventh => { + HarmonyScale::MajorWithoutSeventh.note_mask(key) + } + CorrectionScale::MajorFlatSeventh => HarmonyScale::MajorFlatSeventh.note_mask(key), + CorrectionScale::Minor => HarmonyScale::Minor.note_mask(key), + CorrectionScale::HarmonicMinor => HarmonyScale::HarmonicMinor.note_mask(key), + CorrectionScale::MinorNaturalSixth => HarmonyScale::MinorNaturalSixth.note_mask(key), + CorrectionScale::MinorMajorSeventh => HarmonyScale::MinorMajorSeventh.note_mask(key), + CorrectionScale::Chromatic => 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])) } } diff --git a/src/wasm.rs b/src/wasm.rs index c9cec08..2fad666 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -18,11 +18,16 @@ //! //! - Field names use camelCase. //! - Enum values are strings. -//! - Each object must contain all required fields. -//! - The optional harmony `voices` field defaults to 4. +//! - Omitted configuration fields in the constructor or `setConfig` use their +//! defaults. +//! - Omitted fields in `updateConfig` keep their active values. +//! - Numeric fields use `number`, so configurations, feedback and telemetry +//! work with `JSON.stringify`. //! -//! [`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`] +//! builds a 12-note mask from a key and a scale, and [`parse_midi_bytes`] +//! decodes a 3-byte MIDI message. 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,12 +47,33 @@ //! `free()` method. use crate::{ - Error, Feedback, PrepareConfig, Processor, ProcessorConfig, SampleRate, Telemetry, TimedEvent, + CorrectionScale, Error, Feedback, MidiEvent, NoteMask, PitchClass, PrepareConfig, Processor, + ProcessorConfig, SampleRate, Telemetry, TimedEvent, }; -use js_sys::{Float32Array, Int16Array}; +use js_sys::{Array, Float32Array, Int16Array, Object, Reflect, Uint8Array}; use serde::{Deserialize, Serialize}; use tsify::{Ts, Tsify}; use wasm_bindgen::prelude::*; +use wasm_bindgen::JsCast; + +#[wasm_bindgen(typescript_custom_section)] +const TS_DEEP_PARTIAL: &'static str = r#"/** + * Makes each object property of `T` optional at every depth, and keeps arrays + * and tuples unchanged. + */ +export type DeepPartial = 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). /// @@ -62,10 +88,10 @@ pub struct BlockEvents(Vec); /// 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 are JavaScript `number` values. After the binding +/// decodes them, floating-point controls have the precision of the Rust `f32` +/// type. /// /// # Errors /// @@ -76,6 +102,47 @@ pub fn default_config() -> Result, JsError> { Ok(ProcessorConfig::default().into_ts()?) } +/// Returns the 12-note boolean mask for `key` and `scale`. +/// +/// Index 0 is C and index 11 is B. Give the returned mask to +/// `resynthesis.correction.notes` or a `correctionNotes` parameter event. +/// +/// # Errors +/// +/// Throws a JavaScript `Error` if `key` or `scale` is not a valid variant +/// 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 complete 3-byte MIDI message, as [`MidiEvent::from_bytes`] +/// does. +/// +/// Note On with velocity 0 returns a `noteOff` object. Other messages with +/// valid status and data bytes return `undefined`. System-exclusive data and +/// running status are not supported. +/// +/// # Errors +/// +/// Throws a JavaScript `Error` if `bytes` does not have length 3, 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: &Uint8Array) -> Result>, JsError> { + if bytes.length() != 3 { + return Err(Error::InvalidMidi.into()); + } + let mut raw = [0; 3]; + bytes.copy_to(&mut raw); + Ok(match MidiEvent::from_bytes(raw)? { + Some(event) => Some(event.into_ts()?), + None => 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 +188,11 @@ 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. If you omit `config` or omit + /// fields inside it, the processor uses the default values for those + /// fields. 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 +200,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. /// - The configuration is not valid. /// - The reservation of a PCM buffer fails. /// @@ -142,7 +210,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 +229,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) => merge_processor_config(ProcessorConfig::default(), value.as_ref())?, None => ProcessorConfig::default(), }; let processor = Processor::new(preparation, config)?; @@ -202,8 +270,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 +283,36 @@ 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 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. - /// After an error, all processor state and any active drain stay the same. + /// The method throws if an object or field value is not valid. 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 merged = merge_processor_config(ProcessorConfig::default(), &JsValue::from(config))?; + self.processor.set_config(merged)?; + Ok(()) + } + + /// Merges a partial configuration onto the active configuration, validates + /// the result and applies it. + /// + /// Omitted fields keep their active values. State retention and drain + /// cancellation follow `setConfig`. + /// + /// # Errors + /// + /// The method throws if `config` is not an object or if a field value is + /// not valid. After an error, all processor state and any active drain + /// stay the same. + #[wasm_bindgen(js_name = updateConfig)] + pub fn update_config(&mut self, config: PartialProcessorConfig) -> Result<(), JsError> { + let merged = merge_processor_config(self.processor.config(), config.as_ref())?; + self.processor.set_config(merged)?; Ok(()) } @@ -356,8 +444,8 @@ 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 numbers. See `Feedback` for + /// each measurement. /// /// `targetMidiNote` is `undefined` in these cases, which are also the /// cases where `voiced` is `false`: @@ -394,7 +482,7 @@ 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 + /// the state of the effects. `processedFrames` is a number. See /// `Telemetry` for each measurement. /// /// # Errors @@ -487,6 +575,55 @@ impl WasmProcessor { } } +/// Returns `true` if `value` is a non-null, non-array, non-function object. +fn is_plain_record(value: &JsValue) -> bool { + value.is_object() && !value.is_null() && !Array::is_array(value) && !value.is_function() +} + +/// Copies defined known properties from `patch` into `target`, and merges +/// nested configuration objects. +fn merge_records(target: &JsValue, patch: &JsValue) -> Result<(), JsError> { + let (Some(target_object), Some(patch_object)) = + (target.dyn_ref::(), patch.dyn_ref::()) + else { + return Err(JsError::new("expected a configuration object")); + }; + for pair in Object::entries(patch_object).iter() { + let pair = Array::from(&pair); + let key = pair.get(0); + let value = pair.get(1); + if value.is_undefined() || !Object::has_own(target_object, &key) { + continue; + } + let current = Reflect::get(target, &key) + .map_err(|_| JsError::new("failed to read configuration field"))?; + if is_plain_record(¤t) && is_plain_record(&value) { + merge_records(¤t, &value)?; + } else { + let ok = Reflect::set(target, &key, &value) + .map_err(|_| JsError::new("failed to write configuration field"))?; + if !ok { + return Err(JsError::new("failed to write configuration field")); + } + } + } + Ok(()) +} + +/// Merges a partial JavaScript configuration object onto `base` and decodes the +/// result. +fn merge_processor_config( + base: ProcessorConfig, + patch: &JsValue, +) -> Result { + if !is_plain_record(patch) { + return Err(JsError::new("expected a configuration object")); + } + let target: JsValue = base.into_ts()?.into(); + merge_records(&target, patch)?; + Ok(Ts::::new_unchecked(target).to_rust()?) +} + /// Decodes the optional block controls before the audio state changes. /// /// If there is no value, the result is an empty `Vec`, and no allocation @@ -522,11 +659,17 @@ fn pcm_buffer(frames: usize) -> Result, JsError> { Ok(buffer) } +/// Serializes the 64-bit processed frame counter as a JavaScript number. +pub(crate) fn serialize_processed_frames( + frames: &u64, + serializer: S, +) -> Result { + serializer.serialize_f64(*frames as f64) +} + /// 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`. +/// This module compiles only for wasm32, where every `usize` fits in a `u32`. pub(crate) fn serialize_frame_count( frames: &usize, serializer: S,