From ae741b7a020b280874040f6d572a8e0147884448 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:39:45 +0000 Subject: [PATCH 1/3] feat: add vocal presets, scales and semitone helpers - Add seven musical scales to CorrectionScale and NoteMask. - Add Preset and ProcessorConfig::from_preset for five vocal chains. - Add semitones_to_ratio and ratio_to_semitones with range checks. - Export the scale, preset and semitone helpers from Wasm. - Update the README quick start and the TypeScript API table. --- README.md | 48 ++++++++------- src/config.rs | 159 +++++++++++++++++++++++++++++++++++++++++++++++++- src/lib.rs | 9 ++- src/scale.rs | 73 ++++++++++++++++------- src/wasm.rs | 70 ++++++++++++++++++++-- 5 files changed, 308 insertions(+), 51 deletions(-) diff --git a/README.md b/README.md index d2993dc..bdd8214 100644 --- a/README.md +++ b/README.md @@ -136,11 +136,18 @@ fn main() -> Result<(), tunelet::Error> { ### TypeScript ```ts -import { loadTunelet, Tunelet, defaultConfig } from "tunelet"; +import { + loadTunelet, + Tunelet, + defaultConfig, + noteMaskFromKeyScale, + semitonesToRatio, +} from "tunelet"; await loadTunelet(); const config = defaultConfig(); -config.resynthesis.pitchRatio = 1.25; +config.resynthesis.correction.notes = noteMaskFromKeyScale("a", "minor"); +config.resynthesis.pitchRatio = semitonesToRatio(4); const processor = new Tunelet(48000, 1024, config); const input = new Int16Array(1024); @@ -203,9 +210,9 @@ 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`, and `ProcessorConfig::from_preset` +returns vocal presets. To select voices and effects, edit their fields. To +change the sample rate or the block limit, make a new processor. Select the process function for your output layout: @@ -363,7 +370,7 @@ these items: Both environments use the same imports and the same initialization call. An import of the package does not load the binary. Call `loadTunelet()` before -you use `Tunelet` or `defaultConfig()`. +you use `Tunelet`, `defaultConfig()` or the other helper functions. - Node.js reads the packaged binary from a file URL relative to the module. - Browsers fetch the served Wasm asset. @@ -406,19 +413,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)`, `defaultConfig()`, `presetConfig(preset)` | +| Scales and pitch ratios | `noteMaskFromKeyScale(key, scale)`, `semitonesToRatio(semitones)`, `ratioToSemitones(ratio)` | +| 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 @@ -439,7 +447,7 @@ audio device. Configuration objects contain all required fields. They use camelCase names and show enums as string literals. To change the configuration, do these steps: -1. Start from `defaultConfig()` or `config()`. +1. Start from `defaultConfig()`, `presetConfig(preset)` or `config()`. 2. Edit the necessary fields. 3. Call `setConfig()`. diff --git a/src/config.rs b/src/config.rs index 75bcd82..721efa0 100644 --- a/src/config.rs +++ b/src/config.rs @@ -2,11 +2,13 @@ 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, ConfigProblem}; +use crate::harmony::{HarmonyScale, HarmonySource}; +use crate::resynthesis::{MultiVoiceMode, ResynthesisConfig}; +use crate::scale::{CorrectionScale, NoteMask, PitchClass}; use crate::Error; -use crate::ResynthesisConfig; use std::num::NonZeroUsize; /// The sample rate of the input and the output. @@ -183,7 +185,130 @@ impl Default for ProcessorConfig { } } +/// A preset vocal chain for [`ProcessorConfig::from_preset`]. +/// +/// Each preset returns a complete [`ProcessorConfig`] that passes +/// [`ProcessorConfig::validate`]. You can edit any field before you give the +/// configuration to [`crate::Processor::new`] or +/// [`crate::Processor::set_config`]. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + derive(serde::Serialize, serde::Deserialize, tsify::Tsify), + serde(rename_all = "camelCase") +)] +pub enum Preset { + /// Gentle chromatic correction (`retune_ms` = 35), subtle Warm drive and a + /// `SmallRoom` reverb. This is the default preset. + #[default] + NaturalTune, + /// Instant chromatic correction (`retune_ms` = 0), Punch transient emphasis, + /// active formants with light aspiration and a `MediumHall` reverb. + HardPopTune, + /// Eight stereo choir voices with Warm saturation, a `LargeHall` reverb and + /// an output gain of 0.35 to prevent overload. + LushChoir, + /// Stereo smart-interval harmony in C major (a third and a fifth above the + /// lead), C major correction and a `MediumHall` reverb. + DiatonicHarmony, + /// Punch and Warm dynamics, disabled pitch correction and subtle formant + /// depth with a 0.25 dry mix for speech. + WarmBroadcast, +} + impl ProcessorConfig { + /// Returns a validated configuration for `preset`. + /// + /// Edit the returned copy to set a key, a scale or stage levels before you + /// apply it. [`Preset::LushChoir`] sets `output_gain` to 0.35 so that the + /// sum of the eight choir voices does not overload the output. + pub fn from_preset(preset: Preset) -> Self { + let mut config = Self::default(); + match preset { + Preset::NaturalTune => { + config.warm.enabled = true; + config.warm.drive_db = 1.5; + config.resynthesis.correction.retune_ms = 35.0; + config.reverb.enabled = true; + config.reverb.mode = ReverbMode::SmallRoom; + config.reverb.mix = 0.12; + config.reverb.decay = 0.35; + config.reverb.brightness_hz = 6000.0; + } + Preset::HardPopTune => { + config.punch.enabled = true; + config.punch.gain_db = 2.0; + config.punch.impact = 0.6; + config.punch.ceiling_db = -1.5; + config.punch.attack_ms = 5.0; + config.resynthesis.correction.retune_ms = 0.0; + config.resynthesis.formant.enabled = true; + config.resynthesis.formant.aspiration_mix = 0.05; + config.resynthesis.formant.aspiration_cutoff_hz = 5000.0; + config.reverb.enabled = true; + config.reverb.mode = ReverbMode::MediumHall; + config.reverb.mix = 0.15; + config.reverb.diffusion = 0.6; + config.reverb.decay = 0.45; + config.reverb.brightness_hz = 7000.0; + } + Preset::LushChoir => { + config.warm.enabled = true; + config.warm.drive_db = 2.0; + config.resynthesis.correction.retune_ms = 25.0; + config.resynthesis.mode = MultiVoiceMode::Choir; + config.resynthesis.choir_voices = 8; + config.resynthesis.choir_detune = 55.0; + config.resynthesis.choir_delay = 110.0; + config.resynthesis.choir_spread_percent = 100.0; + config.resynthesis.stereo_output = true; + config.reverb.enabled = true; + config.reverb.mode = ReverbMode::LargeHall; + config.reverb.mix = 0.3; + config.reverb.diffusion = 0.7; + config.reverb.decay = 0.65; + config.reverb.brightness_hz = 5000.0; + config.output_gain = 0.35; + } + Preset::DiatonicHarmony => { + config.resynthesis.correction.notes = + NoteMask::from_key_scale(PitchClass::C, CorrectionScale::Major); + config.resynthesis.correction.retune_ms = 20.0; + config.resynthesis.mode = MultiVoiceMode::Harmony; + config.resynthesis.stereo_output = true; + config.resynthesis.harmony_gain = 0.4; + config.resynthesis.harmony.source = HarmonySource::SmartInterval; + config.resynthesis.harmony.key = PitchClass::C; + config.resynthesis.harmony.scale = HarmonyScale::Major; + config.resynthesis.harmony.diatonic_intervals = [2, 4, -2, 0]; + config.resynthesis.harmony.portamento_ms = 25.0; + config.resynthesis.harmony.voices = 2; + config.reverb.enabled = true; + config.reverb.mode = ReverbMode::MediumHall; + config.reverb.mix = 0.18; + config.reverb.decay = 0.5; + config.reverb.brightness_hz = 5500.0; + config.output_gain = 0.75; + } + Preset::WarmBroadcast => { + config.punch.enabled = true; + config.punch.gain_db = 3.0; + config.punch.impact = 0.4; + config.punch.ceiling_db = -1.5; + config.punch.attack_ms = 12.0; + config.warm.enabled = true; + config.warm.drive_db = 3.5; + config.resynthesis.correction.enabled = false; + config.resynthesis.formant.enabled = true; + config.resynthesis.formant.width = 1.05; + config.resynthesis.formant.stretch = 1.04; + config.resynthesis.dry_mix = 0.25; + config.output_gain = 0.9; + } + } + config + } + /// Checks all stages and the final gain, and does not change state. /// /// The validation uses the signal order: Punch, Warm, resynthesis, Alien, @@ -205,6 +330,36 @@ impl ProcessorConfig { } } +/// Converts a pitch shift in semitones, -24..=24, to a linear pitch ratio in +/// 0.25..=4. +/// +/// Zero semitones give a ratio of 1. Twelve semitones give 2, and -12 +/// semitones give 0.5. Give the result to [`ResynthesisConfig::pitch_ratio`]. +/// +/// # Errors +/// +/// If `semitones` is not finite or is outside -24..=24, this function returns +/// [`Error::InvalidConfig`] with the field `semitones`. +pub fn semitones_to_ratio(semitones: f32) -> Result { + check_range("semitones", semitones, -24.0, 24.0)?; + Ok((f64::from(semitones) / 12.0).exp2() as f32) +} + +/// Converts a linear pitch ratio, 0.25..=4, to a pitch shift in semitones in +/// -24..=24. +/// +/// A ratio of 1 gives 0 semitones. A ratio of 2 gives 12 semitones, and a +/// ratio of 0.5 gives -12 semitones. +/// +/// # Errors +/// +/// If `ratio` is not finite or is outside 0.25..=4, this function returns +/// [`Error::InvalidConfig`] with the field `ratio`. +pub fn ratio_to_semitones(ratio: f32) -> Result { + check_range("ratio", ratio, 0.25, 4.0)?; + Ok((12.0 * f64::from(ratio).log2()) as f32) +} + /// Checks the output gain range. /// /// `ProcessorConfig` and `ControlEvent::OutputGain` use the same range. diff --git a/src/lib.rs b/src/lib.rs index 0e29119..5a4d96e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -10,8 +10,9 @@ //! //! [`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 +//! [`ProcessorConfig`], start from its default value or +//! [`ProcessorConfig::from_preset`] 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. //! @@ -121,7 +122,9 @@ mod scale; #[cfg(all(feature = "wasm", target_arch = "wasm32"))] pub mod wasm; -pub use config::{PrepareConfig, ProcessorConfig, SampleRate}; +pub use config::{ + ratio_to_semitones, semitones_to_ratio, PrepareConfig, Preset, ProcessorConfig, SampleRate, +}; pub use effects::alien::AlienConfig; pub use effects::punch::PunchConfig; pub use effects::reverb::{ReverbConfig, ReverbMode}; diff --git a/src/scale.rs b/src/scale.rs index 01c4f94..4d9692d 100644 --- a/src/scale.rs +++ b/src/scale.rs @@ -72,11 +72,25 @@ impl PitchClass { serde(rename_all = "camelCase") )] pub enum CorrectionScale { - /// The major scale. + /// The major scale: semitone offsets 0, 2, 4, 5, 7, 9, 11. Major, - /// The natural minor scale. + /// The natural minor scale: semitone offsets 0, 2, 3, 5, 7, 8, 10. Minor, - /// The chromatic scale with all notes. + /// The harmonic minor scale: semitone offsets 0, 2, 3, 5, 7, 8, 11. + HarmonicMinor, + /// The melodic minor scale: semitone offsets 0, 2, 3, 5, 7, 9, 11. + MelodicMinor, + /// The Dorian mode: semitone offsets 0, 2, 3, 5, 7, 9, 10. + Dorian, + /// The Mixolydian mode: semitone offsets 0, 2, 4, 5, 7, 9, 10. + Mixolydian, + /// The major pentatonic scale: semitone offsets 0, 2, 4, 7, 9. + MajorPentatonic, + /// The minor pentatonic scale: semitone offsets 0, 3, 5, 7, 10. + MinorPentatonic, + /// The hexatonic blues scale: semitone offsets 0, 3, 5, 6, 7, 10. + Blues, + /// The chromatic scale with all twelve notes: semitone offsets 0..=11. #[default] Chromatic, } @@ -119,24 +133,43 @@ 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. + /// Each [`CorrectionScale`] variant lists its semitone offsets above `key`. + /// [`CorrectionScale::Chromatic`] permits all classes for all keys. This + /// function only makes a value. To apply the value, use the correction + /// configuration. pub fn from_key_scale(key: PitchClass, scale: CorrectionScale) -> Self { - if scale == CorrectionScale::Chromatic { - return Self::CHROMATIC; - } - let offset = usize::from(key.semitone()) - + if scale == CorrectionScale::Minor { - 3 - } else { - 0 - }; - let major = [ - true, false, true, false, true, true, false, true, false, true, false, true, - ]; - Self(std::array::from_fn(|i| major[(i + 24 - offset) % 12])) + let tones = match scale { + CorrectionScale::Chromatic => return Self::CHROMATIC, + CorrectionScale::Major => [ + true, false, true, false, true, true, false, true, false, true, false, true, + ], + CorrectionScale::Minor => [ + true, false, true, true, false, true, false, true, true, false, true, false, + ], + CorrectionScale::HarmonicMinor => [ + true, false, true, true, false, true, false, true, true, false, false, true, + ], + CorrectionScale::MelodicMinor => [ + true, false, true, true, false, true, false, true, false, true, false, true, + ], + CorrectionScale::Dorian => [ + true, false, true, true, false, true, false, true, false, true, true, false, + ], + CorrectionScale::Mixolydian => [ + true, false, true, false, true, true, false, true, false, true, true, false, + ], + CorrectionScale::MajorPentatonic => [ + true, false, true, false, true, false, false, true, false, true, false, false, + ], + CorrectionScale::MinorPentatonic => [ + true, false, false, true, false, true, false, true, false, false, true, false, + ], + CorrectionScale::Blues => [ + true, false, false, true, false, true, true, true, false, false, true, false, + ], + }; + let offset = usize::from(key.semitone()); + Self(std::array::from_fn(|i| tones[(i + 12 - offset) % 12])) } } diff --git a/src/wasm.rs b/src/wasm.rs index c9cec08..4d74e15 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -21,11 +21,11 @@ //! - Each object must contain all required fields. //! - The optional harmony `voices` field defaults to 4. //! -//! [`default_config`] gives a configuration to start from. Control events use -//! `{ type, value }`, and the reset control has no `value`. MIDI messages use -//! `{ type, channel, note, velocity }`, with the fields that apply to the -//! selected variant. The TypeScript declarations come from the same Rust types -//! that validation uses. +//! [`default_config`] and [`preset_config`] give configurations to start from. +//! Control events use `{ type, value }`, and the reset control has no +//! `value`. MIDI messages use `{ type, channel, note, velocity }`, with the +//! fields that apply to the selected variant. The TypeScript declarations come +//! from the same Rust types that validation uses. //! //! The class allocates the PCM storage at construction and uses it again for //! each block. These operations can allocate: @@ -42,7 +42,8 @@ //! `free()` method. use crate::{ - Error, Feedback, PrepareConfig, Processor, ProcessorConfig, SampleRate, Telemetry, TimedEvent, + CorrectionScale, Error, Feedback, NoteMask, PitchClass, PrepareConfig, Preset, Processor, + ProcessorConfig, SampleRate, Telemetry, TimedEvent, }; use js_sys::{Float32Array, Int16Array}; use serde::{Deserialize, Serialize}; @@ -76,6 +77,63 @@ pub fn default_config() -> Result, JsError> { Ok(ProcessorConfig::default().into_ts()?) } +/// Returns a complete, independent preset configuration for JavaScript. +/// +/// Change its fields and give it to `Tunelet` or to `setConfig`. +/// [`Preset::LushChoir`] sets `outputGain` to 0.35 so that the eight choir +/// voices do not overload the output. +/// +/// # Errors +/// +/// If `preset` is not a valid preset name or the conversion fails, this +/// function returns a JavaScript `Error`. +#[wasm_bindgen(js_name = presetConfig)] +pub fn preset_config(preset: Ts) -> Result, JsError> { + Ok(ProcessorConfig::from_preset(preset.to_rust()?).into_ts()?) +} + +/// Returns the twelve-note correction mask of `scale` with `key` as the tonic. +/// +/// Give the result to `config.resynthesis.correction.notes`. +/// +/// # Errors +/// +/// If `key` or `scale` is not valid or the conversion fails, this function +/// returns a JavaScript `Error`. +#[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()?) +} + +/// Converts a pitch shift in semitones, -24..=24, to a linear pitch ratio in +/// 0.25..=4. +/// +/// Give the result to `config.resynthesis.pitchRatio`. +/// +/// # Errors +/// +/// If `semitones` is not finite or is outside -24..=24, this function returns +/// a JavaScript `Error`. +#[wasm_bindgen(js_name = semitonesToRatio)] +pub fn semitones_to_ratio(semitones: f32) -> Result { + Ok(crate::semitones_to_ratio(semitones)?) +} + +/// Converts a linear pitch ratio, 0.25..=4, to a pitch shift in semitones in +/// -24..=24. +/// +/// # Errors +/// +/// If `ratio` is not finite or is outside 0.25..=4, this function returns a +/// JavaScript `Error`. +#[wasm_bindgen(js_name = ratioToSemitones)] +pub fn ratio_to_semitones(ratio: f32) -> Result { + Ok(crate::ratio_to_semitones(ratio)?) +} + /// 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 From 2c0836c337f3d30bdefad78507db82929a3e93d7 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 09:16:59 +0000 Subject: [PATCH 2/3] feat!: mark CorrectionScale and Preset as non-exhaustive - Add #[non_exhaustive] to CorrectionScale in src/scale.rs. - Add #[non_exhaustive] to Preset in src/config.rs. --- src/config.rs | 1 + src/scale.rs | 1 + 2 files changed, 2 insertions(+) diff --git a/src/config.rs b/src/config.rs index 721efa0..6825a70 100644 --- a/src/config.rs +++ b/src/config.rs @@ -192,6 +192,7 @@ impl Default for ProcessorConfig { /// configuration to [`crate::Processor::new`] or /// [`crate::Processor::set_config`]. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), derive(serde::Serialize, serde::Deserialize, tsify::Tsify), diff --git a/src/scale.rs b/src/scale.rs index d2cc995..0857066 100644 --- a/src/scale.rs +++ b/src/scale.rs @@ -66,6 +66,7 @@ impl PitchClass { /// A scale for [`NoteMask::from_key_scale`]. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), derive(serde::Serialize, serde::Deserialize, tsify::Tsify), From 7f461962f8953e17ea00edbe0f0b92b6ae266cc7 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 07:30:00 +0000 Subject: [PATCH 3/3] test(npm): check preset, scale and semitone helpers in verify-pack - Check preset, scale and semitone helpers at runtime. - Check TypeScript types for presets, scales and semitone helpers. - Check @throws JSDoc tags on the four helper exports. --- scripts/verify-pack.mjs | 127 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 124 insertions(+), 3 deletions(-) diff --git a/scripts/verify-pack.mjs b/scripts/verify-pack.mjs index 66d5b7a..e7c414a 100644 --- a/scripts/verify-pack.mjs +++ b/scripts/verify-pack.mjs @@ -305,8 +305,16 @@ function verifyRuntimeImport(consumerDir, packageName) { 'assert.equal(typeof rootModule.Tunelet, "function");', 'assert.equal(typeof rootModule.TuneletAudioViews, "function");', 'assert.equal(typeof rootModule.defaultConfig, "function");', + 'assert.equal(typeof rootModule.presetConfig, "function");', + 'assert.equal(typeof rootModule.noteMaskFromKeyScale, "function");', + 'assert.equal(typeof rootModule.semitonesToRatio, "function");', + 'assert.equal(typeof rootModule.ratioToSemitones, "function");', 'assert.equal(typeof wasmModule.default, "function");', 'assert.equal(typeof wasmModule.initSync, "function");', + 'assert.equal(typeof wasmModule.presetConfig, "function");', + 'assert.equal(typeof wasmModule.noteMaskFromKeyScale, "function");', + 'assert.equal(typeof wasmModule.semitonesToRatio, "function");', + 'assert.equal(typeof wasmModule.ratioToSemitones, "function");', "", "const wasmExports = await rootModule.loadTunelet();", "assert.ok(wasmExports);", @@ -385,6 +393,85 @@ function verifyRuntimeImport(consumerDir, packageName) { " processor.free();", "}", "", + "for (const presetName of [", + ' "naturalTune",', + ' "hardPopTune",', + ' "lushChoir",', + ' "diatonicHarmony",', + ' "warmBroadcast",', + "]) {", + " const presetCfg = rootModule.presetConfig(presetName);", + " const presetProc = new rootModule.Tunelet(48000, 128, presetCfg);", + " try {", + " assert.equal(presetProc.sampleRate, 48000);", + " } finally {", + " presetProc.free();", + " }", + "}", + 'const lushConfig = rootModule.presetConfig("lushChoir");', + "assert.equal(lushConfig.resynthesis.choirVoices, 8);", + "assert.equal(lushConfig.outputGain, Math.fround(0.35));", + 'const harmonyPreset = rootModule.presetConfig("diatonicHarmony");', + 'assert.equal(harmonyPreset.resynthesis.mode, "harmony");', + "assert.equal(harmonyPreset.resynthesis.harmony.voices, 2);", + 'assert.throws(() => rootModule.presetConfig("invalidPreset"));', + "", + 'assert.deepEqual(rootModule.noteMaskFromKeyScale("fSharp", "chromatic"), Array(12).fill(true));', + "assert.deepEqual(", + ' rootModule.noteMaskFromKeyScale("a", "minor"),', + " [true, false, true, false, true, true, false, true, false, true, false, true],", + ");", + "assert.deepEqual(", + ' rootModule.noteMaskFromKeyScale("c", "harmonicMinor"),', + " [true, false, true, true, false, true, false, true, true, false, false, true],", + ");", + "assert.deepEqual(", + ' rootModule.noteMaskFromKeyScale("d", "dorian"),', + " [true, false, true, false, true, true, false, true, false, true, false, true],", + ");", + "assert.deepEqual(", + ' rootModule.noteMaskFromKeyScale("c", "blues"),', + " [true, false, false, true, false, true, true, true, false, false, true, false],", + ");", + 'assert.throws(() => rootModule.noteMaskFromKeyScale("c", "unknownScale"));', + 'assert.throws(() => rootModule.noteMaskFromKeyScale("h", "major"));', + "", + "assert.equal(rootModule.semitonesToRatio(-24), 0.25);", + "assert.equal(rootModule.semitonesToRatio(-12), 0.5);", + "assert.equal(rootModule.semitonesToRatio(0), 1);", + "assert.equal(rootModule.semitonesToRatio(12), 2);", + "assert.equal(rootModule.semitonesToRatio(24), 4);", + "const majorThirdRatio = rootModule.semitonesToRatio(4);", + "assert.ok(Math.abs(majorThirdRatio - Math.pow(2, 4 / 12)) < 1e-6);", + "assert.equal(rootModule.ratioToSemitones(0.25), -24);", + "assert.equal(rootModule.ratioToSemitones(0.5), -12);", + "assert.equal(rootModule.ratioToSemitones(1), 0);", + "assert.equal(rootModule.ratioToSemitones(2), 12);", + "assert.equal(rootModule.ratioToSemitones(4), 24);", + "assert.ok(Math.abs(rootModule.ratioToSemitones(majorThirdRatio) - 4) < 1e-5);", + "assert.throws(() => rootModule.semitonesToRatio(-24.01));", + "assert.throws(() => rootModule.semitonesToRatio(24.01));", + "assert.throws(() => rootModule.semitonesToRatio(Number.NaN));", + "assert.throws(() => rootModule.semitonesToRatio(Number.POSITIVE_INFINITY));", + "assert.throws(() => rootModule.ratioToSemitones(0.24));", + "assert.throws(() => rootModule.ratioToSemitones(4.01));", + "assert.throws(() => rootModule.ratioToSemitones(Number.NaN));", + "assert.throws(() => rootModule.ratioToSemitones(Number.POSITIVE_INFINITY));", + "", + 'const helperConfig = rootModule.presetConfig("naturalTune");', + 'helperConfig.resynthesis.correction.notes = rootModule.noteMaskFromKeyScale("a", "harmonicMinor");', + "helperConfig.resynthesis.pitchRatio = majorThirdRatio;", + "const helperProcessor = new rootModule.Tunelet(48000, 128, helperConfig);", + "try {", + " assert.deepEqual(", + " helperProcessor.config().resynthesis.correction.notes,", + ' rootModule.noteMaskFromKeyScale("a", "harmonicMinor"),', + " );", + " assert.equal(helperProcessor.config().resynthesis.pitchRatio, majorThirdRatio);", + "} finally {", + " helperProcessor.free();", + "}", + "", "const config = rootModule.defaultConfig();", "config.resynthesis.formant.enabled = true;", "config.reverb.enabled = true;", @@ -734,11 +821,19 @@ function verifyTypeDeclarations(consumerDir, packageName) { " defaultConfig,", " initSync as rootInitSync,", " loadTunelet as namedLoadTunelet,", + " noteMaskFromKeyScale,", + " presetConfig,", + " ratioToSemitones,", + " semitonesToRatio,", " Tunelet,", " TuneletAudioViews,", " type ControlActivity,", " type ControlEvent,", + " type CorrectionScale,", + " type NoteMask,", " type ParameterControl,", + " type PitchClass,", + " type Preset,", " type ProcessorConfig,", " type ResynthesisConfig,", " type SyncInitInput as RootSyncInitInput,", @@ -746,6 +841,10 @@ function verifyTypeDeclarations(consumerDir, packageName) { `} from ${pkgLiteral};`, "import init, {", " initSync as wasmInitSync,", + " noteMaskFromKeyScale as wasmNoteMaskFromKeyScale,", + " presetConfig as wasmPresetConfig,", + " ratioToSemitones as wasmRatioToSemitones,", + " semitonesToRatio as wasmSemitonesToRatio,", " type InitInput,", " type InitOutput,", " type ParameterControl as WasmParameterControl,", @@ -770,12 +869,26 @@ function verifyTypeDeclarations(consumerDir, packageName) { " module: syncSource,", " });", " const baseConfig: ProcessorConfig = defaultConfig();", + ' const selectedPreset: Preset = "lushChoir";', + ' const selectedKey: PitchClass = "a";', + ' const selectedScale: CorrectionScale = "harmonicMinor";', + " const selectedMask: NoteMask = noteMaskFromKeyScale(selectedKey, selectedScale);", + " const wasmMask: NoteMask = wasmNoteMaskFromKeyScale(selectedKey, selectedScale);", + " const presetConfiguration: ProcessorConfig = presetConfig(selectedPreset);", + " const wasmPresetConfiguration: ProcessorConfig = wasmPresetConfig(selectedPreset);", + " const shiftedRatio: number = semitonesToRatio(4);", + " const wasmShiftedRatio: number = wasmSemitonesToRatio(4);", + " const shiftedSemitones: number = ratioToSemitones(shiftedRatio);", + " const wasmShiftedSemitones: number = wasmRatioToSemitones(wasmShiftedRatio);", " const configWithUndefined: ProcessorConfig = {", - " ...baseConfig,", + " ...presetConfiguration,", + " outputGain: baseConfig.outputGain,", " resynthesis: {", " ...baseConfig.resynthesis,", + " pitchRatio: shiftedRatio,", " correction: {", " ...baseConfig.resynthesis.correction,", + " notes: selectedMask,", " humanize: optionalVoices,", " flexTune: optionalVoices,", " },", @@ -878,6 +991,10 @@ function verifyTypeDeclarations(consumerDir, packageName) { " void exportsFromWasm;", " void syncExportsFromRoot;", " void syncExportsFromWasm;", + " void wasmMask;", + " void wasmPresetConfiguration;", + " void shiftedSemitones;", + " void wasmShiftedSemitones;", " return exportsFromRoot;", "}", ]; @@ -1176,8 +1293,8 @@ function verifyNormalizedJsDoc(consumerDir, packageName) { const throwsCount = [...dts.matchAll(/\* @throws /g)].length; assert.ok( - throwsCount >= 14, - `Expected at least 14 @throws tags, found ${throwsCount}`, + throwsCount >= 18, + `Expected at least 18 @throws tags, found ${throwsCount}`, ); const fallibleSignatures = [ @@ -1195,6 +1312,10 @@ function verifyNormalizedJsDoc(consumerDir, packageName) { ["takeTelemetry", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+takeTelemetry\(\): Telemetry;/], ["telemetry", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+telemetry\(\): Telemetry;/], ["defaultConfig", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+export function defaultConfig\(\): ProcessorConfig;/], + ["noteMaskFromKeyScale", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+export function noteMaskFromKeyScale\(key: PitchClass, scale: CorrectionScale\): NoteMask;/], + ["presetConfig", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+export function presetConfig\(preset: Preset\): ProcessorConfig;/], + ["ratioToSemitones", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+export function ratioToSemitones\(ratio: number\): number;/], + ["semitonesToRatio", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+export function semitonesToRatio\(semitones: number\): number;/], ]; for (const [label, pattern] of fallibleSignatures) { const doc = extractMemberJsDoc(dts, pattern, label);