diff --git a/README.md b/README.md index 83a8f47..8d18308 100644 --- a/README.md +++ b/README.md @@ -389,15 +389,17 @@ For a custom asset location, give one of these sources to - A promise for one of these. For a Node.js `file:` source, use a URL object. A string source obeys fetch -rules. The first concurrent call selects the source. Later arguments do not -replace an initialized module. A custom binary must match the generated -bindings. - -The package root also exports `loadTunelet` as its default export. For direct -control of Wasm initialization, `tunelet/wasm` gives the generated default -initializer and `initSync`. The package root re-exports `initSync` too. Use -only one initialization entry point for each module instance. The package -gives only ESM exports. CommonJS applications can use `await import("tunelet")`. +rules. Repeated calls with the same source share one initialization result. A +call with a different source, or with a binary that does not match the +generated bindings, rejects with a `TuneletError`. + +The package root also exports `loadTunelet` as its default export. It exports +`TuneletError` with a `camelCase` message and a typed `details` payload for all +validation and lifecycle errors. For direct control of Wasm initialization, +`tunelet/wasm` gives the generated default initializer and `initSync`. The +package root exports `initSync` too. Use only one initialization entry point +for each module instance. The package gives only ESM exports. CommonJS +applications can use `await import("tunelet")`. ### Deployment @@ -425,7 +427,7 @@ page that opens the JavaScript. | Formant envelopes | `formantEnvelope(maxFrequencyHz, input, output)` | | Finite tail | `beginDrain()`, `drain(left, right)`, `drainMono(audio)` | | Configured tail budget | `tailFrames()` | -| Reset or release memory | `reset()`, `free()` | +| Reset or release memory | `reset()`, `free()`, `[Symbol.dispose]()` | ### Audio buffers @@ -451,9 +453,9 @@ and show enums as string literals. To change the configuration, do these steps: 3. Call `setConfig()`. If a required field is absent or a value is not valid, the call throws a -JavaScript `Error`. The optional `resynthesis.harmony.voices` field defaults -to 4 if it is absent. The conversion ignores extra object properties. The -generated declarations contain the parameter documentation from the Rust +`TuneletError` with `details`. 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. `resynthesis.randomSeed` and the `processedFrames` field of feedback and diff --git a/src/config.rs b/src/config.rs index 75bcd82..06d47d7 100644 --- a/src/config.rs +++ b/src/config.rs @@ -5,8 +5,7 @@ use crate::effects::punch::PunchConfig; use crate::effects::reverb::ReverbConfig; use crate::effects::warm::WarmConfig; use crate::error::{check_range, ConfigProblem}; -use crate::Error; -use crate::ResynthesisConfig; +use crate::{ConfigField, Error, ResynthesisConfig}; use std::num::NonZeroUsize; /// The sample rate of the input and the output. @@ -98,17 +97,18 @@ impl PrepareConfig { /// /// # Errors /// - /// Returns [`Error::InvalidConfig`] with the field - /// `prepare.max_block_frames` if the maximum is zero. The field type is - /// [`NonZeroUsize`]. Thus, this invariant also holds if you edit the field - /// after construction. + /// Returns [`Error::InvalidConfig`] with [`ConfigField::PrepareMaxBlockFrames`] + /// and [`ConfigProblem::IntegerOutOfRange`] if `max_block_frames` is zero. + /// The field type is [`NonZeroUsize`]. Thus, this invariant also holds if + /// you edit the field after construction. pub fn new(sample_rate: SampleRate, max_block_frames: usize) -> Result { let max_block_frames = NonZeroUsize::new(max_block_frames).ok_or_else(|| { Error::config( - "prepare.max_block_frames", - ConfigProblem::OutOfRange { - min: 1.0, - max: usize::MAX as f64, + ConfigField::PrepareMaxBlockFrames, + ConfigProblem::IntegerOutOfRange { + value: 0, + min: 1, + max: usize::MAX as i128, }, ) })?; @@ -126,9 +126,16 @@ impl PrepareConfig { /// configuration does active pitch processing. It is not a bypass with zero /// latency. /// -/// Change a copy, then apply it with [`crate::Processor::set_config`] or -/// [`crate::ControlEvent::Configure`]. The validation examines all fields -/// before a change has an effect. This includes the fields of disabled stages. +#[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " Change a copy, then apply it with [`crate::Processor::set_config`] or [`crate::ControlEvent::Configure`]." +)] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " Change a copy, then apply it with `Tunelet.setConfig` or a `configure` event." +)] +/// The validation examines all fields before a change has an effect. This +/// includes the fields of disabled stages. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] #[cfg_attr( @@ -148,8 +155,16 @@ pub struct ProcessorConfig { pub warm: WarmConfig, /// The stage for pitch tracking, correction, voice resynthesis and /// formant control. - /// - /// The default is [`ResynthesisConfig::default`]. + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = "", + doc = " The default is [`ResynthesisConfig::default`]." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = "", + doc = " The default is chromatic correction with one choir voice." + )] pub resynthesis: ResynthesisConfig, /// The reverse-loop effect after resynthesis. /// @@ -209,5 +224,5 @@ impl ProcessorConfig { /// /// `ProcessorConfig` and `ControlEvent::OutputGain` use the same range. pub(crate) fn validate_output_gain(gain: f32) -> Result<(), Error> { - check_range("output_gain", gain, 0.0, 64.0) + check_range(ConfigField::OutputGain, gain, 0.0, 64.0) } diff --git a/src/effects/alien.rs b/src/effects/alien.rs index 5e1f509..7b2a90a 100644 --- a/src/effects/alien.rs +++ b/src/effects/alien.rs @@ -2,7 +2,7 @@ use crate::error::check_count; use crate::numeric::fixed::{Fixed, Q14}; -use crate::Error; +use crate::{ConfigField, Error}; /// The number of history frames that the loop reads from. const HISTORY_FRAMES: usize = 192_000; @@ -50,10 +50,15 @@ impl AlienConfig { /// /// # Errors /// - /// Returns the first [`Error::InvalidConfig`] with its dotted field path - /// and the problem. + /// Returns the first [`Error::InvalidConfig`] with its [`ConfigField`] and + /// the problem. pub fn validate(self) -> Result<(), Error> { - check_count("alien.loop_frames", i64::from(self.loop_frames), 1, 96_000) + check_count( + ConfigField::AlienLoopFrames, + i128::from(self.loop_frames), + 1, + 96_000, + ) } } diff --git a/src/effects/punch.rs b/src/effects/punch.rs index 867dc09..52d266b 100644 --- a/src/effects/punch.rs +++ b/src/effects/punch.rs @@ -4,7 +4,7 @@ use crate::error::check_range; use crate::numeric::fixed::{Q14, Q8}; use crate::numeric::{coefficient_to_exp_value, db_to_gain, envelope_decay, NumericContext}; -use crate::{Error, SampleRate}; +use crate::{ConfigField, Error, SampleRate}; /// The update interval of the peak follower, in frames. const WINDOW_FRAMES: usize = 100; @@ -41,8 +41,15 @@ pub struct PunchConfig { /// The transient emphasis without a unit, 0..=1. /// /// The default is 0.5. It sets the release half-life of the adaptive - /// follower: 5000 ms at 0, 250 ms at 0.5 and 1 ms at 1. The attack uses - /// `attack_ms`. + /// follower: 5000 ms at 0, 250 ms at 0.5 and 1 ms at 1. + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The attack uses `attack_ms`." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The attack uses `attackMs`." + )] pub impact: f32, /// The output ceiling of the saturation in dBFS, -96..=0. /// @@ -75,13 +82,13 @@ impl PunchConfig { /// /// # Errors /// - /// Returns the first [`Error::InvalidConfig`] with its dotted field path - /// and the problem. + /// Returns the first [`Error::InvalidConfig`] with its [`ConfigField`] and + /// the problem. pub fn validate(self) -> Result<(), Error> { - check_range("punch.gain_db", self.gain_db, -96.0, 12.0)?; - check_range("punch.impact", self.impact, 0.0, 1.0)?; - check_range("punch.ceiling_db", self.ceiling_db, -96.0, 0.0)?; - check_range("punch.attack_ms", self.attack_ms, 0.01, 5000.0) + check_range(ConfigField::PunchGainDb, self.gain_db, -96.0, 12.0)?; + check_range(ConfigField::PunchImpact, self.impact, 0.0, 1.0)?; + check_range(ConfigField::PunchCeilingDb, self.ceiling_db, -96.0, 0.0)?; + check_range(ConfigField::PunchAttackMs, self.attack_ms, 0.01, 5000.0) } } diff --git a/src/effects/reverb.rs b/src/effects/reverb.rs index 05155ea..ba1a7a7 100644 --- a/src/effects/reverb.rs +++ b/src/effects/reverb.rs @@ -3,9 +3,16 @@ use crate::error::check_range; use crate::filter::{Biquad, Design}; use crate::numeric::fixed::{Fixed, Q14}; -use crate::{Error, SampleRate}; +use crate::{ConfigField, Error, SampleRate}; -/// The echo or reverberation network. The default is [`Self::Echo`]. +#[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The echo or reverberation network. The default is [`Self::Echo`]." +)] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The echo or reverberation network. The default is `\"echo\"`." +)] /// /// All modes share one delay buffer. A mode change uses the same buffer /// contents and damping filter memories. Thus a transition can play audio @@ -53,8 +60,14 @@ pub struct ReverbConfig { /// Enables the selected network. The default is `false`. In bypass, the /// histories do not change. pub enabled: bool, - /// The topology of the delay network. The default is - /// [`ReverbMode::Echo`]. + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The topology of the delay network. The default is [`ReverbMode::Echo`]." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The topology of the delay network. The default is `\"echo\"`." + )] pub mode: ReverbMode, /// The wet fraction, 0..=1. /// @@ -105,13 +118,18 @@ impl ReverbConfig { /// /// # Errors /// - /// Returns the first [`Error::InvalidConfig`] with its dotted field path - /// and the problem. + /// Returns the first [`Error::InvalidConfig`] with its [`ConfigField`] and + /// the problem. pub fn validate(self) -> Result<(), Error> { - check_range("reverb.mix", self.mix, 0.0, 1.0)?; - check_range("reverb.diffusion", self.diffusion, 0.0, 1.0)?; - check_range("reverb.decay", self.decay, 0.0, 1.0)?; - check_range("reverb.brightness_hz", self.brightness_hz, 80.0, 20000.0) + check_range(ConfigField::ReverbMix, self.mix, 0.0, 1.0)?; + check_range(ConfigField::ReverbDiffusion, self.diffusion, 0.0, 1.0)?; + check_range(ConfigField::ReverbDecay, self.decay, 0.0, 1.0)?; + check_range( + ConfigField::ReverbBrightnessHz, + self.brightness_hz, + 80.0, + 20000.0, + ) } } diff --git a/src/effects/warm.rs b/src/effects/warm.rs index 9721ced..e08f72a 100644 --- a/src/effects/warm.rs +++ b/src/effects/warm.rs @@ -4,7 +4,7 @@ use crate::error::check_range; use crate::filter::{Biquad, Design}; use crate::numeric::db_to_gain; use crate::numeric::fixed::{Fixed, Q12, Q14, Q8}; -use crate::{Error, SampleRate}; +use crate::{ConfigField, Error, SampleRate}; /// The update interval of the peak follower, in frames. const WINDOW_FRAMES: usize = 100; @@ -48,10 +48,10 @@ impl WarmConfig { /// /// # Errors /// - /// Returns the first [`Error::InvalidConfig`] with its dotted field path - /// and the problem. + /// Returns the first [`Error::InvalidConfig`] with its [`ConfigField`] and + /// the problem. pub fn validate(self) -> Result<(), Error> { - check_range("warm.drive_db", self.drive_db, 0.0, 6.0) + check_range(ConfigField::WarmDriveDb, self.drive_db, 0.0, 6.0) } } diff --git a/src/error.rs b/src/error.rs index b971968..ea46ae3 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,4 +1,4 @@ -//! Structured errors for configuration, buffer shapes and timed controls. +//! Structured errors for configuration, buffer shapes, MIDI and timed controls. use std::fmt; @@ -22,19 +22,21 @@ pub enum Error { max_hz: f32, }, /// A configuration field is not valid. - /// - /// `field` is the dotted path of the field from the root configuration, - /// for example `"resynthesis.choir_detune"`, `"reverb.mix"` or - /// `"prepare.max_block_frames"`. InvalidConfig { - /// The dotted path of the field from the root configuration. - field: &'static str, + /// The configuration field that is not valid. + field: ConfigField, + /// The zero-based voice index in `0..=3` for a harmony interval array. + /// + /// For scalar controls, this value is `None`. + voice: Option, /// The problem with the field. problem: ConfigProblem, }, /// A buffer length is not equal to the input length or to the length of /// the other output channel. BufferLength { + /// The output buffer whose length is not valid. + buffer: BufferName, /// The necessary slice length. For `[[i16; 2]]`, this is the number of /// stereo frames. For planar or mono audio, it is the number of samples /// for each channel. @@ -51,38 +53,597 @@ pub enum Error { }, /// The timed event at `index` is not valid. InvalidEvent { - /// The index of the event in the slice. + /// The zero-based index of the event in the slice. index: usize, + /// The zero-based frame offset of the event. + offset: usize, /// The problem with the event. problem: EventProblem, }, /// The MIDI bytes or the MIDI fields are not valid. - /// - /// The causes are: - /// - /// - a status byte below 0x80 - /// - a data byte above 127 - /// - a typed event with a channel, note or velocity out of range. - InvalidMidi, + InvalidMidi { + /// The specific MIDI byte or field problem. + problem: MidiProblem, + }, +} + +/// The output buffer whose length is not equal to the expected length. +#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] +#[non_exhaustive] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + derive(serde::Serialize, serde::Deserialize, tsify::Tsify), + serde(rename_all = "camelCase") +)] +pub enum BufferName { + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The stereo frame buffer of [`crate::Processor::process`] or the synthesis buffer of [`crate::Processor::formant_envelope`]." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The synthesis buffer of `Tunelet.formantEnvelope`." + )] + Output, + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The left channel buffer of [`crate::Processor::process_planar`]." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The left channel buffer of `Tunelet.process`." + )] + Left, + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The right channel buffer of [`crate::Processor::process_planar`] or [`crate::Processor::drain_planar`]." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The right channel buffer of `Tunelet.process` or `Tunelet.drain`." + )] + Right, +} + +impl BufferName { + /// Returns the lowercase name of the buffer. + pub const fn as_str(self) -> &'static str { + match self { + Self::Output => "output", + Self::Left => "left", + Self::Right => "right", + } + } +} + +impl fmt::Display for BufferName { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.as_str()) + } +} + +/// A configuration field that validation examines. +#[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = "", + doc = " [`Self::as_str`] returns the `snake_case` Rust path. [`Self::camel_case`] returns the `camelCase` JavaScript path." +)] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = "", + doc = " Each string value is the dotted `camelCase` path of a field on `ProcessorConfig` or the constructor." +)] +#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] +#[non_exhaustive] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + derive(serde::Serialize, serde::Deserialize, tsify::Tsify) +)] +pub enum ConfigField { + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The block limit [`crate::PrepareConfig::max_block_frames`], `1..=usize::MAX`." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The block limit `maxBlockFrames`, `1..=4294967295`.", + serde(rename = "prepare.maxBlockFrames") + )] + PrepareMaxBlockFrames, + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The Punch input gain [`crate::PunchConfig::gain_db`], `-96..=12`." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The Punch input gain `punch.gainDb`, `-96..=12`.", + serde(rename = "punch.gainDb") + )] + PunchGainDb, + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The Punch transient emphasis [`crate::PunchConfig::impact`], `0..=1`." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The Punch transient emphasis `punch.impact`, `0..=1`.", + serde(rename = "punch.impact") + )] + PunchImpact, + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The Punch output ceiling [`crate::PunchConfig::ceiling_db`], `-96..=0`." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The Punch output ceiling `punch.ceilingDb`, `-96..=0`.", + serde(rename = "punch.ceilingDb") + )] + PunchCeilingDb, + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The Punch attack half-life [`crate::PunchConfig::attack_ms`], `0.01..=5000`." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The Punch attack half-life `punch.attackMs`, `0.01..=5000`.", + serde(rename = "punch.attackMs") + )] + PunchAttackMs, + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The Warm drive [`crate::WarmConfig::drive_db`], `0..=6`." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The Warm drive `warm.driveDb`, `0..=6`.", + serde(rename = "warm.driveDb") + )] + WarmDriveDb, + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The pitch acquisition threshold [`crate::PitchConfig::threshold`], `0.002..=0.2`." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The pitch acquisition threshold `resynthesis.pitch.threshold`, `0.002..=0.2`.", + serde(rename = "resynthesis.pitch.threshold") + )] + ResynthesisPitchThreshold, + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The lower pitch feedback bound [`crate::PitchConfig::min_frequency_hz`], `40..=2000`." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The lower pitch feedback bound `resynthesis.pitch.minFrequencyHz`, `40..=2000`.", + serde(rename = "resynthesis.pitch.minFrequencyHz") + )] + ResynthesisPitchMinFrequencyHz, + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The upper pitch feedback bound [`crate::PitchConfig::max_frequency_hz`], `40..=2000`." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The upper pitch feedback bound `resynthesis.pitch.maxFrequencyHz`, `40..=2000`.", + serde(rename = "resynthesis.pitch.maxFrequencyHz") + )] + ResynthesisPitchMaxFrequencyHz, + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The correction retune half-life [`crate::CorrectionConfig::retune_ms`], `0..=400`." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The correction retune half-life `resynthesis.correction.retuneMs`, `0..=400`.", + serde(rename = "resynthesis.correction.retuneMs") + )] + ResynthesisCorrectionRetuneMs, + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The vocal-tract width factor [`crate::FormantConfig::width`], `0.5..=2`." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The vocal-tract width factor `resynthesis.formant.width`, `0.5..=2`.", + serde(rename = "resynthesis.formant.width") + )] + ResynthesisFormantWidth, + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The vocal-tract length factor [`crate::FormantConfig::stretch`], `0.5..=2`." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The vocal-tract length factor `resynthesis.formant.stretch`, `0.5..=2`.", + serde(rename = "resynthesis.formant.stretch") + )] + ResynthesisFormantStretch, + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The aspiration level [`crate::FormantConfig::aspiration_mix`], `0..=1`." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The aspiration level `resynthesis.formant.aspirationMix`, `0..=1`.", + serde(rename = "resynthesis.formant.aspirationMix") + )] + ResynthesisFormantAspirationMix, + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The aspiration high-pass cutoff [`crate::FormantConfig::aspiration_cutoff_hz`], `500..=10000`." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The aspiration high-pass cutoff `resynthesis.formant.aspirationCutoffHz`, `500..=10000`.", + serde(rename = "resynthesis.formant.aspirationCutoffHz") + )] + ResynthesisFormantAspirationCutoffHz, + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The fixed semitone offsets [`crate::HarmonyConfig::chromatic_intervals`], each in `-24..=24`." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The fixed semitone offsets `resynthesis.harmony.chromaticIntervals`, each in `-24..=24`.", + serde(rename = "resynthesis.harmony.chromaticIntervals") + )] + ResynthesisHarmonyChromaticIntervals, + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The scale-step offsets [`crate::HarmonyConfig::diatonic_intervals`], each in `-14..=14`." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The scale-step offsets `resynthesis.harmony.diatonicIntervals`, each in `-14..=14`.", + serde(rename = "resynthesis.harmony.diatonicIntervals") + )] + ResynthesisHarmonyDiatonicIntervals, + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The interval voice count [`crate::HarmonyConfig::voices`], `0..=4`." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The interval voice count `resynthesis.harmony.voices`, `0..=4`.", + serde(rename = "resynthesis.harmony.voices") + )] + ResynthesisHarmonyVoices, + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The chord register [`crate::HarmonyConfig::register_percent`], `0..=100`." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The chord register `resynthesis.harmony.registerPercent`, `0..=100`.", + serde(rename = "resynthesis.harmony.registerPercent") + )] + ResynthesisHarmonyRegisterPercent, + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The chord voicing spread [`crate::HarmonyConfig::voicing_spread_percent`], `0..=100`." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The chord voicing spread `resynthesis.harmony.voicingSpreadPercent`, `0..=100`.", + serde(rename = "resynthesis.harmony.voicingSpreadPercent") + )] + ResynthesisHarmonyVoicingSpreadPercent, + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The harmony portamento half-life [`crate::HarmonyConfig::portamento_ms`], `0..=10000`." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The harmony portamento half-life `resynthesis.harmony.portamentoMs`, `0..=10000`.", + serde(rename = "resynthesis.harmony.portamentoMs") + )] + ResynthesisHarmonyPortamentoMs, + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The pitch multiplier [`crate::ResynthesisConfig::pitch_ratio`], `0.25..=4`." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The pitch multiplier `resynthesis.pitchRatio`, `0.25..=4`.", + serde(rename = "resynthesis.pitchRatio") + )] + ResynthesisPitchRatio, + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The total choir voice count [`crate::ResynthesisConfig::choir_voices`], `1..=16`." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The total choir voice count `resynthesis.choirVoices`, `1..=16`.", + serde(rename = "resynthesis.choirVoices") + )] + ResynthesisChoirVoices, + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The choir drift control [`crate::ResynthesisConfig::choir_detune`], `10..=100`." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The choir drift control `resynthesis.choirDetune`, `10..=100`.", + serde(rename = "resynthesis.choirDetune") + )] + ResynthesisChoirDetune, + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The choir delay scale [`crate::ResynthesisConfig::choir_delay`], `20..=200`." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The choir delay scale `resynthesis.choirDelay`, `20..=200`.", + serde(rename = "resynthesis.choirDelay") + )] + ResynthesisChoirDelay, + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The choir stereo width [`crate::ResynthesisConfig::choir_spread_percent`], `0..=100`." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The choir stereo width `resynthesis.choirSpreadPercent`, `0..=100`.", + serde(rename = "resynthesis.choirSpreadPercent") + )] + ResynthesisChoirSpreadPercent, + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The harmony pan gain [`crate::ResynthesisConfig::harmony_gain`], `0..=1`." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The harmony pan gain `resynthesis.harmonyGain`, `0..=1`.", + serde(rename = "resynthesis.harmonyGain") + )] + ResynthesisHarmonyGain, + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The harmonic modulation depth [`crate::ResynthesisConfig::harmonic_modulation`], `0..=24`." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The harmonic modulation depth `resynthesis.harmonicModulation`, `0..=24`.", + serde(rename = "resynthesis.harmonicModulation") + )] + ResynthesisHarmonicModulation, + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The resynthesis dry fraction [`crate::ResynthesisConfig::dry_mix`], `0..=1`." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The resynthesis dry fraction `resynthesis.dryMix`, `0..=1`.", + serde(rename = "resynthesis.dryMix") + )] + ResynthesisDryMix, + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The Alien loop length [`crate::AlienConfig::loop_frames`], `1..=96000`." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The Alien loop length `alien.loopFrames`, `1..=96000`.", + serde(rename = "alien.loopFrames") + )] + AlienLoopFrames, + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The reverb wet fraction [`crate::ReverbConfig::mix`], `0..=1`." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The reverb wet fraction `reverb.mix`, `0..=1`.", + serde(rename = "reverb.mix") + )] + ReverbMix, + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The reverb diffusion [`crate::ReverbConfig::diffusion`], `0..=1`." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The reverb diffusion `reverb.diffusion`, `0..=1`.", + serde(rename = "reverb.diffusion") + )] + ReverbDiffusion, + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The reverb feedback decay [`crate::ReverbConfig::decay`], `0..=1`." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The reverb feedback decay `reverb.decay`, `0..=1`.", + serde(rename = "reverb.decay") + )] + ReverbDecay, + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The reverb damping cutoff [`crate::ReverbConfig::brightness_hz`], `80..=20000`." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The reverb damping cutoff `reverb.brightnessHz`, `80..=20000`.", + serde(rename = "reverb.brightnessHz") + )] + ReverbBrightnessHz, + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The final linear gain [`crate::ProcessorConfig::output_gain`], `0..=64`." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The final linear gain `outputGain`, `0..=64`.", + serde(rename = "outputGain") + )] + OutputGain, +} + +impl ConfigField { + /// Returns the dotted `snake_case` Rust path of the field. + pub const fn as_str(self) -> &'static str { + match self { + Self::PrepareMaxBlockFrames => "prepare.max_block_frames", + Self::PunchGainDb => "punch.gain_db", + Self::PunchImpact => "punch.impact", + Self::PunchCeilingDb => "punch.ceiling_db", + Self::PunchAttackMs => "punch.attack_ms", + Self::WarmDriveDb => "warm.drive_db", + Self::ResynthesisPitchThreshold => "resynthesis.pitch.threshold", + Self::ResynthesisPitchMinFrequencyHz => "resynthesis.pitch.min_frequency_hz", + Self::ResynthesisPitchMaxFrequencyHz => "resynthesis.pitch.max_frequency_hz", + Self::ResynthesisCorrectionRetuneMs => "resynthesis.correction.retune_ms", + Self::ResynthesisFormantWidth => "resynthesis.formant.width", + Self::ResynthesisFormantStretch => "resynthesis.formant.stretch", + Self::ResynthesisFormantAspirationMix => "resynthesis.formant.aspiration_mix", + Self::ResynthesisFormantAspirationCutoffHz => { + "resynthesis.formant.aspiration_cutoff_hz" + } + Self::ResynthesisHarmonyChromaticIntervals => "resynthesis.harmony.chromatic_intervals", + Self::ResynthesisHarmonyDiatonicIntervals => "resynthesis.harmony.diatonic_intervals", + Self::ResynthesisHarmonyVoices => "resynthesis.harmony.voices", + Self::ResynthesisHarmonyRegisterPercent => "resynthesis.harmony.register_percent", + Self::ResynthesisHarmonyVoicingSpreadPercent => { + "resynthesis.harmony.voicing_spread_percent" + } + Self::ResynthesisHarmonyPortamentoMs => "resynthesis.harmony.portamento_ms", + Self::ResynthesisPitchRatio => "resynthesis.pitch_ratio", + Self::ResynthesisChoirVoices => "resynthesis.choir_voices", + Self::ResynthesisChoirDetune => "resynthesis.choir_detune", + Self::ResynthesisChoirDelay => "resynthesis.choir_delay", + Self::ResynthesisChoirSpreadPercent => "resynthesis.choir_spread_percent", + Self::ResynthesisHarmonyGain => "resynthesis.harmony_gain", + Self::ResynthesisHarmonicModulation => "resynthesis.harmonic_modulation", + Self::ResynthesisDryMix => "resynthesis.dry_mix", + Self::AlienLoopFrames => "alien.loop_frames", + Self::ReverbMix => "reverb.mix", + Self::ReverbDiffusion => "reverb.diffusion", + Self::ReverbDecay => "reverb.decay", + Self::ReverbBrightnessHz => "reverb.brightness_hz", + Self::OutputGain => "output_gain", + } + } + + /// Returns the dotted `camelCase` JavaScript path of the field. + pub const fn camel_case(self) -> &'static str { + match self { + Self::PrepareMaxBlockFrames => "prepare.maxBlockFrames", + Self::PunchGainDb => "punch.gainDb", + Self::PunchImpact => "punch.impact", + Self::PunchCeilingDb => "punch.ceilingDb", + Self::PunchAttackMs => "punch.attackMs", + Self::WarmDriveDb => "warm.driveDb", + Self::ResynthesisPitchThreshold => "resynthesis.pitch.threshold", + Self::ResynthesisPitchMinFrequencyHz => "resynthesis.pitch.minFrequencyHz", + Self::ResynthesisPitchMaxFrequencyHz => "resynthesis.pitch.maxFrequencyHz", + Self::ResynthesisCorrectionRetuneMs => "resynthesis.correction.retuneMs", + Self::ResynthesisFormantWidth => "resynthesis.formant.width", + Self::ResynthesisFormantStretch => "resynthesis.formant.stretch", + Self::ResynthesisFormantAspirationMix => "resynthesis.formant.aspirationMix", + Self::ResynthesisFormantAspirationCutoffHz => "resynthesis.formant.aspirationCutoffHz", + Self::ResynthesisHarmonyChromaticIntervals => "resynthesis.harmony.chromaticIntervals", + Self::ResynthesisHarmonyDiatonicIntervals => "resynthesis.harmony.diatonicIntervals", + Self::ResynthesisHarmonyVoices => "resynthesis.harmony.voices", + Self::ResynthesisHarmonyRegisterPercent => "resynthesis.harmony.registerPercent", + Self::ResynthesisHarmonyVoicingSpreadPercent => { + "resynthesis.harmony.voicingSpreadPercent" + } + Self::ResynthesisHarmonyPortamentoMs => "resynthesis.harmony.portamentoMs", + Self::ResynthesisPitchRatio => "resynthesis.pitchRatio", + Self::ResynthesisChoirVoices => "resynthesis.choirVoices", + Self::ResynthesisChoirDetune => "resynthesis.choirDetune", + Self::ResynthesisChoirDelay => "resynthesis.choirDelay", + Self::ResynthesisChoirSpreadPercent => "resynthesis.choirSpreadPercent", + Self::ResynthesisHarmonyGain => "resynthesis.harmonyGain", + Self::ResynthesisHarmonicModulation => "resynthesis.harmonicModulation", + Self::ResynthesisDryMix => "resynthesis.dryMix", + Self::AlienLoopFrames => "alien.loopFrames", + Self::ReverbMix => "reverb.mix", + Self::ReverbDiffusion => "reverb.diffusion", + Self::ReverbDecay => "reverb.decay", + Self::ReverbBrightnessHz => "reverb.brightnessHz", + Self::OutputGain => "outputGain", + } + } +} + +impl fmt::Display for ConfigField { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.as_str()) + } } /// The problem with a configuration field. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] pub enum ConfigProblem { - /// The value is outside `min..=max`. + /// The floating-point value is outside `min..=max`. OutOfRange { + /// The rejected floating-point value. + value: f32, /// The lowest valid value. - min: f64, + min: f32, /// The highest valid value. - max: f64, + max: f32, + }, + /// The integer value is outside `min..=max`. + IntegerOutOfRange { + /// The rejected integer value. + value: i128, + /// The lowest valid integer value. + min: i128, + /// The highest valid integer value. + max: i128, + }, + /// The floating-point value is `NaN` or infinite. + NotFinite { + /// The rejected non-finite value. + value: f32, }, - /// The value is NaN or infinite. - NotFinite, - /// The value must be below the value of the field `other`. + /// The value must be strictly less than the value of `other`. Unordered { - /// The dotted path of the field that the value must stay below. - other: &'static str, + /// The rejected value of the field. + value: f32, + /// The field that `value` must stay below. + other: ConfigField, + /// The value of `other`. + other_value: f32, + }, +} + +/// The problem with a three-byte MIDI message or a typed [`crate::MidiEvent`]. +#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] +#[non_exhaustive] +pub enum MidiProblem { + /// The status byte at index `0` is below `0x80`. + StatusByte { + /// The rejected status byte. + byte: u8, + }, + /// A data byte at `index` (`1` or `2`) is more than `127`. + DataByte { + /// The byte index in the three-byte message (`1` or `2`). + index: usize, + /// The rejected data byte. + byte: u8, + }, + /// The zero-based MIDI channel is more than `15`. + Channel { + /// The rejected channel value. + channel: u8, + }, + /// The MIDI note number is more than `127`. + Note { + /// The rejected note value. + note: u8, + }, + /// The MIDI velocity is more than `127`. + Velocity { + /// The rejected velocity value. + velocity: u8, }, } @@ -98,37 +659,77 @@ pub enum EventProblem { /// The zero-based offset is equal to or more than the block frame count. /// /// Each event in an empty block has this problem. - OffsetOutsideBlock, + OffsetOutsideBlock { + /// The rejected zero-based frame offset of the event. + offset: usize, + /// The number of frames in the block. + frames: usize, + }, /// The offset is less than the offset of the previous event. /// /// Equal offsets are valid. - OffsetDecreasing, + OffsetDecreasing { + /// The rejected zero-based frame offset of the event. + offset: usize, + /// The frame offset of the previous event in the slice. + previous: usize, + }, /// The event has a configuration field that is not valid. Config { - /// The dotted path of the field from the root configuration. - field: &'static str, + /// The configuration field that is not valid. + field: ConfigField, + /// The zero-based voice index in `0..=3` for a harmony interval array. + voice: Option, /// The problem with the field. problem: ConfigProblem, }, /// The event has a MIDI message that is not valid. - Midi, + Midi { + /// The specific MIDI field problem. + problem: MidiProblem, + }, } impl Error { - /// Returns an `InvalidConfig` error with a stable, static dotted path. - pub(crate) fn config(field: &'static str, problem: ConfigProblem) -> Self { - Self::InvalidConfig { field, problem } + /// Returns an `InvalidConfig` error for a scalar field. + pub(crate) const fn config(field: ConfigField, problem: ConfigProblem) -> Self { + Self::InvalidConfig { + field, + voice: None, + problem, + } + } + + /// Returns an `InvalidConfig` error for one voice slot of an interval array. + pub(crate) const fn config_voice( + field: ConfigField, + voice: usize, + problem: ConfigProblem, + ) -> Self { + Self::InvalidConfig { + field, + voice: Some(voice), + problem, + } } /// Returns an error if `actual` is not equal to `expected`. /// - /// The stereo and planar process calls and the planar drain call use this - /// length check. The mono calls have only one buffer. - pub(crate) fn check_length(expected: usize, actual: usize) -> Result<(), Self> { + /// The stereo and planar process calls, the planar drain call and the + /// formant envelope call use this length check. + pub(crate) fn check_length( + buffer: BufferName, + expected: usize, + actual: usize, + ) -> Result<(), Self> { if expected == actual { Ok(()) } else { - Err(Self::BufferLength { expected, actual }) + Err(Self::BufferLength { + buffer, + expected, + actual, + }) } } } @@ -137,42 +738,100 @@ impl Error { /// /// The comparison uses single precision, because the controls are defined in /// single precision. -pub(crate) fn check_range( - field: &'static str, - value: f32, - min: f32, - max: f32, -) -> Result<(), Error> { +pub(crate) fn check_range(field: ConfigField, value: f32, min: f32, max: f32) -> Result<(), Error> { if !value.is_finite() { - return Err(Error::config(field, ConfigProblem::NotFinite)); + return Err(Error::config(field, ConfigProblem::NotFinite { value })); } if !(min..=max).contains(&value) { - let (min, max) = (f64::from(min), f64::from(max)); - return Err(Error::config(field, ConfigProblem::OutOfRange { min, max })); + return Err(Error::config( + field, + ConfigProblem::OutOfRange { value, min, max }, + )); } Ok(()) } /// Checks an integer control against `min..=max`. pub(crate) fn check_count( - field: &'static str, - value: i64, - min: i64, - max: i64, + field: ConfigField, + value: i128, + min: i128, + max: i128, ) -> Result<(), Error> { if !(min..=max).contains(&value) { - let (min, max) = (min as f64, max as f64); - return Err(Error::config(field, ConfigProblem::OutOfRange { min, max })); + return Err(Error::config( + field, + ConfigProblem::IntegerOutOfRange { value, min, max }, + )); } Ok(()) } +/// Checks one element of a harmony interval array against `min..=max`. +pub(crate) fn check_voice_count( + field: ConfigField, + voice: usize, + value: i128, + min: i128, + max: i128, +) -> Result<(), Error> { + if !(min..=max).contains(&value) { + return Err(Error::config_voice( + field, + voice, + ConfigProblem::IntegerOutOfRange { value, min, max }, + )); + } + Ok(()) +} + +/// Writes a configuration field and its optional voice slot. +fn write_config_target( + f: &mut fmt::Formatter<'_>, + path: &str, + voice: Option, +) -> fmt::Result { + match voice { + Some(index) => write!(f, "{path}[{index}]"), + None => f.write_str(path), + } +} + impl fmt::Display for ConfigProblem { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Self::OutOfRange { min, max } => write!(f, "must be in {min}..={max}"), - Self::NotFinite => f.write_str("must be finite"), - Self::Unordered { other } => write!(f, "must be below {other}"), + Self::OutOfRange { value, min, max } => { + write!(f, "({value}) must be in {min}..={max}") + } + Self::IntegerOutOfRange { value, min, max } => { + write!(f, "({value}) must be in {min}..={max}") + } + Self::NotFinite { value } => write!(f, "({value}) must be finite"), + Self::Unordered { + value, + other, + other_value, + } => { + write!(f, "({value}) must be below {other} ({other_value})") + } + } + } +} + +impl fmt::Display for MidiProblem { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::StatusByte { byte } => { + write!(f, "MIDI status byte 0x{byte:02x} must be in 0x80..=0xff") + } + Self::DataByte { index, byte } => { + write!(f, "MIDI data byte {index} ({byte}) must be in 0..=127") + } + Self::Channel { channel } => write!(f, "MIDI channel {channel} must be in 0..=15"), + Self::Note { note } => write!(f, "MIDI note {note} must be in 0..=127"), + Self::Velocity { velocity } => { + write!(f, "MIDI velocity {velocity} must be in 0..=127") + } } } } @@ -180,10 +839,21 @@ impl fmt::Display for ConfigProblem { impl fmt::Display for EventProblem { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Self::OffsetOutsideBlock => f.write_str("offset is outside the block"), - Self::OffsetDecreasing => f.write_str("offset is below the previous event's offset"), - Self::Config { field, problem } => write!(f, "{field} {problem}"), - Self::Midi => f.write_str("MIDI message is not valid"), + Self::OffsetOutsideBlock { offset, frames } => { + write!(f, "offset {offset} is outside the block of {frames} frames") + } + Self::OffsetDecreasing { offset, previous } => { + write!(f, "offset {offset} is below previous offset {previous}") + } + Self::Config { + field, + voice, + problem, + } => { + write_config_target(f, field.as_str(), *voice)?; + write!(f, " {problem}") + } + Self::Midi { problem } => write!(f, "{problem}"), } } } @@ -198,11 +868,21 @@ impl fmt::Display for Error { "frequency {hz} Hz must be finite and in 0 < hz <= {max_hz}" ) } - Self::InvalidConfig { field, problem } => { - write!(f, "invalid config: {field} {problem}") + Self::InvalidConfig { + field, + voice, + problem, + } => { + f.write_str("invalid config: ")?; + write_config_target(f, field.as_str(), *voice)?; + write!(f, " {problem}") } - Self::BufferLength { expected, actual } => { - write!(f, "buffer length is {actual}, expected {expected}") + Self::BufferLength { + buffer, + expected, + actual, + } => { + write!(f, "{buffer} buffer length is {actual}, expected {expected}") } Self::BlockTooLarge { frames, max } => { write!( @@ -210,8 +890,19 @@ impl fmt::Display for Error { "block of {frames} frames is larger than the prepared {max}" ) } - Self::InvalidEvent { index, problem } => write!(f, "event {index}: {problem}"), - Self::InvalidMidi => f.write_str("MIDI message is not valid"), + Self::InvalidEvent { + index, + offset, + problem, + } => match problem { + EventProblem::OffsetOutsideBlock { .. } | EventProblem::OffsetDecreasing { .. } => { + write!(f, "event {index}: {problem}") + } + EventProblem::Config { .. } | EventProblem::Midi { .. } => { + write!(f, "event {index} at offset {offset}: {problem}") + } + }, + Self::InvalidMidi { problem } => write!(f, "{problem}"), } } } diff --git a/src/events.rs b/src/events.rs index e1c975c..becdf1e 100644 --- a/src/events.rs +++ b/src/events.rs @@ -9,13 +9,16 @@ use crate::midi::MidiEvent; use crate::{Error, EventProblem, ProcessorConfig, ResynthesisConfig}; /// A configuration or MIDI control that applies before a frame in the block. -/// -/// Give controls to a process call as [`TimedEvent`] values. The call borrows -/// the slice only for that call. There is no heap allocation and no deferred -/// queue. A stage event replaces all settings of that stage. To change one -/// field, start from the current configuration of the processor. -/// Configuration changes have the same effects on state as -/// [`crate::Processor::set_config`]. +#[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = "", + doc = " Give controls to a process call as [`TimedEvent`] values. The call borrows the slice only for that call. There is no heap allocation and no deferred queue. A stage event replaces all settings of that stage. To change one field, start from the current configuration of the processor. Configuration changes have the same effects on state as [`crate::Processor::set_config`]." +)] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = "", + doc = " Give controls to a process call as `TimedEvent` values. A stage event replaces all settings of that stage. To change one field, start from `Tunelet.config()`. Configuration changes have the same effects on state as `Tunelet.setConfig`." +)] #[derive(Clone, Copy, Debug, PartialEq)] #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), @@ -36,12 +39,25 @@ pub enum ControlEvent { /// This event replaces the reverb configuration. Reverb(ReverbConfig), /// This event sets the final linear gain, 0..=64. - /// - /// The quantization and the mute behavior are the same as for - /// [`ProcessorConfig::output_gain`]. The value must be finite. + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = "", + doc = " The quantization and the mute behavior are the same as for [`ProcessorConfig::output_gain`]. The value must be finite." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = "", + doc = " The quantization and the mute behavior are the same as for `ProcessorConfig.outputGain`. The value must be finite." + )] OutputGain(f32), - /// This event sends a note control to the harmony source that - /// [`crate::HarmonyConfig`] selects. + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " This event sends a note control to the harmony source that [`crate::HarmonyConfig`] selects." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " This event sends a note control to the harmony source that `HarmonyConfig` selects." + )] /// /// MIDI-channel mode uses channels 0..=3. Omni mode and MIDI-chord mode /// combine channels. @@ -54,8 +70,14 @@ pub enum ControlEvent { /// correction table. If a later change sets new configured notes, or /// enables or disables correction, the configured mask loads again. CorrectionMidi(MidiEvent), - /// This event resets immediately before the event frame, with the semantics of - /// [`crate::Processor::reset`]. + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " This event resets immediately before the event frame, with the semantics of [`crate::Processor::reset`]." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " This event resets immediately before the event frame, with the semantics of `Tunelet.reset`." + )] /// /// Later events in the same block still run. The processor continues to /// render from this frame. @@ -143,23 +165,35 @@ impl<'a> ValidatedEvents<'a> { pub(crate) fn new(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) + let offset = event.offset; + let problem = if offset >= frames { + Some(EventProblem::OffsetOutsideBlock { offset, frames }) + } else if offset < previous { + Some(EventProblem::OffsetDecreasing { offset, previous }) } else { match event.event.validate() { Ok(()) => None, - Err(Error::InvalidConfig { field, problem }) => { - Some(EventProblem::Config { field, problem }) - } - Err(_) => Some(EventProblem::Midi), + Err(Error::InvalidConfig { + field, + voice, + problem, + }) => Some(EventProblem::Config { + field, + voice, + problem, + }), + Err(Error::InvalidMidi { problem }) => Some(EventProblem::Midi { problem }), + Err(_) => unreachable!("control event validation returns config or MIDI error"), } }; if let Some(problem) = problem { - return Err(Error::InvalidEvent { index, problem }); + return Err(Error::InvalidEvent { + index, + offset, + problem, + }); } - previous = event.offset; + previous = offset; } Ok(Self { remaining: events }) } diff --git a/src/formant.rs b/src/formant.rs index 8bb37f3..8edb43c 100644 --- a/src/formant.rs +++ b/src/formant.rs @@ -23,7 +23,7 @@ use crate::filter::{Biquad, Design}; use crate::lpc; use crate::numeric::fixed::{Q14, Q6}; use crate::numeric::{clamp_i32, db_to_gain, fast_sinc, mul14, round_q14, NumericContext}; -use crate::{Error, SampleRate}; +use crate::{ConfigField, Error, SampleRate}; /// The controls for vocal-tract changes and synthesized aspiration during /// resynthesis. @@ -92,15 +92,28 @@ impl FormantConfig { /// /// # Errors /// - /// Returns the first [`Error::InvalidConfig`], with the dotted path of the - /// field and the problem. + /// Returns the first [`Error::InvalidConfig`], with the [`ConfigField`] and + /// the problem. pub fn validate(self) -> Result<(), Error> { - check_range("resynthesis.formant.width", self.width, 0.5, 2.0)?; - check_range("resynthesis.formant.stretch", self.stretch, 0.5, 2.0)?; - let field = "resynthesis.formant.aspiration_mix"; - check_range(field, self.aspiration_mix, 0.0, 1.0)?; - let field = "resynthesis.formant.aspiration_cutoff_hz"; - check_range(field, self.aspiration_cutoff_hz, 500.0, 10000.0) + check_range(ConfigField::ResynthesisFormantWidth, self.width, 0.5, 2.0)?; + check_range( + ConfigField::ResynthesisFormantStretch, + self.stretch, + 0.5, + 2.0, + )?; + check_range( + ConfigField::ResynthesisFormantAspirationMix, + self.aspiration_mix, + 0.0, + 1.0, + )?; + check_range( + ConfigField::ResynthesisFormantAspirationCutoffHz, + self.aspiration_cutoff_hz, + 500.0, + 10000.0, + ) } } diff --git a/src/harmony.rs b/src/harmony.rs index 67b7111..72e0817 100644 --- a/src/harmony.rs +++ b/src/harmony.rs @@ -6,11 +6,11 @@ mod chords; -use crate::error::{check_count, check_range}; +use crate::error::{check_count, check_range, check_voice_count}; use crate::midi::{note_period, velocity_gain, MidiEvent}; use crate::numeric::fixed::{Q12, Q14, Q6}; use crate::scale::PitchClass; -use crate::{Error, SampleRate}; +use crate::{ConfigField, Error, SampleRate}; use chords::SCALE_TONES; /// The number of harmony voices in addition to the lead voice: four. @@ -33,11 +33,16 @@ const GAIN_ATTACK: Q12 = Q12::from_bits(163); const GAIN_RELEASE: Q12 = Q12::from_bits(81); /// The source of target periods for the four harmony voices. -/// -/// The default is [`Self::MidiChannels`]. The static interval and chord -/// sources use the related [`HarmonyConfig`] fields. The MIDI sources use -/// [`crate::ControlEvent::Midi`]. The configuration of the sources that are -/// not selected is still validated and kept. +#[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = "", + doc = " The default is [`Self::MidiChannels`]. The static interval and chord sources use the related [`HarmonyConfig`] fields. The MIDI sources use [`crate::ControlEvent::Midi`]. Validation checks and keeps the configuration of sources that are not selected." +)] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = "", + doc = " The default is `'midiChannels'`. The static interval and chord sources use the related `HarmonyConfig` fields. The MIDI sources use `ControlEvent` `'midi'`. Validation checks and keeps the configuration of sources that are not selected." +)] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), @@ -45,11 +50,23 @@ const GAIN_RELEASE: Q12 = Q12::from_bits(81); serde(rename_all = "camelCase") )] pub enum HarmonySource { - /// Each voice is a fixed number of semitones from the singer. This source - /// uses `chromatic_intervals`. + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " Each voice is a fixed number of semitones from the singer. This source uses `chromatic_intervals`." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " Each voice is a fixed number of semitones from the singer. This source uses `chromaticIntervals`." + )] FixedInterval, - /// Each voice follows an interval in scale steps from the singer. This - /// source uses `diatonic_intervals`, `key` and `scale`. + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " Each voice follows an interval in scale steps from the singer. This source uses `diatonic_intervals`, `key` and `scale`." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " Each voice follows an interval in scale steps from the singer. This source uses `diatonicIntervals`, `key` and `scale`." + )] SmartInterval, /// The voices sing a chord on a scale degree. This source uses `degree`, /// `key`, `scale` and `inversion`. @@ -57,11 +74,14 @@ pub enum HarmonySource { /// The voices sing a named chord. This source uses `chord`, `key` and /// `inversion`. ChordByName, - /// The voices sing the active MIDI notes as a chord. The register and - /// the spread select new octaves and a new order for these notes. The - /// key and the inversion do not apply. This source combines all - /// channels. It uses the same rules to allocate and steal voices as - /// [`Self::MidiOmni`]. + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The voices sing the active MIDI notes as a chord. The register and the spread select new octaves and a new order for these notes. The key and the inversion do not apply. This source combines all channels. It uses the same rules to allocate and steal voices as [`Self::MidiOmni`]." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The voices sing the active MIDI notes as a chord. The register and the spread select new octaves and a new order for these notes. The key and the inversion do not apply. This source combines all channels. It uses the same rules to allocate and steal voices as `'midiOmni'`." + )] ChordViaMidi, /// A note from any channel goes to the first free voice. If all four /// voices are busy, the note steals the voice with the oldest assignment. @@ -111,7 +131,14 @@ pub enum HarmonyScale { MinorMajorSeventh, } -/// A named chord for [`HarmonySource::ChordByName`]. +#[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " A named chord for [`HarmonySource::ChordByName`]." +)] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " A named chord for `'chordByName'`." +)] /// /// Each variant lists the semitones above the root. These values do not /// include the inversion, the key transposition, the register or the voicing @@ -161,13 +188,26 @@ pub enum ChordName { SuspendedSeventh, } -/// A diatonic chord with its root on a degree of the selected -/// [`HarmonyScale`]. +#[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " A diatonic chord with its root on a degree of the selected [`HarmonyScale`]." +)] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " A diatonic chord with its root on a degree of the selected `HarmonyScale`." +)] /// /// Triads use the root, third and fifth scale degrees. Seventh chords also /// use the seventh. Degrees above the seventh go into higher octaves. The /// degree names do not set a major or minor quality. The selected scale -/// supplies the tones. The default is the tonic triad, [`Self::I`]. +#[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " supplies the tones. The default is the tonic triad, [`Self::I`]." +)] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " supplies the tones. The default is the tonic triad, `'i'`." +)] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[repr(u8)] #[cfg_attr( @@ -261,7 +301,14 @@ pub enum Inversion { serde(rename_all = "camelCase") )] pub struct HarmonyConfig { - /// The pitch source. The default is [`HarmonySource::MidiChannels`]. + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The pitch source. The default is [`HarmonySource::MidiChannels`]." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The pitch source. The default is `'midiChannels'`." + )] pub source: HarmonySource, /// The pitch class of the tonic. The default is C. Smart intervals, named /// chords and degree chords use it. It does not transpose direct MIDI @@ -269,27 +316,43 @@ pub struct HarmonyConfig { pub key: PitchClass, /// The scale for smart intervals and degree chords. The default is major. pub scale: HarmonyScale, - /// Four fixed semitone offsets, each in -24..=24. The default is all - /// zeros. [`HarmonySource::FixedInterval`] uses them. A value of 12 makes - /// the pitch one octave higher. + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " Four fixed semitone offsets, each in -24..=24. The default is all zeros. [`HarmonySource::FixedInterval`] uses them. A value of 12 makes the pitch one octave higher." + )] #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), + doc = " Four fixed semitone offsets, each in -24..=24. The default is all zeros. `'fixedInterval'` uses them. A value of 12 makes the pitch one octave higher.", tsify(type = "[number, number, number, number]") )] pub chromatic_intervals: [i8; HARMONY_VOICES], - /// Four offsets in scale steps, each in -14..=14. The default is all - /// zeros. [`HarmonySource::SmartInterval`] uses them. Seven steps make - /// the pitch one octave higher. + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " Four offsets in scale steps, each in -14..=14. The default is all zeros. [`HarmonySource::SmartInterval`] uses them. Seven steps make the pitch one octave higher." + )] #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), + doc = " Four offsets in scale steps, each in -14..=14. The default is all zeros. `'smartInterval'` uses them. Seven steps make the pitch one octave higher.", tsify(type = "[number, number, number, number]") )] pub diatonic_intervals: [i8; HARMONY_VOICES], - /// The named chord for [`HarmonySource::ChordByName`]. The default is - /// major. + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The named chord for [`HarmonySource::ChordByName`]. The default is major." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The named chord for `'chordByName'`. The default is `'major'`." + )] pub chord: ChordName, - /// The chord on a scale degree for [`HarmonySource::ChordByDegree`]. The - /// default is I. + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The chord on a scale degree for [`HarmonySource::ChordByDegree`]. The default is I." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The chord on a scale degree for `'chordByDegree'`. The default is `'i'`." + )] pub degree: ChordDegree, /// The inversion for named chords and degree chords. The default is root /// position. @@ -316,14 +379,15 @@ pub struct HarmonyConfig { /// semitone bin, each voice starts at its new target without a glide. pub portamento_ms: f32, /// The number of voices that sound in the interval sources, 0..=4. - /// - /// The default is 4. [`HarmonySource::FixedInterval`] and - /// [`HarmonySource::SmartInterval`] use the first `voices` voices. The - /// 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( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = "", + doc = " The default is 4. [`HarmonySource::FixedInterval`] and [`HarmonySource::SmartInterval`] use the first `voices` voices. The 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"), + doc = "", + doc = " The default is 4. `'fixedInterval'` and `'smartInterval'` use the first `voices` voices. The 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.", serde(default = "default_voices"), tsify(optional) )] @@ -366,26 +430,48 @@ impl HarmonyConfig { /// /// # Errors /// - /// Returns the first [`Error::InvalidConfig`] with its dotted field path - /// and the problem. For an array control, the error identifies the array - /// field, not the index of an element. + /// Returns the first [`Error::InvalidConfig`] with its field and the + /// problem. For an interval array control, `voice` holds `Some(0..=3)` for + /// the rejected slot. pub fn validate(self) -> Result<(), Error> { - for interval in self.chromatic_intervals { - let field = "resynthesis.harmony.chromatic_intervals"; - check_count(field, i64::from(interval), -24, 24)?; + for (voice, interval) in self.chromatic_intervals.into_iter().enumerate() { + check_voice_count( + ConfigField::ResynthesisHarmonyChromaticIntervals, + voice, + i128::from(interval), + -24, + 24, + )?; } - for interval in self.diatonic_intervals { - let field = "resynthesis.harmony.diatonic_intervals"; - check_count(field, i64::from(interval), -14, 14)?; + for (voice, interval) in self.diatonic_intervals.into_iter().enumerate() { + check_voice_count( + ConfigField::ResynthesisHarmonyDiatonicIntervals, + voice, + i128::from(interval), + -14, + 14, + )?; } - let field = "resynthesis.harmony.voices"; - check_count(field, i64::from(self.voices), 0, HARMONY_VOICES as i64)?; - let field = "resynthesis.harmony.register_percent"; - check_range(field, self.register_percent, 0.0, 100.0)?; - let field = "resynthesis.harmony.voicing_spread_percent"; - check_range(field, self.voicing_spread_percent, 0.0, 100.0)?; + check_count( + ConfigField::ResynthesisHarmonyVoices, + i128::from(self.voices), + 0, + HARMONY_VOICES as i128, + )?; + check_range( + ConfigField::ResynthesisHarmonyRegisterPercent, + self.register_percent, + 0.0, + 100.0, + )?; + check_range( + ConfigField::ResynthesisHarmonyVoicingSpreadPercent, + self.voicing_spread_percent, + 0.0, + 100.0, + )?; check_range( - "resynthesis.harmony.portamento_ms", + ConfigField::ResynthesisHarmonyPortamentoMs, self.portamento_ms, 0.0, 10_000.0, diff --git a/src/index.ts b/src/index.ts index 8526d77..4b67b49 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,19 +1,509 @@ /** * The shared ESM entry point for browsers and Node.js. * - * Call `loadTunelet()` before you construct processors or read the default - * configuration. Both environments use the same generated bindings and the - * same Wasm binary. This module re-exports all named exports of the module - * that wasm-bindgen generates, which include `Tunelet`, `defaultConfig`, - * `initSync` and the configuration, event and feedback types. + * Call `loadTunelet()` or `initSync()` before you construct processors or read + * the default configuration. Both environments use the same generated bindings + * and the same Wasm binary. This module exports `Tunelet`, `TuneletError`, + * `defaultConfig`, `initSync`, `loadTunelet` and the public TypeScript types. */ -import init from "../pkg/tunelet.js"; -import type { InitInput, InitOutput } from "../pkg/tunelet.js"; +import rawInit, { + Tunelet as RawTunelet, + defaultConfig as rawDefaultConfig, + initSync as rawInitSync, +} from "../pkg/tunelet.js"; +import type { + AlienConfig, + BufferName, + ChordDegree, + ChordName, + ConfigField, + ConfigProblemKind, + ControlEvent, + CorrectionConfig, + CorrectionScale, + ErrorDetails, + EventProblemKind, + Feedback, + FormantConfig, + HarmonyConfig, + HarmonyScale, + HarmonySource, + InitInput, + InitOutput, + InputTarget, + Inversion, + MidiEvent, + MidiProblemKind, + MultiVoiceMode, + NoteMask, + PitchClass, + PitchConfig, + ProcessorConfig, + PunchConfig, + ResynthesisConfig, + ReverbConfig, + ReverbMode, + SyncInitInput, + Telemetry, + TimedEvent, + WarmConfig, +} from "../pkg/tunelet.js"; -export * from "../pkg/tunelet.js"; +export type { + AlienConfig, + BufferName, + ChordDegree, + ChordName, + ConfigField, + ConfigProblemKind, + ControlEvent, + CorrectionConfig, + CorrectionScale, + ErrorDetails, + EventProblemKind, + Feedback, + FormantConfig, + HarmonyConfig, + HarmonyScale, + HarmonySource, + InitInput, + InitOutput, + InputTarget, + Inversion, + MidiEvent, + MidiProblemKind, + MultiVoiceMode, + NoteMask, + PitchClass, + PitchConfig, + ProcessorConfig, + PunchConfig, + ResynthesisConfig, + ReverbConfig, + ReverbMode, + SyncInitInput, + Telemetry, + TimedEvent, + WarmConfig, +}; -/** The shared initialization promise, which a failure clears. */ -let initialization: Promise | undefined; +/** + * A structured error that `Tunelet`, `defaultConfig`, `initSync` or + * `loadTunelet` throws. + * + * Every failure exposes both a plain `camelCase` `message` and typed + * diagnostic fields on `details`. + */ +export class TuneletError extends Error { + /** Machine-readable details for the rejected operation. */ + readonly details: ErrorDetails; + + /** The optional underlying cause of this error. */ + readonly cause?: unknown; + + /** + * Constructs a `TuneletError` with a message and structured `details`. + * + * @param message The human-readable error message. + * @param details The structured diagnostic payload. + * @param options Optional settings such as `cause`. + */ + constructor( + message: string, + details: ErrorDetails, + options?: { readonly cause?: unknown }, + ) { + super(message); + this.name = "TuneletError"; + this.details = details; + if (options !== undefined && "cause" in options) { + this.cause = options.cause; + } + Object.setPrototypeOf(this, new.target.prototype); + } +} + +/** The packaged Wasm URL relative to this module. */ +const DEFAULT_WASM_URL = new URL("../pkg/tunelet_bg.wasm", import.meta.url); + +/** The required export names and kinds on a valid Tunelet Wasm module. */ +const REQUIRED_WASM_EXPORTS: ReadonlyArray = [ + ["memory", "memory"], + ["__wbindgen_start", "function"], + ["__wbg_tunelet_free", "function"], + ["defaultConfig", "function"], + ["tunelet_beginDrain", "function"], + ["tunelet_config", "function"], + ["tunelet_drain", "function"], + ["tunelet_drainMono", "function"], + ["tunelet_feedback", "function"], + ["tunelet_formantEnvelope", "function"], + ["tunelet_latencyFrames", "function"], + ["tunelet_maxBlockFrames", "function"], + ["tunelet_new", "function"], + ["tunelet_process", "function"], + ["tunelet_processMono", "function"], + ["tunelet_reset", "function"], + ["tunelet_sampleRate", "function"], + ["tunelet_setConfig", "function"], + ["tunelet_tailFrames", "function"], + ["tunelet_takeFeedback", "function"], + ["tunelet_takeTelemetry", "function"], + ["tunelet_telemetry", "function"], +]; + +const NOT_INITIALIZED_MESSAGE = + "WebAssembly is not initialized; call await loadTunelet() or initSync() first"; +const DISPOSED_MESSAGE = "Tunelet processor is disposed after free()"; +const SOURCE_MISMATCH_MESSAGE = + "WebAssembly source does not match the active Tunelet module"; + +type SourceDescriptor = + | { readonly kind: "url"; readonly href: string } + | { readonly kind: "string"; readonly value: string } + | { readonly kind: "request"; readonly url: string; readonly ref: Request } + | { readonly kind: "response"; readonly ref: Response } + | { readonly kind: "module"; readonly module: WebAssembly.Module } + | { readonly kind: "bytes"; readonly bytes: Uint8Array } + | { readonly kind: "invalid"; readonly value: unknown }; + +type SdkState = + | { readonly status: "uninitialized" } + | { + readonly status: "loading"; + readonly sourcePromise: Promise; + readonly initPromise: Promise; + } + | { + readonly status: "ready"; + readonly source: SourceDescriptor; + readonly output: InitOutput; + }; + +let sdkState: SdkState = { status: "uninitialized" }; + +/** Ensures WebAssembly initialization is complete before a synchronous call. */ +function assertInitialized(): void { + if (sdkState.status !== "ready") { + throw new TuneletError(NOT_INITIALIZED_MESSAGE, { type: "notInitialized" }); + } +} + +/** Converts an unknown Wasm exception into a `TuneletError`. */ +function toTuneletError( + error: unknown, + fallbackDetails: ErrorDetails, +): TuneletError { + if (error instanceof TuneletError) { + return error; + } + if (error instanceof Error) { + const candidate = (error as Error & { details?: unknown }).details; + const details = isErrorDetails(candidate) ? candidate : fallbackDetails; + return new TuneletError(error.message, details, { cause: error }); + } + return new TuneletError(String(error), fallbackDetails, { cause: error }); +} + +/** Checks that an attached value has the `type` discriminant of `ErrorDetails`. */ +function isErrorDetails(value: unknown): value is ErrorDetails { + return ( + typeof value === "object" && + value !== null && + typeof (value as { type?: unknown }).type === "string" + ); +} + +/** Returns a `Uint8Array` view over an `ArrayBuffer` or `ArrayBufferView`. */ +function asByteView(buffer: BufferSource): Uint8Array { + if (buffer instanceof ArrayBuffer) { + return new Uint8Array(buffer); + } + return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength); +} + +/** Checks whether two byte views contain identical bytes. */ +function bytesEqual(left: Uint8Array, right: Uint8Array): boolean { + if (left.byteLength !== right.byteLength) { + return false; + } + for (let index = 0; index < left.byteLength; index += 1) { + if (left[index] !== right[index]) { + return false; + } + } + return true; +} + +/** Checks whether a value is a Fetch API `Response`. */ +function isResponse(value: unknown): value is Response { + return typeof Response === "function" && value instanceof Response; +} + +/** Normalizes an initialization input so repeated calls can compare sources. */ +function describeSource(input: InitInput | undefined): SourceDescriptor { + if (input === undefined) { + return { kind: "url", href: DEFAULT_WASM_URL.href }; + } + if (input instanceof URL) { + return { kind: "url", href: input.href }; + } + if (typeof input === "string") { + return { kind: "string", value: input }; + } + if (input instanceof WebAssembly.Module) { + return { kind: "module", module: input }; + } + if (input instanceof ArrayBuffer || ArrayBuffer.isView(input)) { + return { kind: "bytes", bytes: asByteView(input) }; + } + if (typeof Request === "function" && input instanceof Request) { + return { kind: "request", url: input.url, ref: input }; + } + if (isResponse(input)) { + return { kind: "response", ref: input }; + } + return { kind: "invalid", value: input }; +} + +/** Compares two normalized source descriptors for equivalence. */ +function sourcesMatch(left: SourceDescriptor, right: SourceDescriptor): boolean { + if (left.kind === "invalid" || right.kind === "invalid") { + return false; + } + if (left.kind !== right.kind) { + return false; + } + switch (left.kind) { + case "url": + return left.href === (right as typeof left).href; + case "string": + return left.value === (right as typeof left).value; + case "request": + return ( + left.ref === (right as typeof left).ref || + left.url === (right as typeof left).url + ); + case "response": + return left.ref === (right as typeof left).ref; + case "module": + return left.module === (right as typeof left).module; + case "bytes": + return bytesEqual(left.bytes, (right as typeof left).bytes); + } +} + +/** + * Checks that a compiled `WebAssembly.Module` has the exports and import + * namespace of the packaged Tunelet bindings. + */ +function validateWasmModule(module: WebAssembly.Module): void { + const exportMap = new Map(); + for (const entry of WebAssembly.Module.exports(module)) { + exportMap.set(entry.name, entry.kind); + } + for (const [name, kind] of REQUIRED_WASM_EXPORTS) { + if (exportMap.get(name) !== kind) { + throw new TuneletError( + `custom WebAssembly module is missing required ${kind} export '${name}'`, + { type: "sourceMismatch" }, + ); + } + } + for (const entry of WebAssembly.Module.imports(module)) { + if (entry.module !== "./tunelet_bg.js") { + throw new TuneletError( + `custom WebAssembly module imports unexpected namespace '${entry.module}'`, + { type: "sourceMismatch" }, + ); + } + } +} + +/** Compiles bytes to a `WebAssembly.Module` or throws a `sourceMismatch` error. */ +async function compileWasmBytes(bytes: BufferSource): Promise { + try { + const view = asByteView(bytes); + const copy = new Uint8Array(view.byteLength); + copy.set(view); + return await WebAssembly.compile(copy); + } catch (error: unknown) { + throw new TuneletError( + "custom WebAssembly source failed to compile", + { type: "sourceMismatch" }, + { cause: error }, + ); + } +} + +/** Compiles a `Response` body to a `WebAssembly.Module`. */ +async function compileWasmResponse( + response: Response, +): Promise { + if (!response.ok) { + throw new Error( + `failed to fetch Wasm: ${response.status} ${response.statusText} for '${response.url}'`, + ); + } + if (typeof WebAssembly.compileStreaming === "function") { + try { + return await WebAssembly.compileStreaming(response); + } catch (error: unknown) { + const canFallback = + (response.type === "basic" || + response.type === "cors" || + response.type === "default") && + response.headers.get("Content-Type") !== "application/wasm"; + if (!canFallback) { + throw new TuneletError( + "custom WebAssembly response failed to compile", + { type: "sourceMismatch" }, + { cause: error }, + ); + } + } + } + const bytes = await response.arrayBuffer(); + return compileWasmBytes(bytes); +} + +/** Loads, validates and instantiates a `WebAssembly.Module` from an `InitInput`. */ +async function instantiateFromInput( + input: InitInput | undefined, +): Promise<{ readonly source: SourceDescriptor; readonly output: InitOutput }> { + const resolved = input === undefined ? DEFAULT_WASM_URL : input; + const source = describeSource(input); + if (source.kind === "invalid") { + throw new TuneletError( + "unsupported WebAssembly initialization source", + { type: "sourceMismatch" }, + ); + } + + let module: WebAssembly.Module; + if (resolved instanceof WebAssembly.Module) { + module = resolved; + } else if (resolved instanceof ArrayBuffer || ArrayBuffer.isView(resolved)) { + module = await compileWasmBytes(resolved); + } else if (resolved instanceof URL && resolved.protocol === "file:") { + // Keep the Node.js built-in module out of browser bundles. TypeScript + // removes the type-only import. The runtime import runs only for `file:` + // URLs. + const moduleName = "node:fs/promises"; + const fs: typeof import("node:fs/promises") = await import( + /* webpackIgnore: true */ /* @vite-ignore */ moduleName + ); + const fileBytes = await fs.readFile(resolved); + module = await compileWasmBytes(fileBytes); + } else if (isResponse(resolved)) { + module = await compileWasmResponse(resolved); + } else { + const response = await fetch(resolved); + module = await compileWasmResponse(response); + } + + validateWasmModule(module); + + try { + const output = await rawInit({ module_or_path: module }); + return { source, output }; + } catch (error: unknown) { + throw new TuneletError( + "custom WebAssembly module failed to link with Tunelet bindings", + { type: "sourceMismatch" }, + { cause: error }, + ); + } +} + +/** Extracts the raw `SyncInitInput` from `initSync` arguments. */ +function unwrapSyncInput( + module: SyncInitInput | { module: SyncInitInput }, +): SyncInitInput { + if ( + typeof module === "object" && + module !== null && + !(module instanceof WebAssembly.Module) && + !(module instanceof ArrayBuffer) && + !ArrayBuffer.isView(module) && + "module" in module + ) { + return module.module; + } + return module as SyncInitInput; +} + +/** + * Synchronously initializes the Wasm module from bytes or a compiled + * `WebAssembly.Module`. + * + * If the module is already initialized with the same source, this function + * returns the active exports. If a different source is active or in flight, + * or if the custom module does not match the Tunelet bindings, this function + * throws a `TuneletError`. + * + * @param module A `BufferSource`, a `WebAssembly.Module`, or `{ module }`. + * @returns The initialized Wasm exports. + */ +export function initSync( + module: SyncInitInput | { module: SyncInitInput }, +): InitOutput { + const rawInput = unwrapSyncInput(module); + const candidate = describeSource(rawInput); + if (candidate.kind !== "module" && candidate.kind !== "bytes") { + throw new TuneletError( + "initSync requires a BufferSource or WebAssembly.Module", + { type: "sourceMismatch" }, + ); + } + + if (sdkState.status === "ready") { + if (!sourcesMatch(sdkState.source, candidate)) { + throw new TuneletError(SOURCE_MISMATCH_MESSAGE, { + type: "sourceMismatch", + }); + } + return sdkState.output; + } + + if (sdkState.status === "loading") { + throw new TuneletError(SOURCE_MISMATCH_MESSAGE, { + type: "sourceMismatch", + }); + } + + let compiled: WebAssembly.Module; + if (rawInput instanceof WebAssembly.Module) { + compiled = rawInput; + } else { + try { + const view = asByteView(rawInput); + const copy = new Uint8Array(view.byteLength); + copy.set(view); + compiled = new WebAssembly.Module(copy); + } catch (error: unknown) { + throw new TuneletError( + "custom WebAssembly source failed to compile", + { type: "sourceMismatch" }, + { cause: error }, + ); + } + } + + validateWasmModule(compiled); + + try { + const output = rawInitSync({ module: compiled }); + sdkState = { status: "ready", source: candidate, output }; + return output; + } catch (error: unknown) { + throw new TuneletError( + "custom WebAssembly module failed to link with Tunelet bindings", + { type: "sourceMismatch" }, + { cause: error }, + ); + } +} /** * Initializes the Wasm module one time for this imported package instance. @@ -27,57 +517,409 @@ let initialization: Promise | undefined; * * - A URL. * - A fetch Response. - * - A byte buffer (BufferSource). - * - A compiled WebAssembly.Module. + * - A byte buffer (`BufferSource`). + * - A compiled `WebAssembly.Module`. * - A promise for one of these. * - * A string source obeys fetch rules. For a Node.js `file:` source, use a - * URL object. A compiled module must use imports that agree with the packaged - * bindings. - * - * Concurrent calls share one promise, and the first call selects the source. - * After a successful initialization, later calls use it again and do not load - * Wasm again, whatever their arguments are. If an attempt fails, the promise - * rejects and the function clears the cached promise. Then you can try again. - * File, network and Wasm errors go to the caller. The function does not try a - * different load method after an error. + * Concurrent or repeated calls with the same source share one initialization + * result. A call with a different source, or with a binary that does not match + * the Tunelet bindings, rejects with a `TuneletError`. If the initial load + * fails, the cached promise clears so the caller can try again. * * @param source The optional Wasm source. The default is the binary in this * package. - * @returns The initialized Wasm exports. Use the re-exported `Tunelet` class - * for processors. + * @returns The initialized Wasm exports. Use the exported `Tunelet` class for + * processors. */ -export function loadTunelet( +export async function loadTunelet( source?: InitInput | Promise, ): Promise { - initialization ??= initialize(source).catch((error: unknown) => { - initialization = undefined; - throw error; - }); - return initialization; -} + if (sdkState.status === "ready") { + const resolved = source === undefined ? undefined : await source; + const candidate = describeSource(resolved); + if (!sourcesMatch(sdkState.source, candidate)) { + throw new TuneletError(SOURCE_MISMATCH_MESSAGE, { + type: "sourceMismatch", + }); + } + return sdkState.output; + } -/** Awaits the source one time, then initializes the Wasm module from it. */ -async function initialize( - source: InitInput | Promise | undefined, -): Promise { - const input = - source === undefined - ? new URL("../pkg/tunelet_bg.wasm", import.meta.url) - : await source; + if (sdkState.status === "loading") { + const current = sdkState; + const resolved = source === undefined ? undefined : await source; + const candidate = describeSource(resolved); + const activeSource = await current.sourcePromise; + if (!sourcesMatch(activeSource, candidate)) { + throw new TuneletError(SOURCE_MISMATCH_MESSAGE, { + type: "sourceMismatch", + }); + } + return current.initPromise; + } - if (input instanceof URL && input.protocol === "file:") { - // Keep the Node.js built-in module out of browser bundles. TypeScript - // removes the type-only import. The runtime import runs only for `file:` - // URLs. - const moduleName = "node:fs/promises"; - const fs: typeof import("node:fs/promises") = await import( - /* webpackIgnore: true */ /* @vite-ignore */ moduleName + const inputPromise = Promise.resolve(source); + const sourcePromise = inputPromise.then((resolved) => + describeSource(resolved), + ); + // Suppress an unhandled rejection on the helper branch if inputPromise rejects. + sourcePromise.catch(() => undefined); + + const initPromise = inputPromise + .then((resolved) => instantiateFromInput(resolved)) + .then( + ({ source: finalSource, output }) => { + sdkState = { status: "ready", source: finalSource, output }; + return output; + }, + (error: unknown) => { + sdkState = { status: "uninitialized" }; + throw error; + }, ); - return init({ module_or_path: await fs.readFile(input) }); + + sdkState = { status: "loading", sourcePromise, initPromise }; + return initPromise; +} + +/** + * Returns a complete, independent default configuration for JavaScript. + * + * Call `await loadTunelet()` or `initSync()` before this function. Change the + * returned fields and pass the object to `new Tunelet(...)` or `setConfig`. + * `resynthesis.randomSeed` is a `bigint`, so it keeps all 64 bits. + * + * @returns A new `ProcessorConfig` with default values. + */ +export function defaultConfig(): ProcessorConfig { + assertInitialized(); + try { + return rawDefaultConfig(); + } catch (error: unknown) { + throw toTuneletError(error, { type: "serializationFailed" }); + } +} + +/** + * A stateful PCM vocal processor that runs in WebAssembly. + * + * The input is signed 16-bit mono PCM. The output is planar stereo or an + * in-place mono downmix. Buffer lengths count frames, not bytes. + * + * Call `await loadTunelet()` or `initSync()` before you construct an instance. + * Every validation or lifecycle failure throws a `TuneletError` before the + * audio state or output buffers change. Call `free()` or `[Symbol.dispose]()` + * to release WebAssembly memory. Repeated `free()` calls do nothing, and calls + * after `free()` throw a `TuneletError`. + */ +export class Tunelet { + #inner: RawTunelet | undefined; + + /** + * Prepares a processor and its reusable PCM buffers. + * + * `sampleRate` must be `44100` or `48000`. `maxBlockFrames` must be an + * integer in `1..=4294967295`. Omit `config` to start from `defaultConfig()`. + * + * @param sampleRate The input and output sample rate in hertz (`44100` or `48000`). + * @param maxBlockFrames The maximum frame count for each process or drain call. + * @param config Optional initial `ProcessorConfig`. + */ + constructor( + sampleRate: number, + maxBlockFrames: number, + config?: ProcessorConfig, + ) { + assertInitialized(); + if (config === null) { + throw new TuneletError( + "invalid ProcessorConfig: expected an object, got null", + { type: "invalidInput", target: "ProcessorConfig" }, + ); + } + try { + this.#inner = new RawTunelet(sampleRate, maxBlockFrames, config); + } catch (error: unknown) { + throw toTuneletError(error, { + type: "invalidInput", + target: "ProcessorConfig", + }); + } + } + + /** Returns the live Wasm handle or throws a disposed `TuneletError`. */ + #requireInner(): RawTunelet { + const inner = this.#inner; + if (inner === undefined) { + throw new TuneletError(DISPOSED_MESSAGE, { type: "disposed" }); + } + return inner; + } + + /** The fixed sample rate of the input and the output in hertz. */ + get sampleRate(): number { + return this.#requireInner().sampleRate; } - return init({ module_or_path: input }); + /** The maximum frame count for each call that processes or drains audio. */ + get maxBlockFrames(): number { + return this.#requireInner().maxBlockFrames; + } + + /** The nominal resynthesis delay in frames. */ + get latencyFrames(): number { + return this.#requireInner().latencyFrames; + } + + /** + * Returns a copy of the active configuration as a new JavaScript object. + * + * A change to the returned object has no effect until `setConfig` or a timed + * event applies it. + */ + config(): ProcessorConfig { + const inner = this.#requireInner(); + try { + return inner.config(); + } catch (error: unknown) { + throw toTuneletError(error, { type: "serializationFailed" }); + } + } + + /** + * Validates a configuration and replaces the active configuration with it. + * + * If validation fails, this method throws a `TuneletError` and keeps the + * processor state and any active drain unchanged. + * + * @param config The complete `ProcessorConfig` to apply. + */ + setConfig(config: ProcessorConfig): void { + const inner = this.#requireInner(); + if (config === null || config === undefined) { + throw new TuneletError( + `invalid ProcessorConfig: expected an object, got ${String(config)}`, + { type: "invalidInput", target: "ProcessorConfig" }, + ); + } + try { + inner.setConfig(config); + } catch (error: unknown) { + throw toTuneletError(error, { + type: "invalidInput", + target: "ProcessorConfig", + }); + } + } + + /** + * Processes mono PCM input into left and right `Int16Array` buffers of equal + * length. + * + * Optional `events` apply immediately before their zero-based frame offset. + * If an error occurs, this method throws a `TuneletError` before the output + * arrays or the DSP state change. + * + * @param input Mono signed 16-bit PCM input frames. + * @param left Left-channel signed 16-bit PCM output buffer. + * @param right Right-channel signed 16-bit PCM output buffer. + * @param events Optional ordered `TimedEvent[]` controls for this block. + */ + process( + input: Int16Array, + left: Int16Array, + right: Int16Array, + events?: TimedEvent[], + ): void { + const inner = this.#requireInner(); + if (events === null) { + throw new TuneletError( + "invalid TimedEvent[]: expected an array, got null", + { type: "invalidInput", target: "TimedEvent[]" }, + ); + } + try { + inner.process(input, left, right, events); + } catch (error: unknown) { + throw toTuneletError(error, { + type: "invalidInput", + target: "TimedEvent[]", + }); + } + } + + /** + * Replaces mono PCM in `audio` with the stereo downmix. + * + * Optional `events` apply immediately before their zero-based frame offset. + * If an error occurs, this method throws a `TuneletError` before `audio` or + * the DSP state changes. + * + * @param audio In-place mono signed 16-bit PCM buffer. + * @param events Optional ordered `TimedEvent[]` controls for this block. + */ + processMono(audio: Int16Array, events?: TimedEvent[]): void { + const inner = this.#requireInner(); + if (events === null) { + throw new TuneletError( + "invalid TimedEvent[]: expected an array, got null", + { type: "invalidInput", target: "TimedEvent[]" }, + ); + } + try { + inner.processMono(audio, events); + } catch (error: unknown) { + throw toTuneletError(error, { + type: "invalidInput", + target: "TimedEvent[]", + }); + } + } + + /** + * Starts a finite tail budget and returns its frame count. + * + * Call this method one time after the final input block. + */ + beginDrain(): number { + return this.#requireInner().beginDrain(); + } + + /** Returns the tail budget of the current configuration in frames. */ + tailFrames(): number { + return this.#requireInner().tailFrames(); + } + + /** + * Renders stereo tail frames into `left` and `right` buffers of equal length. + * + * Returns the number of rendered frames and fills unused frames with zeros. + * + * @param left Left-channel signed 16-bit PCM output buffer. + * @param right Right-channel signed 16-bit PCM output buffer. + */ + drain(left: Int16Array, right: Int16Array): number { + const inner = this.#requireInner(); + try { + return inner.drain(left, right); + } catch (error: unknown) { + throw toTuneletError(error, { + type: "bufferLength", + buffer: "right", + expected: left.length, + actual: right.length, + }); + } + } + + /** + * Renders a mono tail block into `audio` and returns its rendered frame count. + * + * Fills unused frames with zeros. + * + * @param audio Mono signed 16-bit PCM output buffer. + */ + drainMono(audio: Int16Array): number { + const inner = this.#requireInner(); + try { + return inner.drainMono(audio); + } catch (error: unknown) { + throw toTuneletError(error, { + type: "blockTooLarge", + frames: audio.length, + max: inner.maxBlockFrames, + }); + } + } + + /** Returns a feedback snapshot and does not clear the stereo peak window. */ + feedback(): Feedback { + const inner = this.#requireInner(); + try { + return inner.feedback(); + } catch (error: unknown) { + throw toTuneletError(error, { type: "serializationFailed" }); + } + } + + /** Returns a feedback snapshot and clears only the stereo peak window. */ + takeFeedback(): Feedback { + const inner = this.#requireInner(); + try { + return inner.takeFeedback(); + } catch (error: unknown) { + throw toTuneletError(error, { type: "serializationFailed" }); + } + } + + /** Returns a telemetry snapshot and does not clear its three peak windows. */ + telemetry(): Telemetry { + const inner = this.#requireInner(); + try { + return inner.telemetry(); + } catch (error: unknown) { + throw toTuneletError(error, { type: "serializationFailed" }); + } + } + + /** Returns a telemetry snapshot and clears only its three peak windows. */ + takeTelemetry(): Telemetry { + const inner = this.#requireInner(); + try { + return inner.takeTelemetry(); + } catch (error: unknown) { + throw toTuneletError(error, { type: "serializationFailed" }); + } + } + + /** + * Writes the LPC analysis and synthesis formant envelopes into two + * `Float32Array` buffers of equal length. + * + * `maxFrequencyHz` must be finite, greater than zero and at most half of + * `sampleRate`. Returns `false` and fills both arrays with zeros when no + * formant model is active. + * + * @param maxFrequencyHz The frequency of the final envelope point in hertz. + * @param input Output buffer for the LPC analysis envelope. + * @param output Output buffer for the shifted synthesis envelope. + */ + formantEnvelope( + maxFrequencyHz: number, + input: Float32Array, + output: Float32Array, + ): boolean { + const inner = this.#requireInner(); + try { + return inner.formantEnvelope(maxFrequencyHz, input, output); + } catch (error: unknown) { + throw toTuneletError(error, { type: "allocationFailed" }); + } + } + + /** Resets the audio histories, held notes, pitch feedback, peak and frame count. */ + reset(): void { + this.#requireInner().reset(); + } + + /** + * Releases the WebAssembly processor memory. + * + * Repeated calls are safe no-ops. Any other method or getter call after + * `free()` throws a `TuneletError`. + */ + free(): void { + const inner = this.#inner; + if (inner !== undefined) { + this.#inner = undefined; + inner.free(); + } + } + + /** Releases the WebAssembly processor memory for `using` scopes. */ + [Symbol.dispose](): void { + this.free(); + } } /** The default export is the same function as `loadTunelet`. */ diff --git a/src/lib.rs b/src/lib.rs index f17bc85..98d8da2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -126,7 +126,7 @@ pub use effects::alien::AlienConfig; pub use effects::punch::PunchConfig; pub use effects::reverb::{ReverbConfig, ReverbMode}; pub use effects::warm::WarmConfig; -pub use error::{ConfigProblem, Error, EventProblem}; +pub use error::{BufferName, ConfigField, ConfigProblem, Error, EventProblem, MidiProblem}; pub use events::{ControlEvent, TimedEvent}; pub use formant::FormantConfig; pub use harmony::{ diff --git a/src/midi.rs b/src/midi.rs index 63f8660..f91ddf6 100644 --- a/src/midi.rs +++ b/src/midi.rs @@ -1,15 +1,19 @@ //! MIDI note messages, pitch periods and the conversion of velocity to gain. use crate::numeric::fixed::{Q12, Q6}; -use crate::Error; +use crate::{Error, MidiProblem}; /// The supported MIDI note controls, with zero-based channel numbers. -/// -/// Use [`crate::ControlEvent::Midi`] for harmony. Use -/// [`crate::ControlEvent::CorrectionMidi`] for the independent correction -/// keyboard. The typed representation can contain `u8` values that are not -/// valid. [`Self::validate`] and the event preflight of the processor check -/// the MIDI ranges. Note numbers use A4 = 69 at 440 Hz. +#[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = "", + doc = " Use [`crate::ControlEvent::Midi`] for harmony. Use [`crate::ControlEvent::CorrectionMidi`] for the independent correction keyboard. The typed representation can contain `u8` values that are not valid. [`Self::validate`] and the event preflight of the processor check the MIDI ranges. Note numbers use A4 = 69 at 440 Hz." +)] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = "", + doc = " Use `ControlEvent` `'midi'` for harmony. Use `ControlEvent` `'correctionMidi'` for the independent correction keyboard. The event preflight of the processor checks the MIDI ranges. Note numbers use A4 = 69 at 440 Hz." +)] #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), @@ -24,8 +28,16 @@ pub enum MidiEvent { /// The MIDI note, 0..=127. note: u8, /// The velocity, 0..=127. - /// - /// Zero releases the note, as [`Self::NoteOff`] does. + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = "", + doc = " Zero releases the note, as [`Self::NoteOff`] does." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = "", + doc = " Zero releases the note, as `'noteOff'` does." + )] velocity: u8, }, /// A note stops. @@ -63,11 +75,30 @@ impl MidiEvent { /// /// # Errors /// - /// Returns [`Error::InvalidMidi`] if the status is below `0x80` or a data + /// Returns [`Error::InvalidMidi`] with [`MidiProblem::StatusByte`] if the + /// status byte is below `0x80`, or with [`MidiProblem::DataByte`] if a data /// byte is more than 127. This also applies to an unsupported message. pub fn from_bytes(bytes: [u8; 3]) -> Result, Error> { - if bytes[0] < 0x80 || bytes[1] > 127 || bytes[2] > 127 { - return Err(Error::InvalidMidi); + if bytes[0] < 0x80 { + return Err(Error::InvalidMidi { + problem: MidiProblem::StatusByte { byte: bytes[0] }, + }); + } + if bytes[1] > 127 { + return Err(Error::InvalidMidi { + problem: MidiProblem::DataByte { + index: 1, + byte: bytes[1], + }, + }); + } + if bytes[2] > 127 { + return Err(Error::InvalidMidi { + problem: MidiProblem::DataByte { + index: 2, + byte: bytes[2], + }, + }); } let channel = bytes[0] & 15; Ok(match bytes[0] & 0xf0 { @@ -89,20 +120,47 @@ impl MidiEvent { /// /// # Errors /// - /// Returns [`Error::InvalidMidi`] if a channel is more than 15, or if a - /// note or a velocity is more than 127. Zero velocity and All Notes Off - /// are valid. + /// Returns [`Error::InvalidMidi`] with [`MidiProblem::Channel`], + /// [`MidiProblem::Note`] or [`MidiProblem::Velocity`] if a field is out of + /// range. Zero velocity and All Notes Off are valid. pub fn validate(&self) -> Result<(), Error> { match *self { Self::NoteOn { channel, note, velocity, - } if channel > 15 || note > 127 || velocity > 127 => Err(Error::InvalidMidi), - Self::NoteOff { channel, note } if channel > 15 || note > 127 => { - Err(Error::InvalidMidi) + } => { + if channel > 15 { + return Err(Error::InvalidMidi { + problem: MidiProblem::Channel { channel }, + }); + } + if note > 127 { + return Err(Error::InvalidMidi { + problem: MidiProblem::Note { note }, + }); + } + if velocity > 127 { + return Err(Error::InvalidMidi { + problem: MidiProblem::Velocity { velocity }, + }); + } + Ok(()) + } + Self::NoteOff { channel, note } => { + if channel > 15 { + return Err(Error::InvalidMidi { + problem: MidiProblem::Channel { channel }, + }); + } + if note > 127 { + return Err(Error::InvalidMidi { + problem: MidiProblem::Note { note }, + }); + } + Ok(()) } - _ => Ok(()), + Self::AllNotesOff => Ok(()), } } } diff --git a/src/pitch.rs b/src/pitch.rs index 6b682ca..7b3c8dc 100644 --- a/src/pitch.rs +++ b/src/pitch.rs @@ -9,7 +9,7 @@ mod search; pub(crate) mod tracker; use crate::error::{check_range, ConfigProblem}; -use crate::Error; +use crate::{ConfigField, Error}; /// The acquisition sensitivity and the bounds for pitch reports to the host. #[derive(Clone, Copy, Debug, PartialEq)] @@ -28,16 +28,30 @@ pub struct PitchConfig { pub threshold: f32, /// The lower bound of the feedback in hertz (inclusive), 40..=2000. /// - /// The default is 40. It must be strictly less than `max_frequency_hz`. + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The default is 40. It must be strictly less than `max_frequency_hz`." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The default is 40. It must be strictly less than `maxFrequencyHz`." + )] /// These bounds do not change the tracking, the correction or the /// resampling. A feedback query applies the current bounds to the kept /// analysis. It does not process another sample. pub min_frequency_hz: f32, /// The upper bound of the feedback in hertz (inclusive), 40..=2000. /// - /// The default is 1100. It must be strictly greater than - /// `min_frequency_hz`. Results outside the bounds are reported as - /// unvoiced, with zero frequency and zero period. + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The default is 1100. It must be strictly greater than `min_frequency_hz`." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The default is 1100. It must be strictly greater than `minFrequencyHz`." + )] + /// Results outside the bounds are reported as unvoiced, with zero frequency + /// and zero period. pub max_frequency_hz: f32, } @@ -75,19 +89,32 @@ impl PitchConfig { /// /// Returns [`Error::InvalidConfig`] for a value that is not finite or is /// out of range. If the bounds are equal or reversed, the error has the - /// field `resynthesis.pitch.min_frequency_hz` and the problem + /// field [`ConfigField::ResynthesisPitchMinFrequencyHz`] and the problem /// [`ConfigProblem::Unordered`]. The `other` value of that problem is - /// `resynthesis.pitch.max_frequency_hz`. + /// [`ConfigField::ResynthesisPitchMaxFrequencyHz`], and both rejected + /// bounds are stored. pub fn validate(self) -> Result<(), Error> { - check_range("resynthesis.pitch.threshold", self.threshold, 0.002, 0.2)?; + check_range( + ConfigField::ResynthesisPitchThreshold, + self.threshold, + 0.002, + 0.2, + )?; let (min, max) = ( - "resynthesis.pitch.min_frequency_hz", - "resynthesis.pitch.max_frequency_hz", + ConfigField::ResynthesisPitchMinFrequencyHz, + ConfigField::ResynthesisPitchMaxFrequencyHz, ); check_range(min, self.min_frequency_hz, 40.0, 2000.0)?; check_range(max, self.max_frequency_hz, 40.0, 2000.0)?; if self.min_frequency_hz >= self.max_frequency_hz { - return Err(Error::config(min, ConfigProblem::Unordered { other: max })); + return Err(Error::config( + min, + ConfigProblem::Unordered { + value: self.min_frequency_hz, + other: max, + other_value: self.max_frequency_hz, + }, + )); } Ok(()) } diff --git a/src/processor.rs b/src/processor.rs index 83bccf6..5414ae0 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -8,7 +8,7 @@ use crate::events::{ValidatedEvent, ValidatedEvents}; use crate::numeric::rng::RandomStream; use crate::numeric::NumericContext; use crate::resynthesis::{self, Resynthesis}; -use crate::{ControlEvent, Error, PrepareConfig, ProcessorConfig, TimedEvent}; +use crate::{BufferName, ControlEvent, Error, PrepareConfig, ProcessorConfig, TimedEvent}; /// A prepared vocal processor with state, mono input and stereo synthesis. /// @@ -149,7 +149,7 @@ impl Processor { output: &mut [[i16; 2]], events: &[TimedEvent], ) -> Result<(), Error> { - Error::check_length(input.len(), output.len())?; + Error::check_length(BufferName::Output, input.len(), output.len())?; self.process_into(input.len(), events, |processor, index| { output[index] = processor.next(input[index]); }) @@ -175,8 +175,8 @@ impl Processor { right: &mut [i16], events: &[TimedEvent], ) -> Result<(), Error> { - Error::check_length(input.len(), left.len())?; - Error::check_length(input.len(), right.len())?; + Error::check_length(BufferName::Left, input.len(), left.len())?; + Error::check_length(BufferName::Right, input.len(), right.len())?; self.process_into(input.len(), events, |processor, index| { let frame = processor.next(input[index]); left[index] = frame[0]; @@ -257,7 +257,7 @@ impl Processor { /// [`Error::BlockTooLarge`]. If either error occurs, the two channels and /// the drain state do not change. pub fn drain_planar(&mut self, left: &mut [i16], right: &mut [i16]) -> Result { - Error::check_length(left.len(), right.len())?; + Error::check_length(BufferName::Right, left.len(), right.len())?; let count = self.drain_into(left.len(), |index, frame| { left[index] = frame[0]; right[index] = frame[1]; @@ -438,7 +438,7 @@ impl Processor { input: &mut [f32], output: &mut [f32], ) -> Result { - Error::check_length(input.len(), output.len())?; + Error::check_length(BufferName::Output, input.len(), output.len())?; let nyquist = self.preparation.sample_rate.hz() / 2.0; if !max_frequency_hz.is_finite() || max_frequency_hz <= 0.0 || max_frequency_hz > nyquist { return Err(Error::InvalidFrequency { @@ -702,12 +702,16 @@ fn downmix(frame: [i16; 2]) -> i16 { } /// A snapshot of the pitch analysis and the output level that you can copy. -/// -/// Get it with [`Processor::feedback`] or [`Processor::take_feedback`]. The -/// pitch fields describe the tracked input and the correction target. The -/// peak measures the final clipped stereo output. `Default` gives a snapshot -/// with all zeros and no target. It does not read the nominal latency of a -/// prepared processor. +#[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = "", + doc = " Get it with [`Processor::feedback`] or [`Processor::take_feedback`]. The pitch fields describe the tracked input and the correction target. The peak measures the final clipped stereo output. `Default` gives a snapshot with all zeros and no target. It does not read the nominal latency of a prepared processor." +)] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = "", + doc = " Get it with `Tunelet.feedback` or `Tunelet.takeFeedback`. The pitch fields describe the tracked input and the correction target. The peak measures the final clipped stereo output." +)] #[derive(Clone, Copy, Debug, Default, PartialEq)] #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), @@ -724,9 +728,16 @@ pub struct Feedback { /// a change of stereo output. pub resample_ratio: f32, /// The reported input pitch period in samples, with fractional samples. - /// - /// It is zero if the input is unvoiced or outside the reporting bounds of - /// [`crate::PitchConfig`]. + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = "", + doc = " It is zero if the input is unvoiced or outside the reporting bounds of [`crate::PitchConfig`]." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = "", + doc = " It is zero if the input is unvoiced or outside the reporting bounds of `PitchConfig`." + )] pub period_samples: f32, /// The reported input pitch frequency in hertz. /// @@ -746,11 +757,16 @@ pub struct Feedback { /// The pitch class is in the octave nearest to the reported input. In /// other cases, the value is the input pitch as a fractional MIDI note. It /// is not the final pitch of shifted output or harmony output. - /// - /// The value is `None` if [`voiced`](Self::voiced) is `false`, and only - /// then. This occurs if the input is unvoiced or if its frequency is - /// outside the current reporting bounds. A target table that has no - /// selected target does not give `None`. + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = "", + doc = " The value is `None` if [`voiced`](Self::voiced) is `false`, and only then. This occurs if the input is unvoiced or if its frequency is outside the current reporting bounds. A target table that has no selected target does not give `None`." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = "", + doc = " The value is `undefined` if `voiced` is `false`, and only then. This occurs if the input is unvoiced or if its frequency is outside the current reporting bounds. A target table that has no selected target does not give `undefined`." + )] pub target_midi_note: Option, /// This field is `true` if the current pitch estimate is positive and /// inside the current reporting bounds. @@ -759,11 +775,16 @@ pub struct Feedback { /// can stay between detector updates. pub voiced: bool, /// The largest absolute clipped stereo sample, divided by 32768. - /// - /// The peak window starts at construction, at a reset, at a change of - /// stereo output or at a call to [`Processor::take_feedback`]. The value - /// is in 0..=32767/32768. The mono downmix occurs after this measurement. - /// [`Processor::feedback`] does not clear the value. + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = "", + doc = " The peak window starts at construction, at a reset, at a change of stereo output or at a call to [`Processor::take_feedback`]. The value is in 0..=32767/32768. The mono downmix occurs after this measurement. [`Processor::feedback`] does not clear the value." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = "", + doc = " The peak window starts at construction, at a reset, at a change of stereo output or at a call to `Tunelet.takeFeedback`. The value is in 0..=32767/32768. The mono downmix occurs after this measurement. `Tunelet.feedback` does not clear the value." + )] pub peak_level: f32, /// The number of frames processed since construction or the last reset, /// with drain frames included. @@ -771,9 +792,13 @@ pub struct Feedback { /// The count saturates at `u64::MAX`. Drain completion resets it in the /// last drain call. pub processed_frames: u64, - /// The nominal resynthesis latency, as [`Processor::latency_frames`] gives. + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The nominal resynthesis latency, as [`Processor::latency_frames`] gives." + )] #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), + doc = " The nominal resynthesis latency, as `Tunelet.latencyFrames` gives.", serde(serialize_with = "crate::wasm::serialize_frame_count"), tsify(type = "number") )] @@ -782,15 +807,20 @@ pub struct Feedback { /// A snapshot of the voices, the levels and the effect state that you can /// copy. -/// -/// Get it with [`Processor::telemetry`] or [`Processor::take_telemetry`]. The -/// telemetry is for meters and displays. No audio calculation reads it. -/// `Default` gives a snapshot with all zeros. -/// -/// The three peak fields measure a window. The window starts at -/// construction, at a reset, at a change of stereo output or at a call to -/// [`Processor::take_telemetry`]. This window is independent of the peak -/// window of [`Feedback`]. +#[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = "", + doc = " Get it with [`Processor::telemetry`] or [`Processor::take_telemetry`]. The telemetry is for meters and displays. No audio calculation reads it. `Default` gives a snapshot with all zeros.", + doc = "", + doc = " The three peak fields measure a window. The window starts at construction, at a reset, at a change of stereo output or at a call to [`Processor::take_telemetry`]. This window is independent of the peak window of [`Feedback`]." +)] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = "", + doc = " Get it with `Tunelet.telemetry` or `Tunelet.takeTelemetry`. The telemetry is for meters and displays. No audio calculation reads it.", + doc = "", + doc = " The three peak fields measure a window. The window starts at construction, at a reset, at a change of stereo output or at a call to `Tunelet.takeTelemetry`. This window is independent of the peak window of `Feedback`." +)] #[derive(Clone, Copy, Debug, Default, PartialEq)] #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), @@ -799,8 +829,14 @@ pub struct Feedback { tsify(large_number_types_as_bigints) )] pub struct Telemetry { - /// The number of frames processed since construction or the last reset, - /// as [`Feedback::processed_frames`] gives. + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The number of frames processed since construction or the last reset, as [`Feedback::processed_frames`] gives." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The number of frames processed since construction or the last reset, as `Feedback.processedFrames` gives." + )] pub processed_frames: u64, /// The largest absolute input sample in the window, divided by 32768. /// @@ -820,33 +856,54 @@ pub struct Telemetry { /// disabled, the window gets no new values. pub reverb_wet_peak: f32, /// How periodic the tracked input is, in 0..=1. - /// - /// The value is 1 for a signal that repeats exactly at the tracked - /// period. It is 0 for a signal with no relation between cycles and - /// during pitch acquisition. Use it as a confidence score for - /// [`Feedback::voiced`]. The tracker updates the related sums on each - /// frame. + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = "", + doc = " The value is 1 for a signal that repeats exactly at the tracked period. It is 0 for a signal with no relation between cycles and during pitch acquisition. Use it as a confidence score for [`Feedback::voiced`]. The tracker updates the related sums on each frame." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = "", + doc = " The value is 1 for a signal that repeats exactly at the tracked period. It is 0 for a signal with no relation between cycles and during pitch acquisition. Use it as a confidence score for `Feedback.voiced`. The tracker updates the related sums on each frame." + )] pub clarity: f32, /// This field is `true` if the pitch tracker follows a period. It is /// `false` during pitch acquisition. pub tracking: bool, - /// The number of valid entries in [`voice_ratios`](Self::voice_ratios) - /// and [`voice_gains`](Self::voice_gains). - /// - /// The value is 5 in Harmony mode. In Choir mode, it is - /// [`crate::ResynthesisConfig::choir_voices`], in 1..=16. + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The number of valid entries in [`voice_ratios`](Self::voice_ratios) and [`voice_gains`](Self::voice_gains).", + doc = "", + doc = " The value is 5 in Harmony mode. In Choir mode, it is [`crate::ResynthesisConfig::choir_voices`], in 1..=16." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The number of valid entries in `voiceRatios` and `voiceGains`.", + doc = "", + doc = " The value is 5 in Harmony mode. In Choir mode, it is `ResynthesisConfig.choirVoices`, in 1..=16." + )] pub voice_count: u8, /// The pitch ratio of each voice on the last frame, where 1 is the input /// pitch. - /// - /// Entry zero is the lead voice. In Harmony mode, entries 1 to 4 are the - /// harmony voices. In Choir mode, the entries after the lead are the - /// secondary voices. Each ratio includes the correction, the configured - /// pitch shift and the ratio of the voice. The entries after - /// [`voice_count`](Self::voice_count) are zero. + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = "", + doc = " Entry zero is the lead voice. In Harmony mode, entries 1 to 4 are the harmony voices. In Choir mode, the entries after the lead are the secondary voices. Each ratio includes the correction, the configured pitch shift and the ratio of the voice. The entries after [`voice_count`](Self::voice_count) are zero." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = "", + doc = " Entry zero is the lead voice. In Harmony mode, entries 1 to 4 are the harmony voices. In Choir mode, the entries after the lead are the secondary voices. Each ratio includes the correction, the configured pitch shift and the ratio of the voice. The entries after `voiceCount` are zero." + )] pub voice_ratios: [f32; 16], - /// The linear gain of each voice, in the order of - /// [`voice_ratios`](Self::voice_ratios). + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The linear gain of each voice, in the order of [`voice_ratios`](Self::voice_ratios)." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The linear gain of each voice, in the order of `voiceRatios`." + )] /// /// The lead and the choir voices have a gain of 1. The gain of a harmony /// voice includes the MIDI velocity gain, in 0..=3.98095703125. MIDI @@ -868,19 +925,37 @@ pub struct Telemetry { /// -30 dB, it is the gain of +30 dB. Warm updates it every 100 frames. /// The value is 1 while Warm is disabled. pub warm_gain: f32, - /// The length of the Alien loop in frames, as - /// [`crate::AlienConfig::loop_frames`] gives. + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The length of the Alien loop in frames, as [`crate::AlienConfig::loop_frames`] gives." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The length of the Alien loop in frames, as `AlienConfig.loopFrames` gives." + )] pub alien_loop_frames: u32, - /// The current frame in the Alien loop. It is less than - /// [`alien_loop_frames`](Self::alien_loop_frames). + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The current frame in the Alien loop. It is less than [`alien_loop_frames`](Self::alien_loop_frames)." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The current frame in the Alien loop. It is less than `alienLoopFrames`." + )] /// /// The reverse reader is two times this number of frames behind the /// recording position. The value advances also while Alien is disabled. pub alien_phase_frames: u32, /// The wrapping count of formant analyses since construction. - /// - /// The count increases every 441 frames while the formant stage is - /// enabled. Compare two values to find if - /// [`Processor::formant_envelope`] can give a new result. + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = "", + doc = " The count increases every 441 frames while the formant stage is enabled. Compare two values to find if [`Processor::formant_envelope`] can give a new result." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = "", + doc = " The count increases every 441 frames while the formant stage is enabled. Compare two values to find if `Tunelet.formantEnvelope` can give a new result." + )] pub formant_generation: u32, } diff --git a/src/resynthesis.rs b/src/resynthesis.rs index 3833d86..b60fbd9 100644 --- a/src/resynthesis.rs +++ b/src/resynthesis.rs @@ -39,7 +39,7 @@ use crate::numeric::{clamp_i32, ring, NumericContext, HISTORY}; use crate::pitch::tracker::PitchTracker; use crate::pitch::{PitchConfig, PitchEstimate}; use crate::scale::{CorrectionTable, NoteMask}; -use crate::{Error, SampleRate}; +use crate::{ConfigField, Error, SampleRate}; use history::prepare_history; /// The method that resynthesis uses to render its voices. @@ -88,13 +88,25 @@ pub enum MultiVoiceMode { )] pub struct CorrectionConfig { /// Enables the selection of correction targets. The default is `true`. - /// - /// If you disable correction, the ratio moves toward 1.0 with `retune_ms` - /// at the next tracking updates. The ratio does not change to 1.0 - /// immediately. + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = "", + doc = " If you disable correction, the ratio moves toward 1.0 with `retune_ms` at the next tracking updates. The ratio does not change to 1.0 immediately." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = "", + doc = " If you disable correction, the ratio moves toward 1.0 with `retuneMs` at the next tracking updates. The ratio does not change to 1.0 immediately." + )] pub enabled: bool, - /// The configured target pitch classes. The default is - /// [`NoteMask::CHROMATIC`]. + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The configured target pitch classes. The default is [`NoteMask::CHROMATIC`]." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The configured target pitch classes. By default, all 12 pitch classes are enabled." + )] /// /// All boolean masks are valid. MIDI can replace the active table. This /// replacement stays until this mask or `enabled` changes. @@ -127,11 +139,12 @@ impl CorrectionConfig { /// /// # Errors /// - /// Returns [`Error::InvalidConfig`], with the dotted path of the field and - /// the problem, if `retune_ms` is not valid. + /// Returns [`Error::InvalidConfig`] with + /// [`ConfigField::ResynthesisCorrectionRetuneMs`] and the problem if + /// `retune_ms` is not valid. pub fn validate(self) -> Result<(), Error> { check_range( - "resynthesis.correction.retune_ms", + ConfigField::ResynthesisCorrectionRetuneMs, self.retune_ms, 0.0, 400.0, @@ -166,8 +179,14 @@ impl CorrectionConfig { tsify(large_number_types_as_bigints) )] pub struct ResynthesisConfig { - /// The acquisition sensitivity and the reporting bounds. The - /// default is [`PitchConfig::default`]. + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The acquisition sensitivity and the reporting bounds. The default is [`PitchConfig::default`]." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The acquisition sensitivity and the reporting bounds." + )] pub pitch: PitchConfig, /// The target notes and the retune time. The default is enabled /// chromatic correction with a retune time of zero. @@ -181,7 +200,14 @@ pub struct ResynthesisConfig { pub pitch_ratio: f32, /// The vocal-tract changes and aspiration. They are disabled by default. pub formant: FormantConfig, - /// The voice arrangement. The default is [`MultiVoiceMode::Choir`]. + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The voice arrangement. The default is [`MultiVoiceMode::Choir`]." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The voice arrangement. The default is `'choir'`." + )] /// /// Harmony renders the lead voice and a maximum of four harmony voices. pub mode: MultiVoiceMode, @@ -207,15 +233,28 @@ pub struct ResynthesisConfig { /// settings. pub choir_delay: f32, /// The stereo width of the choir, 0..=100%. The default is 100%. - /// - /// The code uses this value only if `stereo_output` enables the voice pan - /// and the choir has more than one voice. + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = "", + doc = " The code uses this value only if `stereo_output` enables the voice pan and the choir has more than one voice." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = "", + doc = " The code uses this value only if `stereoOutput` enables the voice pan and the choir has more than one voice." + )] pub choir_spread_percent: f32, /// Enables a stereo pan for each voice. The default is `false`. - /// - /// This value is independent of the buffer layout of the process method. - /// A change to this value resets some audio histories and the feedback. - /// [`crate::Processor::set_config`] gives the details. + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = "", + doc = " This value is independent of the buffer layout of the process method. A change to this value resets some audio histories and the feedback. [`crate::Processor::set_config`] gives the details." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = "", + doc = " This value is independent of the buffer layout of the process method. A change to this value resets some audio histories and the feedback. `Tunelet.setConfig` gives the details." + )] pub stereo_output: bool, /// The controls for the four harmony voices. The default is MIDI-channel /// allocation. @@ -224,10 +263,16 @@ pub struct ResynthesisConfig { /// while Choir is selected. pub harmony: HarmonyConfig, /// The linear gain of the four harmony voices, 0..=1. The default is 0.5. - /// - /// If `stereo_output` is `true`, the stereo pan gains include this gain. - /// If `stereo_output` is `false`, this gain scales each harmony voice - /// directly. It does not scale the lead voice. + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = "", + doc = " If `stereo_output` is `true`, the stereo pan gains include this gain. If `stereo_output` is `false`, this gain scales each harmony voice directly. It does not scale the lead voice." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = "", + doc = " If `stereoOutput` is `true`, the stereo pan gains include this gain. If `stereoOutput` is `false`, this gain scales each harmony voice directly. It does not scale the lead voice." + )] pub harmony_gain: f32, /// The modulation depth, 0..=24, without a unit. The default is 0 (off). /// @@ -285,26 +330,54 @@ impl ResynthesisConfig { /// /// # Errors /// - /// Returns the first [`Error::InvalidConfig`], with the dotted path of the - /// field and the problem. For an array control in `harmony`, the error - /// identifies the array field, not the index of an element. + /// Returns the first [`Error::InvalidConfig`] with its field and the + /// problem. For an interval array control in `harmony`, `voice` holds + /// `Some(0..=3)` for the rejected slot. pub fn validate(self) -> Result<(), Error> { self.pitch.validate()?; self.correction.validate()?; self.formant.validate()?; self.harmony.validate()?; - check_range("resynthesis.pitch_ratio", self.pitch_ratio, 0.25, 4.0)?; - check_range("resynthesis.choir_detune", self.choir_detune, 10.0, 100.0)?; - check_range("resynthesis.choir_delay", self.choir_delay, 20.0, 200.0)?; - let field = "resynthesis.choir_spread_percent"; - check_range(field, self.choir_spread_percent, 0.0, 100.0)?; - check_range("resynthesis.harmony_gain", self.harmony_gain, 0.0, 1.0)?; - let field = "resynthesis.harmonic_modulation"; - check_range(field, self.harmonic_modulation, 0.0, 24.0)?; - check_range("resynthesis.dry_mix", self.dry_mix, 0.0, 1.0)?; + check_range( + ConfigField::ResynthesisPitchRatio, + self.pitch_ratio, + 0.25, + 4.0, + )?; + check_range( + ConfigField::ResynthesisChoirDetune, + self.choir_detune, + 10.0, + 100.0, + )?; + check_range( + ConfigField::ResynthesisChoirDelay, + self.choir_delay, + 20.0, + 200.0, + )?; + check_range( + ConfigField::ResynthesisChoirSpreadPercent, + self.choir_spread_percent, + 0.0, + 100.0, + )?; + check_range( + ConfigField::ResynthesisHarmonyGain, + self.harmony_gain, + 0.0, + 1.0, + )?; + check_range( + ConfigField::ResynthesisHarmonicModulation, + self.harmonic_modulation, + 0.0, + 24.0, + )?; + check_range(ConfigField::ResynthesisDryMix, self.dry_mix, 0.0, 1.0)?; check_count( - "resynthesis.choir_voices", - i64::from(self.choir_voices), + ConfigField::ResynthesisChoirVoices, + i128::from(self.choir_voices), 1, 16, ) diff --git a/src/scale.rs b/src/scale.rs index 01c4f94..2565fb0 100644 --- a/src/scale.rs +++ b/src/scale.rs @@ -64,7 +64,14 @@ impl PitchClass { } } -/// A scale for [`NoteMask::from_key_scale`]. +#[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " A scale for [`NoteMask::from_key_scale`]." +)] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " A scale preset for pitch-class correction." +)] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), @@ -86,10 +93,16 @@ pub enum CorrectionScale { /// /// A `true` flag enables that pitch class in all octaves. /// -/// The default is [`Self::CHROMATIC`]. All combinations of flags are valid. -/// This includes [`Self::NONE`]. If the mask is empty, the correction ratio -/// moves toward unity with the configured retune half-life. An empty mask -/// does not clear the histories. +#[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The default is [`Self::CHROMATIC`]. All combinations of flags are valid. This includes [`Self::NONE`]." +)] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The default enables all twelve pitch classes. All combinations of flags are valid, also an all-`false` array." +)] +/// If the mask is empty, the correction ratio moves toward unity with the +/// configured retune half-life. An empty mask does not clear the histories. #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), diff --git a/src/wasm.rs b/src/wasm.rs index 15262e2..fc4a295 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -9,7 +9,7 @@ //! wasm-pack can do the two steps in one command. The npm entry point uses //! `loadTunelet()` to initialize these bindings in browsers and in Node.js. //! -//! The exported `Tunelet` class owns a native [`Processor`] and three reusable +//! The exported `Tunelet` class owns a native `Processor` and three reusable //! PCM buffers. JavaScript gives the `Int16Array` input and output buffers. The //! PCM API does not give buffer pointers or long-lived memory views to //! JavaScript. The class copies the input before it writes the output. @@ -21,7 +21,7 @@ //! - 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 +//! `defaultConfig` 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 @@ -38,14 +38,15 @@ //! //! The JavaScript glue can also make temporary views when it copies data. This //! generic binding does not guarantee an AudioWorklet callback that is free of -//! allocation. If you do not need a processor any more, call the generated -//! `free()` method. +//! allocation. If you do not need a processor any more, call `free()`. use crate::{ - Error, Feedback, PrepareConfig, Processor, ProcessorConfig, SampleRate, Telemetry, TimedEvent, + BufferName, ConfigField, ConfigProblem, Error, EventProblem, Feedback, MidiProblem, + PrepareConfig, Processor, ProcessorConfig, SampleRate, Telemetry, TimedEvent, }; use js_sys::{Float32Array, Int16Array}; use serde::{Deserialize, Serialize}; +use std::fmt::Write as _; use tsify::{Ts, Tsify}; use wasm_bindgen::prelude::*; @@ -56,10 +57,232 @@ use wasm_bindgen::prelude::*; /// with equal offsets execute in array order. An empty block accepts no /// events. If there are no events, omit the optional argument. Then the /// binding does not decode an array. -#[derive(Default, Serialize, Deserialize, Tsify)] +#[derive(Default, Serialize, Deserialize)] #[serde(transparent)] pub struct BlockEvents(Vec); +const _: () = { + #[wasm_bindgen] + extern "C" { + #[derive(Clone)] + #[wasm_bindgen(typescript_type = "TimedEvent[]")] + pub type JsTimedEvents; + } + + impl Tsify for BlockEvents { + type JsType = JsTimedEvents; + const DECL: &'static str = ""; + } +}; + +/// The specific kind of configuration failure in `ErrorDetails`. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, Tsify)] +#[serde(rename_all = "camelCase")] +pub enum ConfigProblemKind { + /// The floating-point value is outside `min..=max`. + OutOfRange, + /// The integer value is outside `min..=max`. + IntegerOutOfRange, + /// The number is finite, but it has a fractional part where an integer is required. + NotInteger, + /// The number is `NaN` or infinite. + NotFinite, + /// The value is not strictly less than `other`. + Unordered, +} + +/// The specific kind of timed-event failure in `ErrorDetails`. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, Tsify)] +#[serde(rename_all = "camelCase")] +pub enum EventProblemKind { + /// The zero-based frame offset is outside `0..frames`. + OffsetOutsideBlock, + /// The zero-based frame offset is less than `previous`. + OffsetDecreasing, + /// The configuration payload of the event is not valid. + Config, + /// The MIDI payload of the event is not valid. + Midi, +} + +/// The specific kind of MIDI failure in `ErrorDetails`. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, Tsify)] +#[serde(rename_all = "camelCase")] +pub enum MidiProblemKind { + /// The status byte at index `0` is below `0x80`. + StatusByte, + /// A data byte at `byteIndex` is more than `127`. + DataByte, + /// The zero-based MIDI channel is more than `15`. + Channel, + /// The MIDI note number is more than `127`. + Note, + /// The MIDI velocity is more than `127`. + Velocity, +} + +/// The public TypeScript input type that rejected a malformed JavaScript value. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, Tsify)] +pub enum InputTarget { + /// A `ProcessorConfig` argument. + #[serde(rename = "ProcessorConfig")] + ProcessorConfig, + /// A `TimedEvent[]` argument. + #[serde(rename = "TimedEvent[]")] + TimedEvents, +} + +/// Machine-readable diagnostic fields on `TuneletError.details`. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Tsify)] +#[serde(rename_all = "camelCase", tag = "type")] +pub enum ErrorDetails { + /// The constructor `sampleRate` is not `44100` or `48000`. + UnsupportedSampleRate { + /// The rejected sample rate in hertz. + hz: f64, + }, + /// A frequency argument is not finite or is outside `0 < hz <= maxHz`. + InvalidFrequency { + /// The rejected frequency in hertz. + hz: f64, + /// The inclusive upper limit, half of `sampleRate` in hertz. + #[serde(rename = "maxHz")] + max_hz: f64, + }, + /// A constructor or `ProcessorConfig` control is not valid. + InvalidConfig { + /// The dotted `camelCase` path of the rejected field. + field: ConfigField, + /// The zero-based voice index in `0..=3` for a harmony interval array. + #[serde(skip_serializing_if = "Option::is_none")] + #[tsify(optional)] + voice: Option, + /// The kind of validation failure. + problem: ConfigProblemKind, + /// The rejected numeric value. + value: f64, + /// The inclusive lower bound, when `problem` checks bounds. + #[serde(skip_serializing_if = "Option::is_none")] + #[tsify(optional)] + min: Option, + /// The inclusive upper bound, when `problem` checks bounds. + #[serde(skip_serializing_if = "Option::is_none")] + #[tsify(optional)] + max: Option, + /// The related field whose value `value` must stay below. + #[serde(skip_serializing_if = "Option::is_none")] + #[tsify(optional)] + other: Option, + /// The current value of `other`. + #[serde(rename = "otherValue", skip_serializing_if = "Option::is_none")] + #[tsify(optional)] + other_value: Option, + }, + /// An output buffer length is not equal to the input or the other channel. + BufferLength { + /// The output buffer whose length is not valid. + buffer: BufferName, + /// The required frame or point count. + expected: usize, + /// The actual length of `buffer`. + actual: usize, + }, + /// A block has more frames than `maxBlockFrames`. + BlockTooLarge { + /// The frame count of the rejected block. + frames: usize, + /// The prepared `maxBlockFrames` limit. + max: usize, + }, + /// A timed event in `TimedEvent[]` failed the block preflight check. + InvalidEvent { + /// The zero-based index of the rejected event in `events`. + index: usize, + /// The zero-based frame offset of the rejected event. + offset: usize, + /// The kind of event failure. + problem: EventProblemKind, + /// The frame count of the current block, for `offsetOutsideBlock`. + #[serde(skip_serializing_if = "Option::is_none")] + #[tsify(optional)] + frames: Option, + /// The frame offset of the previous event, for `offsetDecreasing`. + #[serde(skip_serializing_if = "Option::is_none")] + #[tsify(optional)] + previous: Option, + /// The rejected `camelCase` field path, for `config` failures. + #[serde(skip_serializing_if = "Option::is_none")] + #[tsify(optional)] + field: Option, + /// The zero-based voice index in `0..=3`, for harmony array failures. + #[serde(skip_serializing_if = "Option::is_none")] + #[tsify(optional)] + voice: Option, + /// The configuration failure kind, for `config` failures. + #[serde(rename = "configProblem", skip_serializing_if = "Option::is_none")] + #[tsify(optional)] + config_problem: Option, + /// The MIDI failure kind, for `midi` failures. + #[serde(rename = "midiProblem", skip_serializing_if = "Option::is_none")] + #[tsify(optional)] + midi_problem: Option, + /// The byte index in a three-byte MIDI message, when applicable. + #[serde(rename = "byteIndex", skip_serializing_if = "Option::is_none")] + #[tsify(optional)] + byte_index: Option, + /// The rejected configuration or MIDI value, when applicable. + #[serde(skip_serializing_if = "Option::is_none")] + #[tsify(optional)] + value: Option, + /// The inclusive lower bound of the rejected field or MIDI value. + #[serde(skip_serializing_if = "Option::is_none")] + #[tsify(optional)] + min: Option, + /// The inclusive upper bound of the rejected field or MIDI value. + #[serde(skip_serializing_if = "Option::is_none")] + #[tsify(optional)] + max: Option, + /// The related field for an `unordered` configuration failure. + #[serde(skip_serializing_if = "Option::is_none")] + #[tsify(optional)] + other: Option, + /// The value of `other` for an `unordered` configuration failure. + #[serde(rename = "otherValue", skip_serializing_if = "Option::is_none")] + #[tsify(optional)] + other_value: Option, + }, + /// A MIDI message or `MidiEvent` field is out of range. + InvalidMidi { + /// The kind of MIDI failure. + problem: MidiProblemKind, + /// The byte index (`0`, `1` or `2`) for raw three-byte MIDI messages. + #[serde(rename = "byteIndex", skip_serializing_if = "Option::is_none")] + #[tsify(optional)] + byte_index: Option, + /// The rejected byte, channel, note or velocity value. + value: u8, + /// The inclusive lower bound for the byte or field. + min: u8, + /// The inclusive upper bound for the byte or field. + max: u8, + }, + /// A JavaScript argument failed conversion into a public SDK type. + InvalidInput { + /// The target TypeScript type that rejected the input. + target: InputTarget, + }, + /// WebAssembly failed to reserve a required internal buffer. + AllocationFailed, + /// WebAssembly failed to convert a configuration or snapshot object. + SerializationFailed, + /// A call ran before `loadTunelet()` or `initSync()` initialized WebAssembly. + NotInitialized, + /// A method or getter ran on a `Tunelet` instance after `free()`. + Disposed, + /// An initialization call gave a custom Wasm source that did not match. + SourceMismatch, +} + /// Returns a complete, independent default configuration for JavaScript. /// /// Change its fields and give it to `Tunelet` or to `setConfig`. The @@ -69,11 +292,11 @@ pub struct BlockEvents(Vec); /// /// # Errors /// -/// If the conversion to a JavaScript object fails, this function returns a -/// JavaScript `Error`. +/// If the conversion to a JavaScript object fails, this function throws a +/// structured JavaScript `Error`. #[wasm_bindgen(js_name = defaultConfig)] -pub fn default_config() -> Result, JsError> { - Ok(ProcessorConfig::default().into_ts()?) +pub fn default_config() -> Result, JsValue> { + encode_ts(&ProcessorConfig::default()) } /// A stateful PCM processor that JavaScript uses as the `Tunelet` class. @@ -119,7 +342,7 @@ pub struct WasmProcessor { impl WasmProcessor { /// Prepares a processor and its reusable PCM buffers. /// - /// `sample_rate` must be 44100 or 48000. `max_block_frames` must be an + /// `sampleRate` must be 44100 or 48000. `maxBlockFrames` 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 @@ -132,7 +355,7 @@ impl WasmProcessor { /// /// - The rate is not 44100 or 48000. /// - The block limit is not an integer or is out of range. - /// - The configuration object is malformed or a field is missing. + /// - The configuration object is malformed or a field is absent. /// - The configuration is not valid. /// - The reservation of a PCM buffer fails. /// @@ -140,31 +363,29 @@ impl WasmProcessor { /// histories. #[wasm_bindgen(constructor)] pub fn new( - sample_rate: f64, - max_block_frames: f64, + #[wasm_bindgen(js_name = sampleRate)] sample_rate: f64, + #[wasm_bindgen(js_name = maxBlockFrames)] max_block_frames: f64, config: Option>, - ) -> Result { + ) -> Result { // Accept JavaScript numbers without the u32 coercion of wasm-bindgen. // That coercion silently truncates fractions and wraps large values. let rate = match sample_rate { 44100.0 => SampleRate::Hz44100, 48000.0 => SampleRate::Hz48000, - _ => return Err(JsError::new("sampleRate must be 44100 or 48000")), + _ => { + return Err(js_error( + &format!("sampleRate ({sample_rate} Hz) must be 44100 or 48000"), + &ErrorDetails::UnsupportedSampleRate { hz: sample_rate }, + )); + } }; - if !(1.0..=f64::from(u32::MAX)).contains(&max_block_frames) - || max_block_frames.fract() != 0.0 - { - return Err(JsError::new( - "maxBlockFrames must be an integer in 1..=4294967295", - )); - } - let max_block_frames = max_block_frames as usize; - let preparation = PrepareConfig::new(rate, max_block_frames)?; + let max_block_frames = validate_max_block_frames(max_block_frames)?; + let preparation = PrepareConfig::new(rate, max_block_frames).map_err(domain_error)?; let config = match config { - Some(value) => value.to_rust()?, + Some(value) => decode_config(&value)?, None => ProcessorConfig::default(), }; - let processor = Processor::new(preparation, config)?; + let processor = Processor::new(preparation, config).map_err(domain_error)?; Ok(Self { processor, input: pcm_buffer(max_block_frames)?, @@ -209,8 +430,8 @@ impl WasmProcessor { /// # Errors /// /// If the conversion to a JavaScript object fails, this method throws. - pub fn config(&self) -> Result, JsError> { - Ok(self.processor.config().into_ts()?) + pub fn config(&self) -> Result, JsValue> { + encode_ts(&self.processor.config()) } /// Decodes and validates a configuration, then replaces the complete @@ -221,12 +442,12 @@ impl WasmProcessor { /// /// # Errors /// - /// The method throws if an object is not valid or a field is missing. + /// The method throws if an object is not valid or a field is absent. /// 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()?)?; - Ok(()) + pub fn set_config(&mut self, config: Ts) -> Result<(), JsValue> { + let decoded = decode_config(&config)?; + self.processor.set_config(decoded).map_err(domain_error) } /// Processes mono input into left and right `Int16Array` buffers of equal @@ -251,19 +472,23 @@ impl WasmProcessor { left: &Int16Array, right: &Int16Array, events: Option>, - ) -> Result<(), JsError> { + ) -> Result<(), JsValue> { let frames = input.length() as usize; - Error::check_length(frames, left.length() as usize)?; - Error::check_length(frames, right.length() as usize)?; - self.processor.check_block(frames)?; + Error::check_length(BufferName::Left, frames, left.length() as usize) + .map_err(domain_error)?; + Error::check_length(BufferName::Right, frames, right.length() as usize) + .map_err(domain_error)?; + self.processor.check_block(frames).map_err(domain_error)?; let events = decode_events(events)?; input.copy_to(&mut self.input[..frames]); - self.processor.process_planar( - &self.input[..frames], - &mut self.left[..frames], - &mut self.right[..frames], - &events.0, - )?; + self.processor + .process_planar( + &self.input[..frames], + &mut self.left[..frames], + &mut self.right[..frames], + &events.0, + ) + .map_err(domain_error)?; left.copy_from(&self.left[..frames]); right.copy_from(&self.right[..frames]); Ok(()) @@ -284,13 +509,14 @@ impl WasmProcessor { &mut self, audio: &Int16Array, events: Option>, - ) -> Result<(), JsError> { + ) -> Result<(), JsValue> { let frames = audio.length() as usize; - self.processor.check_block(frames)?; + self.processor.check_block(frames).map_err(domain_error)?; let events = decode_events(events)?; audio.copy_to(&mut self.input[..frames]); self.processor - .process_mono_in_place(&mut self.input[..frames], &events.0)?; + .process_mono_in_place(&mut self.input[..frames], &events.0) + .map_err(domain_error)?; audio.copy_from(&self.input[..frames]); Ok(()) } @@ -325,13 +551,15 @@ impl WasmProcessor { /// The method throws if the channel lengths are not equal or if a block is /// larger than `maxBlockFrames`. After an error, both output arrays and the /// drain state do not change. - pub fn drain(&mut self, left: &Int16Array, right: &Int16Array) -> Result { + pub fn drain(&mut self, left: &Int16Array, right: &Int16Array) -> Result { let frames = left.length() as usize; - Error::check_length(frames, right.length() as usize)?; - self.processor.check_block(frames)?; + Error::check_length(BufferName::Right, frames, right.length() as usize) + .map_err(domain_error)?; + self.processor.check_block(frames).map_err(domain_error)?; let count = self .processor - .drain_planar(&mut self.left[..frames], &mut self.right[..frames])?; + .drain_planar(&mut self.left[..frames], &mut self.right[..frames]) + .map_err(domain_error)?; left.copy_from(&self.left[..frames]); right.copy_from(&self.right[..frames]); Ok(count) @@ -348,10 +576,13 @@ impl WasmProcessor { /// If the block is larger than `maxBlockFrames`, this method throws before /// the output or the state changes. #[wasm_bindgen(js_name = drainMono)] - pub fn drain_mono(&mut self, audio: &Int16Array) -> Result { + pub fn drain_mono(&mut self, audio: &Int16Array) -> Result { let frames = audio.length() as usize; - self.processor.check_block(frames)?; - let count = self.processor.drain_mono(&mut self.input[..frames])?; + self.processor.check_block(frames).map_err(domain_error)?; + let count = self + .processor + .drain_mono(&mut self.input[..frames]) + .map_err(domain_error)?; audio.copy_from(&self.input[..frames]); Ok(count) } @@ -372,8 +603,8 @@ impl WasmProcessor { /// # Errors /// /// If the conversion to a JavaScript object fails, this method throws. - pub fn feedback(&self) -> Result, JsError> { - Ok(self.processor.feedback().into_ts()?) + pub fn feedback(&self) -> Result, JsValue> { + encode_ts(&self.processor.feedback()) } /// Returns the feedback and clears only the stereo peak window. @@ -386,8 +617,8 @@ impl WasmProcessor { /// method clears the peak only after it successfully makes a feedback /// object. #[wasm_bindgen(js_name = takeFeedback)] - pub fn take_feedback(&mut self) -> Result, JsError> { - let feedback = self.processor.feedback().into_ts()?; + pub fn take_feedback(&mut self) -> Result, JsValue> { + let feedback = encode_ts(&self.processor.feedback())?; self.processor.take_feedback(); Ok(feedback) } @@ -402,8 +633,8 @@ impl WasmProcessor { /// # Errors /// /// If the conversion to a JavaScript object fails, this method throws. - pub fn telemetry(&self) -> Result, JsError> { - Ok(self.processor.telemetry().into_ts()?) + pub fn telemetry(&self) -> Result, JsValue> { + encode_ts(&self.processor.telemetry()) } /// Returns the telemetry and clears only its three peak windows. @@ -416,8 +647,8 @@ impl WasmProcessor { /// method clears the peaks only after it successfully makes a telemetry /// object. #[wasm_bindgen(js_name = takeTelemetry)] - pub fn take_telemetry(&mut self) -> Result, JsError> { - let telemetry = self.processor.telemetry().into_ts()?; + pub fn take_telemetry(&mut self) -> Result, JsValue> { + let telemetry = encode_ts(&self.processor.telemetry())?; self.processor.take_telemetry(); Ok(telemetry) } @@ -450,18 +681,20 @@ impl WasmProcessor { #[wasm_bindgen(js_name = formantEnvelope)] pub fn formant_envelope( &mut self, - max_frequency_hz: f32, + #[wasm_bindgen(js_name = maxFrequencyHz)] max_frequency_hz: f32, input: &Float32Array, output: &Float32Array, - ) -> Result { + ) -> Result { let points = input.length() as usize; // Check before the buffers become longer for a call that cannot succeed. - Error::check_length(points, output.length() as usize)?; + Error::check_length(BufferName::Output, points, output.length() as usize) + .map_err(domain_error)?; let analysis = envelope_buffer(&mut self.envelope_input, points)?; let synthesis = envelope_buffer(&mut self.envelope_output, points)?; let valid = self .processor - .formant_envelope(max_frequency_hz, analysis, synthesis)?; + .formant_envelope(max_frequency_hz, analysis, synthesis) + .map_err(domain_error)?; input.copy_from(analysis); output.copy_from(synthesis); Ok(valid) @@ -477,15 +710,440 @@ impl WasmProcessor { } } +/// Validates the JavaScript `maxBlockFrames` number before `usize` conversion. +fn validate_max_block_frames(value: f64) -> Result { + let field = ConfigField::PrepareMaxBlockFrames; + let max = f64::from(u32::MAX); + if !value.is_finite() { + return Err(js_error( + &format!( + "invalid config: {} ({value}) must be finite", + field.camel_case() + ), + &ErrorDetails::InvalidConfig { + field, + voice: None, + problem: ConfigProblemKind::NotFinite, + value, + min: Some(1.0), + max: Some(max), + other: None, + other_value: None, + }, + )); + } + if value.fract() != 0.0 { + return Err(js_error( + &format!( + "invalid config: {} ({value}) must be an integer in 1..={}", + field.camel_case(), + u32::MAX + ), + &ErrorDetails::InvalidConfig { + field, + voice: None, + problem: ConfigProblemKind::NotInteger, + value, + min: Some(1.0), + max: Some(max), + other: None, + other_value: None, + }, + )); + } + if !(1.0..=max).contains(&value) { + return Err(js_error( + &format!( + "invalid config: {} ({value}) must be in 1..={}", + field.camel_case(), + u32::MAX + ), + &ErrorDetails::InvalidConfig { + field, + voice: None, + problem: ConfigProblemKind::IntegerOutOfRange, + value, + min: Some(1.0), + max: Some(max), + other: None, + other_value: None, + }, + )); + } + Ok(value as usize) +} + +/// Converts a Rust `f32` value to a JavaScript `f64` number without binary +/// conversion artifacts on decimal literals. +fn f32_to_f64(value: f32) -> f64 { + if value.is_finite() { + value.to_string().parse::().unwrap_or(f64::from(value)) + } else { + f64::from(value) + } +} + +/// Unpacked `camelCase` text and `ErrorDetails` fields for a `ConfigProblem`. +struct UnpackedConfigProblem { + reason: String, + kind: ConfigProblemKind, + value: f64, + min: Option, + max: Option, + other: Option, + other_value: Option, +} + +/// Unpacks a `ConfigProblem` into `camelCase` message text and `ErrorDetails` +/// components. +fn unpack_config_problem(problem: ConfigProblem) -> UnpackedConfigProblem { + match problem { + ConfigProblem::OutOfRange { value, min, max } => UnpackedConfigProblem { + reason: format!("({value}) must be in {min}..={max}"), + kind: ConfigProblemKind::OutOfRange, + value: f32_to_f64(value), + min: Some(f32_to_f64(min)), + max: Some(f32_to_f64(max)), + other: None, + other_value: None, + }, + ConfigProblem::IntegerOutOfRange { value, min, max } => UnpackedConfigProblem { + reason: format!("({value}) must be in {min}..={max}"), + kind: ConfigProblemKind::IntegerOutOfRange, + value: value as f64, + min: Some(min as f64), + max: Some(max as f64), + other: None, + other_value: None, + }, + ConfigProblem::NotFinite { value } => UnpackedConfigProblem { + reason: format!("({value}) must be finite"), + kind: ConfigProblemKind::NotFinite, + value: f32_to_f64(value), + min: None, + max: None, + other: None, + other_value: None, + }, + ConfigProblem::Unordered { + value, + other, + other_value, + } => UnpackedConfigProblem { + reason: format!( + "({value}) must be below {} ({other_value})", + other.camel_case() + ), + kind: ConfigProblemKind::Unordered, + value: f32_to_f64(value), + min: None, + max: None, + other: Some(other), + other_value: Some(f32_to_f64(other_value)), + }, + } +} + +/// Unpacked `ErrorDetails` fields for a `MidiProblem`. +struct UnpackedMidiProblem { + kind: MidiProblemKind, + byte_index: Option, + value: u8, + min: u8, + max: u8, +} + +/// Unpacks a `MidiProblem` into its kind, optional byte index, value and bounds. +const fn unpack_midi_problem(problem: MidiProblem) -> UnpackedMidiProblem { + match problem { + MidiProblem::StatusByte { byte } => UnpackedMidiProblem { + kind: MidiProblemKind::StatusByte, + byte_index: Some(0), + value: byte, + min: 0x80, + max: 0xff, + }, + MidiProblem::DataByte { index, byte } => UnpackedMidiProblem { + kind: MidiProblemKind::DataByte, + byte_index: Some(index), + value: byte, + min: 0, + max: 127, + }, + MidiProblem::Channel { channel } => UnpackedMidiProblem { + kind: MidiProblemKind::Channel, + byte_index: None, + value: channel, + min: 0, + max: 15, + }, + MidiProblem::Note { note } => UnpackedMidiProblem { + kind: MidiProblemKind::Note, + byte_index: None, + value: note, + min: 0, + max: 127, + }, + MidiProblem::Velocity { velocity } => UnpackedMidiProblem { + kind: MidiProblemKind::Velocity, + byte_index: None, + value: velocity, + min: 0, + max: 127, + }, + } +} + +/// Formats a `ConfigField` path with an optional `[voice]` suffix in `camelCase`. +fn format_camel_target(field: ConfigField, voice: Option) -> String { + let mut target = String::from(field.camel_case()); + if let Some(index) = voice { + let _ = write!(target, "[{index}]"); + } + target +} + +/// Converts a native `Error` into a JavaScript `Error` with `camelCase` text +/// and `ErrorDetails`. +fn domain_error(error: Error) -> JsValue { + match error { + Error::UnsupportedSampleRate { hz } => js_error( + &format!("sampleRate ({hz} Hz) must be 44100 or 48000"), + &ErrorDetails::UnsupportedSampleRate { hz: f64::from(hz) }, + ), + Error::InvalidFrequency { hz, max_hz } => js_error( + &format!("maxFrequencyHz ({hz} Hz) must be finite and in 0 < hz <= {max_hz}"), + &ErrorDetails::InvalidFrequency { + hz: f32_to_f64(hz), + max_hz: f32_to_f64(max_hz), + }, + ), + Error::InvalidConfig { + field, + voice, + problem, + } => { + let target = format_camel_target(field, voice); + let unpacked = unpack_config_problem(problem); + js_error( + &format!("invalid config: {target} {}", unpacked.reason), + &ErrorDetails::InvalidConfig { + field, + voice, + problem: unpacked.kind, + value: unpacked.value, + min: unpacked.min, + max: unpacked.max, + other: unpacked.other, + other_value: unpacked.other_value, + }, + ) + } + Error::BufferLength { + buffer, + expected, + actual, + } => js_error( + &format!("{buffer} buffer length is {actual}, expected {expected}"), + &ErrorDetails::BufferLength { + buffer, + expected, + actual, + }, + ), + Error::BlockTooLarge { frames, max } => js_error( + &format!("block of {frames} frames exceeds maxBlockFrames ({max})"), + &ErrorDetails::BlockTooLarge { frames, max }, + ), + Error::InvalidEvent { + index, + offset, + problem, + } => match problem { + EventProblem::OffsetOutsideBlock { offset, frames } => js_error( + &format!("event {index}: offset {offset} is outside the block of {frames} frames"), + &ErrorDetails::InvalidEvent { + index, + offset, + problem: EventProblemKind::OffsetOutsideBlock, + frames: Some(frames), + previous: None, + field: None, + voice: None, + config_problem: None, + midi_problem: None, + byte_index: None, + value: None, + min: None, + max: None, + other: None, + other_value: None, + }, + ), + EventProblem::OffsetDecreasing { offset, previous } => js_error( + &format!("event {index}: offset {offset} is below previous offset {previous}"), + &ErrorDetails::InvalidEvent { + index, + offset, + problem: EventProblemKind::OffsetDecreasing, + frames: None, + previous: Some(previous), + field: None, + voice: None, + config_problem: None, + midi_problem: None, + byte_index: None, + value: None, + min: None, + max: None, + other: None, + other_value: None, + }, + ), + EventProblem::Config { + field, + voice, + problem, + } => { + let target = format_camel_target(field, voice); + let unpacked = unpack_config_problem(problem); + js_error( + &format!( + "event {index} at offset {offset}: {target} {}", + unpacked.reason + ), + &ErrorDetails::InvalidEvent { + index, + offset, + problem: EventProblemKind::Config, + frames: None, + previous: None, + field: Some(field), + voice, + config_problem: Some(unpacked.kind), + midi_problem: None, + byte_index: None, + value: Some(unpacked.value), + min: unpacked.min, + max: unpacked.max, + other: unpacked.other, + other_value: unpacked.other_value, + }, + ) + } + EventProblem::Midi { problem } => { + let unpacked = unpack_midi_problem(problem); + js_error( + &format!("event {index} at offset {offset}: {problem}"), + &ErrorDetails::InvalidEvent { + index, + offset, + problem: EventProblemKind::Midi, + frames: None, + previous: None, + field: None, + voice: None, + config_problem: None, + midi_problem: Some(unpacked.kind), + byte_index: unpacked.byte_index, + value: Some(f64::from(unpacked.value)), + min: Some(f64::from(unpacked.min)), + max: Some(f64::from(unpacked.max)), + other: None, + other_value: None, + }, + ) + } + }, + Error::InvalidMidi { problem } => { + let unpacked = unpack_midi_problem(problem); + js_error( + &problem.to_string(), + &ErrorDetails::InvalidMidi { + problem: unpacked.kind, + byte_index: unpacked.byte_index, + value: unpacked.value, + min: unpacked.min, + max: unpacked.max, + }, + ) + } + } +} + +/// Removes any Rust module path prefixes from a serde error string. +fn sanitize_serde_message(raw: &str) -> String { + let mut text = raw.replace("tunelet::wasm::BlockEvents", "TimedEvent[]"); + text = text.replace("BlockEvents", "TimedEvent[]"); + while let Some(start) = text.find("tunelet::") { + let rest = &text[start + "tunelet::".len()..]; + let mut offset = 0; + while let Some(sep) = rest[offset..].find("::") { + let segment = &rest[offset..offset + sep]; + if segment + .chars() + .all(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '_') + { + offset += sep + 2; + } else { + break; + } + } + text.replace_range(start..start + "tunelet::".len() + offset, ""); + } + text +} + +/// Builds a JavaScript `Error` with an attached `details` property. +fn js_error(message: &str, details: &ErrorDetails) -> JsValue { + let error = js_sys::Error::new(message); + if let Ok(details_js) = details.into_js() { + let _ = js_sys::Reflect::set(error.as_ref(), &JsValue::from_str("details"), &details_js); + } + error.into() +} + +/// Converts a Rust `Tsify` value into a JavaScript object or throws a +/// structured error. +fn encode_ts(value: &T) -> Result, JsValue> { + value.into_ts().map_err(|err| { + js_error( + &sanitize_serde_message(&err.to_string()), + &ErrorDetails::SerializationFailed, + ) + }) +} + +/// Decodes a `ProcessorConfig` from JavaScript without Rust path leaks. +fn decode_config(config: &Ts) -> Result { + ProcessorConfig::from_js(config.js_value()).map_err(|err| { + let reason = sanitize_serde_message(&err.to_string()); + js_error( + &format!("invalid ProcessorConfig: {reason}"), + &ErrorDetails::InvalidInput { + target: InputTarget::ProcessorConfig, + }, + ) + }) +} + /// Decodes the optional block controls before the audio state changes. /// /// If there is no value, the result is an empty `Vec`, and no allocation /// occurs. If the caller gives an array, the decode can allocate storage. -fn decode_events(events: Option>) -> Result { - Ok(match events { - Some(value) => value.to_rust()?, - None => BlockEvents::default(), - }) +fn decode_events(events: Option>) -> Result { + match events { + Some(value) => BlockEvents::from_js(value.js_value()).map_err(|err| { + let reason = sanitize_serde_message(&err.to_string()); + js_error( + &format!("invalid TimedEvent[]: {reason}"), + &ErrorDetails::InvalidInput { + target: InputTarget::TimedEvents, + }, + ) + }), + None => Ok(BlockEvents::default()), + } } /// Returns the first `points` entries of a reusable envelope buffer. If the @@ -493,9 +1151,16 @@ fn decode_events(events: Option>) -> Result, points: usize) -> Result<&mut [f32], JsError> { +fn envelope_buffer(buffer: &mut Vec, points: usize) -> Result<&mut [f32], JsValue> { if buffer.len() < points { - buffer.try_reserve_exact(points - buffer.len())?; + buffer + .try_reserve_exact(points - buffer.len()) + .map_err(|_| { + js_error( + "failed to reserve formant envelope buffer", + &ErrorDetails::AllocationFailed, + ) + })?; buffer.resize(points, 0.0); } Ok(&mut buffer[..points]) @@ -505,9 +1170,14 @@ fn envelope_buffer(buffer: &mut Vec, points: usize) -> Result<&mut [f32], J /// /// If the capacity overflows or the allocation fails, this function returns a /// JavaScript error. It does not panic. -fn pcm_buffer(frames: usize) -> Result, JsError> { +fn pcm_buffer(frames: usize) -> Result, JsValue> { let mut buffer = Vec::new(); - buffer.try_reserve_exact(frames)?; + buffer.try_reserve_exact(frames).map_err(|_| { + js_error( + "failed to reserve PCM buffer", + &ErrorDetails::AllocationFailed, + ) + })?; buffer.resize(frames, 0); Ok(buffer) }