From b596c25275a48975ec8c178f23ce1bcdbe97a0e1 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Sat, 21 Nov 2026 01:56:38 +0000 Subject: [PATCH 1/4] feat(error)!: add values, indices, MIDI causes and buffer names - Store the rejected value in the range and finiteness errors. - Add an exact size problem for the zero block limit. - Store both pitch bounds in the unordered frequency error. - Add the voice index to the harmony interval errors. - Store the offsets and the frame count in the event errors. - Add MidiProblem for invalid MIDI bytes and fields. - Carry MidiProblem in the MIDI errors and event errors. - Add the buffer name to the buffer length checks. --- src/config.rs | 7 +- src/error.rs | 251 +++++++++++++++++++++++++++++++++++++++------ src/events.rs | 26 +++-- src/harmony.rs | 14 +-- src/lib.rs | 2 +- src/midi.rs | 43 ++++++-- src/pitch.rs | 9 +- src/processor.rs | 10 +- src/resynthesis.rs | 4 +- src/wasm.rs | 8 +- 10 files changed, 299 insertions(+), 75 deletions(-) diff --git a/src/config.rs b/src/config.rs index 75bcd82..95a547e 100644 --- a/src/config.rs +++ b/src/config.rs @@ -106,9 +106,10 @@ impl PrepareConfig { 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, + ConfigProblem::SizeOutOfRange { + value: max_block_frames, + min: 1, + max: usize::MAX, }, ) })?; diff --git a/src/error.rs b/src/error.rs index b971968..edf52ab 100644 --- a/src/error.rs +++ b/src/error.rs @@ -25,16 +25,22 @@ pub enum Error { /// /// `field` is the dotted path of the field from the root configuration, /// for example `"resynthesis.choir_detune"`, `"reverb.mix"` or - /// `"prepare.max_block_frames"`. + /// `"prepare.max_block_frames"`. For an array control, `index` gives the + /// zero-based element index. InvalidConfig { /// The dotted path of the field from the root configuration. field: &'static str, + /// The zero-based element index, if the field is an array. + index: 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 name of the mismatched buffer (`"output"`, `"left"` or + /// `"right"`). + buffer: &'static str, /// 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. @@ -57,13 +63,10 @@ pub enum Error { 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 problem with the MIDI bytes or fields. + problem: MidiProblem, + }, } /// The problem with a configuration field. @@ -72,17 +75,66 @@ pub enum Error { pub enum ConfigProblem { /// The value is outside `min..=max`. OutOfRange { + /// The rejected value. + value: f64, /// The lowest valid value. min: f64, /// The highest valid value. max: f64, }, + /// The size is outside `min..=max`. + SizeOutOfRange { + /// The rejected size. + value: usize, + /// The lowest valid size. + min: usize, + /// The highest valid size. + max: usize, + }, /// The value is NaN or infinite. - NotFinite, + NotFinite { + /// The rejected value. + value: f64, + }, /// The value must be below the value of the field `other`. Unordered { + /// The rejected value of the field. + value: f32, /// The dotted path of the field that the value must stay below. other: &'static str, + /// The value of `other`. + other_value: f32, + }, +} + +/// The problem with raw MIDI bytes or typed MIDI fields. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum MidiProblem { + /// The status byte is below `0x80`. + StatusByte { + /// The rejected status byte. + byte: u8, + }, + /// A data byte is above 127. + DataByte { + /// The rejected data byte. + byte: u8, + }, + /// The zero-based MIDI channel is above 15. + Channel { + /// The rejected channel number. + channel: u8, + }, + /// The MIDI note number is above 127. + Note { + /// The rejected note number. + note: u8, + }, + /// The MIDI velocity is above 127. + Velocity { + /// The rejected velocity. + velocity: u8, }, } @@ -98,37 +150,83 @@ 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. + 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. + offset: usize, + /// The zero-based frame offset of the previous event. + 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 zero-based element index, if the field is an array. + index: Option, /// The problem with the field. problem: ConfigProblem, }, /// The event has a MIDI message that is not valid. - Midi, + Midi { + /// The problem with the MIDI message. + 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 } + Self::InvalidConfig { + field, + index: None, + problem, + } + } + + /// Returns an `InvalidConfig` error for one element of an array field. + pub(crate) fn config_element( + field: &'static str, + index: usize, + problem: ConfigProblem, + ) -> Self { + Self::InvalidConfig { + field, + index: Some(index), + problem, + } + } + + /// Returns an `InvalidMidi` error with the specific MIDI problem. + pub(crate) fn midi(problem: MidiProblem) -> Self { + Self::InvalidMidi { 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. The mono calls have only + /// one buffer. + pub(crate) fn check_length( + buffer: &'static str, + expected: usize, + actual: usize, + ) -> Result<(), Self> { if expected == actual { Ok(()) } else { - Err(Self::BufferLength { expected, actual }) + Err(Self::BufferLength { + buffer, + expected, + actual, + }) } } } @@ -144,11 +242,19 @@ pub(crate) fn check_range( max: f32, ) -> Result<(), Error> { if !value.is_finite() { - return Err(Error::config(field, ConfigProblem::NotFinite)); + return Err(Error::config( + field, + ConfigProblem::NotFinite { + value: f64::from(value), + }, + )); } if !(min..=max).contains(&value) { - let (min, max) = (f64::from(min), f64::from(max)); - return Err(Error::config(field, ConfigProblem::OutOfRange { min, max })); + let (value, min, max) = (f64::from(value), f64::from(min), f64::from(max)); + return Err(Error::config( + field, + ConfigProblem::OutOfRange { value, min, max }, + )); } Ok(()) } @@ -161,8 +267,30 @@ pub(crate) fn check_count( max: i64, ) -> 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 })); + let (value, min, max) = (value as f64, min as f64, max as f64); + return Err(Error::config( + field, + ConfigProblem::OutOfRange { value, min, max }, + )); + } + Ok(()) +} + +/// Checks one integer element of an array control against `min..=max`. +pub(crate) fn check_indexed_count( + field: &'static str, + index: usize, + value: i64, + min: i64, + max: i64, +) -> Result<(), Error> { + if !(min..=max).contains(&value) { + let (value, min, max) = (value as f64, min as f64, max as f64); + return Err(Error::config_element( + field, + index, + ConfigProblem::OutOfRange { value, min, max }, + )); } Ok(()) } @@ -170,9 +298,35 @@ pub(crate) fn check_count( 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, "is {value}, must be in {min}..={max}") + } + Self::SizeOutOfRange { value, min, max } => { + write!(f, "is {value}, must be in {min}..={max}") + } + Self::NotFinite { value } => write!(f, "is {value}, must be finite"), + Self::Unordered { + value, + other, + other_value, + } => write!(f, "is {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} ({byte}) must be in 0x80..=0xff" + ) + } + Self::DataByte { byte } => write!(f, "MIDI data byte {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 +334,26 @@ 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 the previous event's offset {previous}" + ) + } + Self::Config { + field, + index: Some(index), + problem, + } => write!(f, "{field}[{index}] {problem}"), + Self::Config { + field, + index: None, + problem, + } => write!(f, "{field} {problem}"), + Self::Midi { problem } => write!(f, "{problem}"), } } } @@ -198,11 +368,26 @@ impl fmt::Display for Error { "frequency {hz} Hz must be finite and in 0 < hz <= {max_hz}" ) } - Self::InvalidConfig { field, problem } => { + Self::InvalidConfig { + field, + index: Some(index), + problem, + } => { + write!(f, "invalid config: {field}[{index}] {problem}") + } + Self::InvalidConfig { + field, + index: None, + problem, + } => { write!(f, "invalid config: {field} {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!( @@ -211,7 +396,7 @@ impl fmt::Display for Error { ) } Self::InvalidEvent { index, problem } => write!(f, "event {index}: {problem}"), - Self::InvalidMidi => f.write_str("MIDI message is not valid"), + Self::InvalidMidi { problem } => write!(f, "{problem}"), } } } diff --git a/src/events.rs b/src/events.rs index e1c975c..097fc69 100644 --- a/src/events.rs +++ b/src/events.rs @@ -143,23 +143,31 @@ 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, + index, + problem, + }) => Some(EventProblem::Config { + field, + index, + problem, + }), + Err(Error::InvalidMidi { problem }) => Some(EventProblem::Midi { problem }), + Err(_) => None, } }; if let Some(problem) = problem { return Err(Error::InvalidEvent { index, problem }); } - previous = event.offset; + previous = offset; } Ok(Self { remaining: events }) } diff --git a/src/harmony.rs b/src/harmony.rs index 67b7111..a034559 100644 --- a/src/harmony.rs +++ b/src/harmony.rs @@ -6,7 +6,7 @@ mod chords; -use crate::error::{check_count, check_range}; +use crate::error::{check_count, check_indexed_count, check_range}; use crate::midi::{note_period, velocity_gain, MidiEvent}; use crate::numeric::fixed::{Q12, Q14, Q6}; use crate::scale::PitchClass; @@ -367,16 +367,16 @@ 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. + /// and the problem. For an interval array control, `index` gives the + /// zero-based voice index `0..=3`. pub fn validate(self) -> Result<(), Error> { - for interval in self.chromatic_intervals { + for (index, interval) in self.chromatic_intervals.into_iter().enumerate() { let field = "resynthesis.harmony.chromatic_intervals"; - check_count(field, i64::from(interval), -24, 24)?; + check_indexed_count(field, index, i64::from(interval), -24, 24)?; } - for interval in self.diatonic_intervals { + for (index, interval) in self.diatonic_intervals.into_iter().enumerate() { let field = "resynthesis.harmony.diatonic_intervals"; - check_count(field, i64::from(interval), -14, 14)?; + check_indexed_count(field, index, i64::from(interval), -14, 14)?; } let field = "resynthesis.harmony.voices"; check_count(field, i64::from(self.voices), 0, HARMONY_VOICES as i64)?; diff --git a/src/lib.rs b/src/lib.rs index 0e29119..a1ee222 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::{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..8c3f693 100644 --- a/src/midi.rs +++ b/src/midi.rs @@ -1,7 +1,7 @@ //! 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. /// @@ -66,8 +66,14 @@ impl MidiEvent { /// Returns [`Error::InvalidMidi`] if the status is below `0x80` or 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::midi(MidiProblem::StatusByte { byte: bytes[0] })); + } + if bytes[1] > 127 { + return Err(Error::midi(MidiProblem::DataByte { byte: bytes[1] })); + } + if bytes[2] > 127 { + return Err(Error::midi(MidiProblem::DataByte { byte: bytes[2] })); } let channel = bytes[0] & 15; Ok(match bytes[0] & 0xf0 { @@ -89,20 +95,37 @@ 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 the [`MidiProblem`] 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. 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::midi(MidiProblem::Channel { channel })); + } + if note > 127 { + return Err(Error::midi(MidiProblem::Note { note })); + } + if velocity > 127 { + return Err(Error::midi(MidiProblem::Velocity { velocity })); + } + Ok(()) + } + Self::NoteOff { channel, note } => { + if channel > 15 { + return Err(Error::midi(MidiProblem::Channel { channel })); + } + if note > 127 { + return Err(Error::midi(MidiProblem::Note { note })); + } + Ok(()) } - _ => Ok(()), + Self::AllNotesOff => Ok(()), } } } diff --git a/src/pitch.rs b/src/pitch.rs index 6b682ca..4f2a276 100644 --- a/src/pitch.rs +++ b/src/pitch.rs @@ -87,7 +87,14 @@ impl PitchConfig { 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 cc910f4..5cc33bc 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -149,7 +149,7 @@ impl Processor { output: &mut [[i16; 2]], events: &[TimedEvent], ) -> Result<(), Error> { - Error::check_length(input.len(), output.len())?; + Error::check_length("output", input.len(), output.len())?; self.process_into(input, events, |index, frame| output[index] = frame) } @@ -173,8 +173,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("left", input.len(), left.len())?; + Error::check_length("right", input.len(), right.len())?; self.process_into(input, events, |index, frame| { left[index] = frame[0]; right[index] = frame[1]; @@ -260,7 +260,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("right", left.len(), right.len())?; let count = self.drain_into(left.len(), |index, frame| { left[index] = frame[0]; right[index] = frame[1]; @@ -441,7 +441,7 @@ impl Processor { input: &mut [f32], output: &mut [f32], ) -> Result { - Error::check_length(input.len(), output.len())?; + Error::check_length("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 { diff --git a/src/resynthesis.rs b/src/resynthesis.rs index 34e98fa..22a0b6b 100644 --- a/src/resynthesis.rs +++ b/src/resynthesis.rs @@ -286,8 +286,8 @@ 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. + /// field and the problem. For an interval array control in `harmony`, + /// `index` gives the zero-based voice index `0..=3`. pub fn validate(self) -> Result<(), Error> { self.pitch.validate()?; self.correction.validate()?; diff --git a/src/wasm.rs b/src/wasm.rs index c9cec08..ccff598 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -252,8 +252,8 @@ impl WasmProcessor { events: Option>, ) -> Result<(), JsError> { let frames = input.length() as usize; - Error::check_length(frames, left.length() as usize)?; - Error::check_length(frames, right.length() as usize)?; + Error::check_length("left", frames, left.length() as usize)?; + Error::check_length("right", frames, right.length() as usize)?; self.check_frames(frames)?; let events = decode_events(events)?; input.copy_to(&mut self.input[..frames]); @@ -326,7 +326,7 @@ impl WasmProcessor { /// drain state do not change. pub fn drain(&mut self, left: &Int16Array, right: &Int16Array) -> Result { let frames = left.length() as usize; - Error::check_length(frames, right.length() as usize)?; + Error::check_length("right", frames, right.length() as usize)?; self.check_frames(frames)?; let count = self .processor @@ -454,7 +454,7 @@ impl WasmProcessor { ) -> 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("output", points, output.length() as usize)?; let analysis = envelope_buffer(&mut self.envelope_input, points)?; let synthesis = envelope_buffer(&mut self.envelope_output, points)?; let valid = self From 76640542240229d4bdd0a469d643906c9dbb450d Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Sat, 21 Nov 2026 01:56:42 +0000 Subject: [PATCH 2/4] fix(wasm): format JS error paths and clean TypeScript docs - Include the rejected rate and block limit in constructor errors. - Format dotted configuration paths as camelCase in JavaScript errors. - Replace internal Rust type paths with public TypeScript names. - Emit clean camelCase TSDoc without raw rustdoc links. --- src/config.rs | 24 +++++- src/effects/punch.rs | 12 ++- src/effects/reverb.rs | 20 ++++- src/events.rs | 22 +++-- src/harmony.rs | 102 +++++++++++++++++++---- src/midi.rs | 29 +++++-- src/pitch.rs | 18 +++- src/processor.rs | 186 ++++++++++++++++++++++++++++++++++-------- src/resynthesis.rs | 69 ++++++++++++++-- src/scale.rs | 22 ++++- src/wasm.rs | 183 ++++++++++++++++++++++++++++++++--------- 11 files changed, 565 insertions(+), 122 deletions(-) diff --git a/src/config.rs b/src/config.rs index 95a547e..f522c74 100644 --- a/src/config.rs +++ b/src/config.rs @@ -127,9 +127,18 @@ 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", + doc = " [`crate::ControlEvent::Configure`]. The validation examines all fields", + doc = " before a change has an effect. This includes the fields of disabled stages." +)] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " Change a copy, then apply it with `setConfig` or a `\"configure\"`", + doc = " control event. The validation examines all fields before a change has", + doc = " an effect. This includes the fields of disabled stages." +)] #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] #[cfg_attr( @@ -150,7 +159,14 @@ pub struct ProcessorConfig { /// 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 = " The default is [`ResynthesisConfig::default`]." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " See `ResynthesisConfig` for the defaults." + )] pub resynthesis: ResynthesisConfig, /// The reverse-loop effect after resynthesis. /// diff --git a/src/effects/punch.rs b/src/effects/punch.rs index 867dc09..063701a 100644 --- a/src/effects/punch.rs +++ b/src/effects/punch.rs @@ -41,8 +41,16 @@ 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`. + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " follower: 5000 ms at 0, 250 ms at 0.5 and 1 ms at 1. The attack uses", + doc = " `attack_ms`." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " follower: 5000 ms at 0, 250 ms at 0.5 and 1 ms at 1. The attack uses", + doc = " `attackMs`." + )] pub impact: f32, /// The output ceiling of the saturation in dBFS, -96..=0. /// diff --git a/src/effects/reverb.rs b/src/effects/reverb.rs index fe60cd4..406cebc 100644 --- a/src/effects/reverb.rs +++ b/src/effects/reverb.rs @@ -5,7 +5,14 @@ use crate::filter::{Biquad, Design}; use crate::numeric::fixed::{Fixed, Q14}; use crate::{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,15 @@ 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", + doc = " [`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. /// diff --git a/src/events.rs b/src/events.rs index 097fc69..d1aa16c 100644 --- a/src/events.rs +++ b/src/events.rs @@ -10,12 +10,22 @@ 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 = " Give controls to a process call as [`TimedEvent`] values. The call borrows", + doc = " the slice only for that call. There is no heap allocation and no deferred", + doc = " queue. A stage event replaces all settings of that stage. To change one", + doc = " field, start from the current configuration of the processor.", + doc = " Configuration changes have the same effects on state as", + doc = " [`crate::Processor::set_config`]." +)] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " Give controls to a process call in `TimedEvent` objects. There is no", + doc = " deferred queue after the call. A stage event replaces all settings of", + doc = " that stage. To change one field, start from `config()`. Configuration", + doc = " changes have the same effects on state as `setConfig`." +)] #[derive(Clone, Copy, Debug, PartialEq)] #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), diff --git a/src/harmony.rs b/src/harmony.rs index a034559..6a34ea5 100644 --- a/src/harmony.rs +++ b/src/harmony.rs @@ -34,10 +34,20 @@ 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 = " The default is [`Self::MidiChannels`]. The static interval and chord", + doc = " sources use the related [`HarmonyConfig`] fields. The MIDI sources use", + doc = " [`crate::ControlEvent::Midi`]. The configuration of the sources that are", + doc = " not selected is still validated and kept." +)] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The default is `\"midiChannels\"`. The static interval and chord sources", + doc = " use the related `HarmonyConfig` fields. The MIDI sources use `\"midi\"`", + doc = " control events. The configuration of the sources that are not selected", + doc = " is still validated and kept." +)] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), @@ -111,7 +121,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 @@ -162,12 +179,26 @@ pub enum ChordName { } /// A diatonic chord with its root on a degree of the selected -/// [`HarmonyScale`]. +#[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " [`HarmonyScale`]." +)] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " `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 +292,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 @@ -270,7 +308,14 @@ pub struct HarmonyConfig { /// 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 + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " zeros. [`HarmonySource::FixedInterval`] uses them. A value of 12 makes" + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " zeros. `\"fixedInterval\"` uses them. A value of 12 makes" + )] /// the pitch one octave higher. #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), @@ -278,17 +323,38 @@ pub struct HarmonyConfig { )] 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 + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " zeros. [`HarmonySource::SmartInterval`] uses them. Seven steps make" + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " zeros. `\"smartInterval\"` uses them. Seven steps make" + )] /// the pitch one octave higher. #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), tsify(type = "[number, number, number, number]") )] pub diatonic_intervals: [i8; HARMONY_VOICES], - /// The named chord for [`HarmonySource::ChordByName`]. The default is + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The named chord for [`HarmonySource::ChordByName`]. The default is" + )] + #[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 + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The chord on a scale degree for [`HarmonySource::ChordByDegree`]. The" + )] + #[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 @@ -317,8 +383,16 @@ pub struct HarmonyConfig { 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 + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The default is 4. [`HarmonySource::FixedInterval`] and", + doc = " [`HarmonySource::SmartInterval`] use the first `voices` voices. The" + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The default is 4. `\"fixedInterval\"` and `\"smartInterval\"` use the", + doc = " 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. diff --git a/src/midi.rs b/src/midi.rs index 8c3f693..a43fe31 100644 --- a/src/midi.rs +++ b/src/midi.rs @@ -5,11 +5,21 @@ 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 = " Use [`crate::ControlEvent::Midi`] for harmony. Use", + doc = " [`crate::ControlEvent::CorrectionMidi`] for the independent correction", + doc = " keyboard. The typed representation can contain `u8` values that are not", + doc = " valid. [`Self::validate`] and the event preflight of the processor check", + doc = " the MIDI ranges. Note numbers use A4 = 69 at 440 Hz." +)] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " Use a `\"midi\"` control event for harmony. Use a `\"correctionMidi\"`", + doc = " control event for the independent correction keyboard. The processor", + doc = " checks the channel, note and velocity ranges before it processes a", + doc = " block. Note numbers use A4 = 69 at 440 Hz." +)] #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), @@ -25,7 +35,14 @@ pub enum MidiEvent { note: u8, /// The velocity, 0..=127. /// - /// Zero releases the note, as [`Self::NoteOff`] does. + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " Zero releases the note, as [`Self::NoteOff`] does." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " Zero releases the note, as `\"noteOff\"` does." + )] velocity: u8, }, /// A note stops. diff --git a/src/pitch.rs b/src/pitch.rs index 4f2a276..181f28a 100644 --- a/src/pitch.rs +++ b/src/pitch.rs @@ -28,7 +28,14 @@ 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. @@ -36,7 +43,14 @@ pub struct PitchConfig { /// 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 + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " `min_frequency_hz`. Results outside the bounds are reported as" + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " `minFrequencyHz`. Results outside the bounds are reported as" + )] /// unvoiced, with zero frequency and zero period. pub max_frequency_hz: f32, } diff --git a/src/processor.rs b/src/processor.rs index 5cc33bc..fdc372e 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -698,11 +698,20 @@ impl Processor { /// 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 = " Get it with [`Processor::feedback`] or [`Processor::take_feedback`]. The", + doc = " pitch fields describe the tracked input and the correction target. The", + doc = " peak measures the final clipped stereo output. `Default` gives a snapshot", + doc = " with all zeros and no target. It does not read the nominal latency of a", + doc = " prepared processor." +)] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " Get it with `feedback` or `takeFeedback`. The pitch fields describe the", + doc = " tracked input and the correction target. The peak measures the final", + doc = " clipped stereo output." +)] #[derive(Clone, Copy, Debug, Default, PartialEq)] #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), @@ -721,7 +730,11 @@ pub struct Feedback { /// 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 = " [`crate::PitchConfig`]." + )] + #[cfg_attr(all(feature = "wasm", target_arch = "wasm32"), doc = " `PitchConfig`.")] pub period_samples: f32, /// The reported input pitch frequency in hertz. /// @@ -742,10 +755,20 @@ pub struct Feedback { /// 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 = " The value is `None` if [`voiced`](Self::voiced) is `false`, and only", + doc = " then. This occurs if the input is unvoiced or if its frequency is", + doc = " outside the current reporting bounds. A target table that has no", + doc = " selected target does not give `None`." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The value is `undefined` if `voiced` is `false`, and only then. This", + doc = " occurs if the input is unvoiced or if its frequency is outside the", + doc = " current reporting bounds. A target table that has no selected target", + doc = " 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. @@ -756,17 +779,41 @@ pub struct Feedback { /// 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 = " stereo output or at a call to [`Processor::take_feedback`]. The value", + doc = " is in 0..=32767/32768. The mono downmix occurs after this measurement.", + doc = " [`Processor::feedback`] does not clear the value." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " stereo output or at a call to `takeFeedback`. The value is in", + doc = " 0..=32767/32768. The mono downmix occurs after this measurement.", + doc = " `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. /// - /// The count saturates at `u64::MAX`. Drain completion resets it in the + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The count saturates at `u64::MAX`. Drain completion resets it in the" + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The count saturates at the maximum unsigned 64-bit integer. Drain", + doc = " 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 `latencyFrames` gives." + )] #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), serde(serialize_with = "crate::wasm::serialize_frame_count"), @@ -778,14 +825,27 @@ 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 = " Get it with [`Processor::telemetry`] or [`Processor::take_telemetry`]. The", + doc = " telemetry is for meters and displays. No audio calculation reads it.", + doc = " `Default` gives a snapshot with all zeros.", + doc = "", + doc = " The three peak fields measure a window. The window starts at", + doc = " construction, at a reset, at a change of stereo output or at a call to", + doc = " [`Processor::take_telemetry`]. This window is independent of the peak", + doc = " window of [`Feedback`]." +)] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " Get it with `telemetry` or `takeTelemetry`. The telemetry is for", + doc = " meters and displays. No audio calculation reads it.", + doc = "", + doc = " The three peak fields measure a window. The window starts at", + doc = " construction, at a reset, at a change of stereo output or at a call to", + doc = " `takeTelemetry`. This window is independent of the peak window of", + doc = " `Feedback`." +)] #[derive(Clone, Copy, Debug, Default, PartialEq)] #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), @@ -795,7 +855,14 @@ pub struct Feedback { )] 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 = " as [`Feedback::processed_frames`] gives." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " as `Feedback.processedFrames` gives." + )] pub processed_frames: u64, /// The largest absolute input sample in the window, divided by 32768. /// @@ -819,17 +886,34 @@ pub struct Telemetry { /// 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 + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " [`Feedback::voiced`]. The tracker updates the related sums on each" + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " `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)", + doc = " and [`voice_gains`](Self::voice_gains).", + doc = "", + doc = " The value is 5 in Harmony mode. In Choir mode, it is", + doc = " [`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", + doc = " `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. @@ -838,10 +922,21 @@ pub struct Telemetry { /// 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 = " [`voice_count`](Self::voice_count) are zero." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " `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 = " [`voice_ratios`](Self::voice_ratios)." + )] + #[cfg_attr(all(feature = "wasm", target_arch = "wasm32"), doc = " `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 @@ -864,10 +959,24 @@ pub struct Telemetry { /// 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 = " [`crate::AlienConfig::loop_frames`] gives." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " `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 = " [`alien_loop_frames`](Self::alien_loop_frames)." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " `alienLoopFrames`." + )] /// /// The reverse reader is two times this number of frames behind the /// recording position. The value advances also while Alien is disabled. @@ -876,6 +985,13 @@ pub struct Telemetry { /// /// 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 = " [`Processor::formant_envelope`] can give a new result." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " `formantEnvelope` can give a new result." + )] pub formant_generation: u32, } diff --git a/src/resynthesis.rs b/src/resynthesis.rs index 22a0b6b..68da0ef 100644 --- a/src/resynthesis.rs +++ b/src/resynthesis.rs @@ -89,12 +89,27 @@ 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` + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " If you disable correction, the ratio moves toward 1.0 with `retune_ms`" + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + 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", + doc = " [`NoteMask::CHROMATIC`]." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The configured target pitch classes. The default enables all twelve", + doc = " pitch classes." + )] /// /// All boolean masks are valid. MIDI can replace the active table. This /// replacement stays until this mask or `enabled` changes. @@ -166,8 +181,16 @@ 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", + doc = " default is [`PitchConfig::default`]." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The acquisition sensitivity and the reporting bounds. See", + doc = " `PitchConfig` for the defaults." + )] pub pitch: PitchConfig, /// The target notes and the retune time. The default is enabled /// chromatic correction with a retune time of zero. @@ -181,7 +204,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, @@ -208,14 +238,28 @@ pub struct ResynthesisConfig { 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 + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The code uses this value only if `stereo_output` enables the voice pan" + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + 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 = " [`crate::Processor::set_config`] gives the details." + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " `setConfig` gives the details." + )] pub stereo_output: bool, /// The controls for the four harmony voices. The default is MIDI-channel /// allocation. @@ -225,7 +269,14 @@ pub struct ResynthesisConfig { pub harmony: HarmonyConfig, /// The pan gain of the harmony voices, 0..=1. The default is 0.5. /// - /// The code applies this gain only if `stereo_output` is `true`. The + #[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The code applies this gain only if `stereo_output` is `true`. The" + )] + #[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The code applies this gain only if `stereoOutput` is `true`. The" + )] /// harmony path without pan does not use this control. It does not scale /// the lead voice. pub harmony_gain: f32, diff --git a/src/scale.rs b/src/scale.rs index 01c4f94..8a12570 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 name for correction targets." +)] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), @@ -86,8 +93,17 @@ 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 +#[cfg_attr( + not(all(feature = "wasm", target_arch = "wasm32")), + doc = " The default is [`Self::CHROMATIC`]. All combinations of flags are valid.", + doc = " This includes [`Self::NONE`]. If the mask is empty, the correction ratio" +)] +#[cfg_attr( + all(feature = "wasm", target_arch = "wasm32"), + doc = " The default enables all twelve pitch classes. All combinations of flags", + doc = " are valid, which includes all `false` values. If the mask is empty, the", + doc = " 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)] diff --git a/src/wasm.rs b/src/wasm.rs index ccff598..79ee4f4 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -42,7 +42,8 @@ //! `free()` method. use crate::{ - Error, Feedback, PrepareConfig, Processor, ProcessorConfig, SampleRate, Telemetry, TimedEvent, + ConfigProblem, Error, EventProblem, Feedback, PrepareConfig, Processor, ProcessorConfig, + SampleRate, Telemetry, TimedEvent, }; use js_sys::{Float32Array, Int16Array}; use serde::{Deserialize, Serialize}; @@ -73,7 +74,7 @@ pub struct BlockEvents(Vec); /// JavaScript `Error`. #[wasm_bindgen(js_name = defaultConfig)] pub fn default_config() -> Result, JsError> { - Ok(ProcessorConfig::default().into_ts()?) + ProcessorConfig::default().into_ts().map_err(ts_error) } /// A stateful PCM processor that JavaScript uses as the `Tunelet` class. @@ -119,7 +120,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 @@ -140,8 +141,8 @@ 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 { // Accept JavaScript numbers without the u32 coercion of wasm-bindgen. @@ -149,22 +150,28 @@ impl WasmProcessor { let rate = match sample_rate { 44100.0 => SampleRate::Hz44100, 48000.0 => SampleRate::Hz48000, - _ => return Err(JsError::new("sampleRate must be 44100 or 48000")), + _ => { + let value = format_js_number(sample_rate); + return Err(JsError::new(&format!( + "sampleRate is {value}, must be 44100 or 48000" + ))); + } }; 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 value = format_js_number(max_block_frames); + return Err(JsError::new(&format!( + "maxBlockFrames is {value}, 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 preparation = PrepareConfig::new(rate, max_block_frames).map_err(wasm_error)?; let config = match config { - Some(value) => value.to_rust()?, + Some(value) => value.to_rust().map_err(ts_error)?, None => ProcessorConfig::default(), }; - let processor = Processor::new(preparation, config)?; + let processor = Processor::new(preparation, config).map_err(wasm_error)?; Ok(Self { processor, input: pcm_buffer(max_block_frames)?, @@ -209,7 +216,7 @@ impl WasmProcessor { /// /// If the conversion to a JavaScript object fails, this method throws. pub fn config(&self) -> Result, JsError> { - Ok(self.processor.config().into_ts()?) + self.processor.config().into_ts().map_err(ts_error) } /// Decodes and validates a configuration, then replaces the complete @@ -224,7 +231,8 @@ impl WasmProcessor { /// After an error, all processor state and any active drain stay the same. #[wasm_bindgen(js_name = setConfig)] pub fn set_config(&mut self, config: Ts) -> Result<(), JsError> { - self.processor.set_config(config.to_rust()?)?; + let config = config.to_rust().map_err(ts_error)?; + self.processor.set_config(config).map_err(wasm_error)?; Ok(()) } @@ -252,17 +260,19 @@ impl WasmProcessor { events: Option>, ) -> Result<(), JsError> { let frames = input.length() as usize; - Error::check_length("left", frames, left.length() as usize)?; - Error::check_length("right", frames, right.length() as usize)?; - self.check_frames(frames)?; + Error::check_length("left", frames, left.length() as usize).map_err(wasm_error)?; + Error::check_length("right", frames, right.length() as usize).map_err(wasm_error)?; + self.check_frames(frames).map_err(wasm_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(wasm_error)?; left.copy_from(&self.left[..frames]); right.copy_from(&self.right[..frames]); Ok(()) @@ -285,11 +295,12 @@ impl WasmProcessor { events: Option>, ) -> Result<(), JsError> { let frames = audio.length() as usize; - self.check_frames(frames)?; + self.check_frames(frames).map_err(wasm_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(wasm_error)?; audio.copy_from(&self.input[..frames]); Ok(()) } @@ -326,11 +337,12 @@ impl WasmProcessor { /// drain state do not change. pub fn drain(&mut self, left: &Int16Array, right: &Int16Array) -> Result { let frames = left.length() as usize; - Error::check_length("right", frames, right.length() as usize)?; - self.check_frames(frames)?; + Error::check_length("right", frames, right.length() as usize).map_err(wasm_error)?; + self.check_frames(frames).map_err(wasm_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(wasm_error)?; left.copy_from(&self.left[..frames]); right.copy_from(&self.right[..frames]); Ok(count) @@ -348,8 +360,11 @@ impl WasmProcessor { #[wasm_bindgen(js_name = drainMono)] pub fn drain_mono(&mut self, audio: &Int16Array) -> Result { let frames = audio.length() as usize; - self.check_frames(frames)?; - let count = self.processor.drain_mono(&mut self.input[..frames])?; + self.check_frames(frames).map_err(wasm_error)?; + let count = self + .processor + .drain_mono(&mut self.input[..frames]) + .map_err(wasm_error)?; audio.copy_from(&self.input[..frames]); Ok(count) } @@ -371,7 +386,7 @@ impl WasmProcessor { /// /// If the conversion to a JavaScript object fails, this method throws. pub fn feedback(&self) -> Result, JsError> { - Ok(self.processor.feedback().into_ts()?) + self.processor.feedback().into_ts().map_err(ts_error) } /// Returns the feedback and clears only the stereo peak window. @@ -385,7 +400,7 @@ impl WasmProcessor { /// object. #[wasm_bindgen(js_name = takeFeedback)] pub fn take_feedback(&mut self) -> Result, JsError> { - let feedback = self.processor.feedback().into_ts()?; + let feedback = self.processor.feedback().into_ts().map_err(ts_error)?; self.processor.take_feedback(); Ok(feedback) } @@ -401,7 +416,7 @@ impl WasmProcessor { /// /// If the conversion to a JavaScript object fails, this method throws. pub fn telemetry(&self) -> Result, JsError> { - Ok(self.processor.telemetry().into_ts()?) + self.processor.telemetry().into_ts().map_err(ts_error) } /// Returns the telemetry and clears only its three peak windows. @@ -415,7 +430,7 @@ impl WasmProcessor { /// object. #[wasm_bindgen(js_name = takeTelemetry)] pub fn take_telemetry(&mut self) -> Result, JsError> { - let telemetry = self.processor.telemetry().into_ts()?; + let telemetry = self.processor.telemetry().into_ts().map_err(ts_error)?; self.processor.take_telemetry(); Ok(telemetry) } @@ -448,18 +463,19 @@ 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 { let points = input.length() as usize; // Check before the buffers become longer for a call that cannot succeed. - Error::check_length("output", points, output.length() as usize)?; + Error::check_length("output", points, output.length() as usize).map_err(wasm_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(wasm_error)?; input.copy_from(analysis); output.copy_from(synthesis); Ok(valid) @@ -493,11 +509,102 @@ impl WasmProcessor { /// 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()?, + Some(value) => value.to_rust().map_err(ts_error)?, None => BlockEvents::default(), }) } +/// Formats a JavaScript `number` for error messages. +fn format_js_number(value: f64) -> String { + if value == f64::INFINITY { + String::from("Infinity") + } else if value == f64::NEG_INFINITY { + String::from("-Infinity") + } else { + value.to_string() + } +} + +/// Converts a dotted `snake_case` field path into a `camelCase` JavaScript +/// property path, with an optional array index. +fn format_js_field(field: &str, index: Option) -> String { + let mut result = String::with_capacity(field.len() + 4); + let mut upper_next = false; + for ch in field.chars() { + if ch == '_' { + upper_next = true; + } else if upper_next { + result.push(ch.to_ascii_uppercase()); + upper_next = false; + } else { + result.push(ch); + } + } + if let Some(slot) = index { + use std::fmt::Write as _; + let _ = write!(result, "[{slot}]"); + } + result +} + +/// Formats a `ConfigProblem` with `camelCase` JavaScript property paths. +fn format_js_config_problem(problem: ConfigProblem) -> String { + match problem { + ConfigProblem::Unordered { + value, + other, + other_value, + } => { + let other = format_js_field(other, None); + format!("is {value}, must be below {other} ({other_value})") + } + other => other.to_string(), + } +} + +/// Converts a native `Error` into a `JsError` with `camelCase` JavaScript +/// property paths. +fn wasm_error(error: Error) -> JsError { + let message = match error { + Error::InvalidConfig { + field, + index, + problem, + } => { + let path = format_js_field(field, index); + let detail = format_js_config_problem(problem); + format!("invalid config: {path} {detail}") + } + Error::InvalidEvent { + index, + problem: + EventProblem::Config { + field, + index: slot, + problem, + }, + } => { + let path = format_js_field(field, slot); + let detail = format_js_config_problem(problem); + format!("event {index}: {path} {detail}") + } + other => other.to_string(), + }; + JsError::new(&message) +} + +/// Rewrites Rust module paths in `tsify` conversion errors to public +/// TypeScript names. +fn ts_error(error: tsify::Error) -> JsError { + let message = error + .to_string() + .replace("tunelet::wasm::BlockEvents", "TimedEvent[]") + .replace("tunelet::config::ProcessorConfig", "ProcessorConfig") + .replace("tunelet::processor::Feedback", "Feedback") + .replace("tunelet::processor::Telemetry", "Telemetry"); + JsError::new(&message) +} + /// Returns the first `points` entries of a reusable envelope buffer. If the /// buffer is shorter, it becomes `points` long first. /// From dcd67925b7136dcf2ec34d2c0796386df67244e8 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Sat, 21 Nov 2026 01:56:45 +0000 Subject: [PATCH 3/4] fix(npm): guard Wasm initialization and processor disposal - Reject defaultConfig and Tunelet calls before initialization. - Reject loadTunelet and initSync calls with a different Wasm source. - Clear the initialization state after a load error. - Make free and Symbol.dispose safe to call more than one time. - Reject method and property calls on a disposed Tunelet instance. - Document the lifecycle rules in the README. --- README.md | 12 +- src/index.ts | 446 +++++++++++++++++++++++++++++++++++++++++++++++---- 2 files changed, 422 insertions(+), 36 deletions(-) diff --git a/README.md b/README.md index d2993dc..9e09663 100644 --- a/README.md +++ b/README.md @@ -382,15 +382,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. +rules. Calls with the same source share the initialized module. A call with a +different source rejects with an `Error`. 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")`. +only one initialization entry point for each module instance. Calls before +initialization or after `free()` throw an `Error`, and duplicate `free()` +calls do no work. The package gives only ESM exports. CommonJS applications +can use `await import("tunelet")`. ### Deployment diff --git a/src/index.ts b/src/index.ts index da35a57..fd9ed4e 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,19 +1,163 @@ /** * 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 wraps `loadTunelet`, `initSync`, + * `defaultConfig` and `Tunelet` with lifecycle checks, and re-exports the + * configuration, event, feedback and telemetry types. */ -import init, { initSync } from "../pkg/tunelet.js"; -import type { InitInput, InitOutput } from "../pkg/tunelet.js"; +import wasmInit, { + Tunelet as WasmTunelet, + defaultConfig as wasmDefaultConfig, + initSync as wasmInitSync, +} from "../pkg/tunelet.js"; +import type { + AlienConfig, + BlockEvents, + ChordDegree, + ChordName, + ControlEvent, + CorrectionConfig, + CorrectionScale, + Feedback, + FormantConfig, + HarmonyConfig, + HarmonyScale, + HarmonySource, + InitInput, + InitOutput, + Inversion, + MidiEvent, + 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, + BlockEvents, + ChordDegree, + ChordName, + ControlEvent, + CorrectionConfig, + CorrectionScale, + Feedback, + FormantConfig, + HarmonyConfig, + HarmonyScale, + HarmonySource, + InitInput, + InitOutput, + Inversion, + MidiEvent, + 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; +/** State for the active or completed Wasm initialization attempt. */ +interface InitAttempt { + rawSource: InitInput | Promise | undefined; + resolvedInput: InitInput | undefined; + inputPromise: Promise; + outputPromise: Promise; +} + +/** The active or completed initialization state, which a failure clears. */ +let activeAttempt: InitAttempt | undefined; + +/** The initialized Wasm exports after a successful initialization. */ +let initializedOutput: InitOutput | undefined; + +/** Returns the default URL of the packaged Wasm binary. */ +function defaultWasmUrl(): URL { + return new URL("../pkg/tunelet_bg.wasm", import.meta.url); +} + +/** Checks if a value is a Promise-like object. */ +function isPromiseLike( + value: InitInput | Promise | undefined, +): value is Promise { + return ( + (typeof value === "object" || typeof value === "function") && + value !== null && + "then" in value && + typeof (value as { then?: unknown }).then === "function" + ); +} + +/** Checks if two resolved Wasm sources identify the same input. */ +function sameInput(left: InitInput, right: InitInput): boolean { + if (Object.is(left, right)) { + return true; + } + return left instanceof URL && right instanceof URL && left.href === right.href; +} + +/** Checks if two unawaited `loadTunelet` arguments are immediately equal. */ +function sameRawSource( + left: InitInput | Promise | undefined, + right: InitInput | Promise | undefined, +): boolean { + if (Object.is(left, right)) { + return true; + } + if (isPromiseLike(left) || isPromiseLike(right)) { + return false; + } + const leftInput = left === undefined ? defaultWasmUrl() : left; + const rightInput = right === undefined ? defaultWasmUrl() : right; + return sameInput(leftInput, rightInput); +} + +/** Resolves an optional `loadTunelet` argument to a concrete `InitInput`. */ +async function resolveInput( + source: InitInput | Promise | undefined, +): Promise { + return source === undefined ? defaultWasmUrl() : await source; +} + +/** Throws if the Wasm module has not completed initialization. */ +function ensureInitialized(): void { + if (initializedOutput === undefined) { + throw new Error( + "Tunelet Wasm is not initialized. Await loadTunelet() or call initSync() first.", + ); + } +} + +/** Checks if a synchronous init argument uses the `{ module }` wrapper. */ +function isSyncModuleObject( + value: { module: SyncInitInput } | SyncInitInput, +): value is { module: SyncInitInput } { + return ( + typeof value === "object" && + value !== null && + Object.getPrototypeOf(value) === Object.prototype && + "module" in value + ); +} /** * Initializes the Wasm module one time for this imported package instance. @@ -35,37 +179,79 @@ let initialization: Promise | undefined; * 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 calls with the same source share one promise. After a successful + * initialization, later calls with the same source return that promise and do + * not load Wasm again. Calls with a different source reject with an `Error`. + * 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. * * @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( source?: InitInput | Promise, ): Promise { - initialization ??= initialize(source).catch((error: unknown) => { - initialization = undefined; - throw error; - }); - return initialization; + if (activeAttempt !== undefined) { + if (sameRawSource(activeAttempt.rawSource, source)) { + return activeAttempt.outputPromise; + } + if (!isPromiseLike(activeAttempt.rawSource) && !isPromiseLike(source)) { + return Promise.reject( + new Error( + "Cannot call loadTunelet() with a different Wasm source after initialization starts.", + ), + ); + } + return verifyMatchingSource(activeAttempt, source); + } + + const inputPromise = resolveInput(source); + const attempt: InitAttempt = { + rawSource: source, + resolvedInput: undefined, + inputPromise, + outputPromise: Promise.resolve(undefined as never), + }; + attempt.outputPromise = initializeFromAttempt(attempt).catch( + (error: unknown) => { + if (activeAttempt === attempt && initializedOutput === undefined) { + activeAttempt = undefined; + } + throw error; + }, + ); + activeAttempt = attempt; + return attempt.outputPromise; } -/** Awaits the source one time, then initializes the Wasm module from it. */ -async function initialize( +/** Verifies that a Promise-wrapped source resolves to the active source. */ +async function verifyMatchingSource( + attempt: InitAttempt, source: InitInput | Promise | undefined, ): Promise { - const input = - source === undefined - ? new URL("../pkg/tunelet_bg.wasm", import.meta.url) - : await source; + const [expected, actual] = await Promise.all([ + attempt.inputPromise, + resolveInput(source), + ]); + if (!sameInput(expected, actual)) { + throw new Error( + "Cannot call loadTunelet() with a different Wasm source after initialization starts.", + ); + } + return attempt.outputPromise; +} + +/** Instantiates the Wasm module for a new initialization attempt. */ +async function initializeFromAttempt( + attempt: InitAttempt, +): Promise { + const input = await attempt.inputPromise; + attempt.resolvedInput = input; + let output: InitOutput; 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:` @@ -74,10 +260,208 @@ async function initialize( const fs: typeof import("node:fs/promises") = await import( /* webpackIgnore: true */ /* @vite-ignore */ moduleName ); - return initSync({ module: await fs.readFile(input) }); + output = wasmInitSync({ module: await fs.readFile(input) }); + } else { + output = await wasmInit({ module_or_path: input }); } - return init({ module_or_path: input }); + initializedOutput = output; + return output; +} + +/** + * Instantiates the Wasm module synchronously from bytes or a compiled + * `WebAssembly.Module`. + * + * Repeated calls with the same source return the initialized exports. A call + * with a different source, or while `loadTunelet()` is active, throws an + * `Error`. + */ +export function initSync( + module: { module: SyncInitInput } | SyncInitInput, +): InitOutput { + const input = isSyncModuleObject(module) ? module.module : module; + if (activeAttempt !== undefined) { + if ( + initializedOutput !== undefined && + activeAttempt.resolvedInput !== undefined && + sameInput(activeAttempt.resolvedInput, input) + ) { + return initializedOutput; + } + throw new Error( + "Cannot call initSync() with a different Wasm source after initialization starts.", + ); + } + + const output = + input === undefined ? wasmInitSync(module) : wasmInitSync({ module: input }); + initializedOutput = output; + const outputPromise = Promise.resolve(output); + activeAttempt = { + rawSource: input, + resolvedInput: input, + inputPromise: Promise.resolve(input), + outputPromise, + }; + return output; +} + +/** + * Returns a complete, independent default configuration for JavaScript. + * + * Call `loadTunelet()` or `initSync()` before this function. Change the fields + * of the returned object and give it to `new Tunelet(...)` or `setConfig`. + */ +export function defaultConfig(): ProcessorConfig { + ensureInitialized(); + return wasmDefaultConfig(); +} + +/** + * A stateful PCM processor with lifecycle guards. + * + * Call `loadTunelet()` or `initSync()` before you construct an instance. Call + * `free()` when you do not need the instance any more. Duplicate `free()` + * calls do no work, and later method or property calls throw an `Error`. + */ +export class Tunelet { + #inner: WasmTunelet | undefined; + + declare [Symbol.dispose]: () => void; + + /** + * Prepares a processor and its reusable PCM buffers. + * + * `sampleRate` must be 44100 or 48000. `maxBlockFrames` must be an integer + * in 1..=4294967295. If you omit `config`, the processor uses the default + * configuration. + */ + constructor( + sampleRate: number, + maxBlockFrames: number, + config?: ProcessorConfig | null, + ) { + ensureInitialized(); + this.#inner = new WasmTunelet(sampleRate, maxBlockFrames, config); + } + + #active(): WasmTunelet { + if (this.#inner === undefined) { + throw new Error( + "Tunelet instance is disposed. Do not use it after free().", + ); + } + return this.#inner; + } + + /** Releases the Wasm processor memory. Duplicate calls do no work. */ + free(): void { + const inner = this.#inner; + if (inner === undefined) { + return; + } + this.#inner = undefined; + inner.free(); + } + + /** The sample rate of the input and the output in hertz. */ + get sampleRate(): number { + return this.#active().sampleRate; + } + + /** The maximum frame count for each call that processes or drains audio. */ + get maxBlockFrames(): number { + return this.#active().maxBlockFrames; + } + + /** The nominal resynthesis delay in frames. */ + get latencyFrames(): number { + return this.#active().latencyFrames; + } + + /** Returns a copy of the active configuration as a new JavaScript object. */ + config(): ProcessorConfig { + return this.#active().config(); + } + + /** Validates a configuration and replaces the complete configuration. */ + setConfig(config: ProcessorConfig): void { + this.#active().setConfig(config); + } + + /** Processes mono input into left and right `Int16Array` buffers. */ + process( + input: Int16Array, + left: Int16Array, + right: Int16Array, + events?: BlockEvents | null, + ): void { + this.#active().process(input, left, right, events); + } + + /** Replaces the audio in a mono `Int16Array` with the stereo downmix. */ + processMono(audio: Int16Array, events?: BlockEvents | null): void { + this.#active().processMono(audio, events); + } + + /** Starts a finite tail budget and returns its frame count. */ + beginDrain(): number { + return this.#active().beginDrain(); + } + + /** Returns the tail budget of the current configuration. */ + tailFrames(): number { + return this.#active().tailFrames(); + } + + /** Renders stereo tail frames into `Int16Array` buffers of equal length. */ + drain(left: Int16Array, right: Int16Array): number { + return this.#active().drain(left, right); + } + + /** Renders a mono tail block and returns its frame count. */ + drainMono(audio: Int16Array): number { + return this.#active().drainMono(audio); + } + + /** Returns a new feedback object and does not clear the peak window. */ + feedback(): Feedback { + return this.#active().feedback(); + } + + /** Returns the feedback and clears only the stereo peak window. */ + takeFeedback(): Feedback { + return this.#active().takeFeedback(); + } + + /** Returns a new telemetry object and does not clear its peak windows. */ + telemetry(): Telemetry { + return this.#active().telemetry(); + } + + /** Returns the telemetry and clears only its three peak windows. */ + takeTelemetry(): Telemetry { + return this.#active().takeTelemetry(); + } + + /** Writes the formant envelopes into two `Float32Array` buffers. */ + formantEnvelope( + maxFrequencyHz: number, + input: Float32Array, + output: Float32Array, + ): boolean { + return this.#active().formantEnvelope(maxFrequencyHz, input, output); + } + + /** Resets the audio histories and feedback. */ + reset(): void { + this.#active().reset(); + } +} + +if (typeof Symbol.dispose === "symbol") { + Tunelet.prototype[Symbol.dispose] = Tunelet.prototype.free; } /** The default export is the same function as `loadTunelet`. */ From 4b2ff4504679c2ea39fd2db4a7e76549e61c0866 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 07:24:55 +0000 Subject: [PATCH 4/4] test(npm): check Wasm errors and Tunelet lifecycle in pack - Check pre-initialization errors for defaultConfig and Tunelet - Check camelCase Wasm error paths and clean TypeScript names - Check duplicate free calls and post-free errors --- scripts/verify-pack.mjs | 164 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 163 insertions(+), 1 deletion(-) diff --git a/scripts/verify-pack.mjs b/scripts/verify-pack.mjs index 66d5b7a..848713e 100644 --- a/scripts/verify-pack.mjs +++ b/scripts/verify-pack.mjs @@ -308,6 +308,15 @@ function verifyRuntimeImport(consumerDir, packageName) { 'assert.equal(typeof wasmModule.default, "function");', 'assert.equal(typeof wasmModule.initSync, "function");', "", + "assert.throws(", + " () => rootModule.defaultConfig(),", + " /Tunelet Wasm is not initialized\\. Call loadTunelet\\(\\) or initSync\\(\\) first\\./,", + ");", + "assert.throws(", + " () => new rootModule.Tunelet(48000, 128),", + " /Tunelet Wasm is not initialized\\. Call loadTunelet\\(\\) or initSync\\(\\) first\\./,", + ");", + "", "const wasmExports = await rootModule.loadTunelet();", "assert.ok(wasmExports);", "assert.ok(wasmExports.memory instanceof WebAssembly.Memory);", @@ -381,9 +390,92 @@ function verifyRuntimeImport(consumerDir, packageName) { " assert.equal(processor.config().resynthesis.dryMix, 0.25);", " assert.equal(processor.config().resynthesis.correction.humanize, 0.5);", " assert.equal(processor.config().resynthesis.correction.flexTune, 0.25);", + "", + " const invalidConstructorConfig = rootModule.defaultConfig();", + " invalidConstructorConfig.resynthesis.choirDetune = 5;", + " assert.throws(", + " () => new rootModule.Tunelet(48000, 128, invalidConstructorConfig),", + " /invalid config: resynthesis\\.choirDetune must be in 10\\.\\.=100/,", + " );", + "", + " const unorderedPitchConfig = rootModule.defaultConfig();", + " unorderedPitchConfig.resynthesis.pitch.minFrequencyHz = 500;", + " unorderedPitchConfig.resynthesis.pitch.maxFrequencyHz = 400;", + " assert.throws(", + " () => processor.setConfig(unorderedPitchConfig),", + " /invalid config: resynthesis\\.pitch\\.minFrequencyHz must be below resynthesis\\.pitch\\.maxFrequencyHz/,", + " );", + "", + " const invalidFlexTuneConfig = processor.config();", + " invalidFlexTuneConfig.resynthesis.correction.flexTune = 2;", + " assert.throws(", + " () => processor.setConfig(invalidFlexTuneConfig),", + " /invalid config: resynthesis\\.correction\\.flexTune must be in 0\\.\\.=1/,", + " );", + "", + " assert.throws(", + " () => processor.setConfig({}),", + " (err) =>", + ' err instanceof Error &&', + ' err.message.includes("ProcessorConfig") &&', + ' !err.message.includes("tunelet::"),', + " );", + "", + " const framesBeforeEventErrors = processor.feedback().processedFrames;", + " assert.throws(", + " () =>", + " processor.process(input, left, right, [", + ' { offset: 0, event: { type: "outputGain", value: 100 } },', + " ]),", + " /event 0: outputGain must be in 0\\.\\.=64/,", + " );", + " const badEventResynthesis = processor.config().resynthesis;", + " badEventResynthesis.choirDetune = 5;", + " assert.throws(", + " () =>", + " processor.process(input, left, right, [", + ' { offset: 0, event: { type: "resynthesis", value: badEventResynthesis } },', + " ]),", + " /event 0: resynthesis\\.choirDetune must be in 10\\.\\.=100/,", + " );", + " assert.throws(", + " () =>", + " processor.process(input, left, right, [", + ' { offset: 0, event: { type: "parameter", value: { type: "punchGainDb", value: 99 } } },', + " ]),", + " /event 0: punch\\.gainDb must be in -96\\.\\.=12/,", + " );", + " assert.throws(", + " () =>", + " processor.process(input, left, right, [", + ' { offset: 0, event: { type: "parameter", value: { type: "choirDetune", value: 5 } } },', + " ]),", + " /event 0: resynthesis\\.choirDetune must be in 10\\.\\.=100/,", + " );", + " assert.throws(", + " () =>", + " processor.process(input, left, right, [", + ' { offset: 0, event: { type: "punch", value: {} } },', + " ]),", + ' (err) => err instanceof Error && !err.message.includes("tunelet::"),', + " );", + " assert.equal(processor.feedback().processedFrames, framesBeforeEventErrors);", "} finally {", " processor.free();", "}", + "processor.free();", + "assert.throws(", + " () => processor.sampleRate,", + " /Tunelet instance is disposed\\. Do not use it after free\\(\\)\\./,", + ");", + "assert.throws(", + " () => processor.config(),", + " /Tunelet instance is disposed\\. Do not use it after free\\(\\)\\./,", + ");", + "assert.throws(", + " () => processor.reset(),", + " /Tunelet instance is disposed\\. Do not use it after free\\(\\)\\./,", + ");", "", "const config = rootModule.defaultConfig();", "config.resynthesis.formant.enabled = true;", @@ -485,6 +577,23 @@ function verifyRuntimeImport(consumerDir, packageName) { " assert.throws(() =>", " f32Processor.processF32InPlace(64, [{ offset: 64, event: { type: \"reset\" } }]),", " );", + " assert.throws(", + " () =>", + " f32Processor.processF32InPlace(64, [", + ' { offset: 0, event: { type: "parameter", value: { type: "reverbBrightnessHz", value: 10 } } },', + " ]),", + " /event 0: reverb\\.brightnessHz must be in 80\\.\\.=20000/,", + " );", + " assert.throws(", + " () =>", + " copiedF32Processor.processF32(", + " inputF32.subarray(0, 64),", + " leftF32.subarray(0, 64),", + " rightF32.subarray(0, 64),", + ' [{ offset: 0, event: { type: "parameter", value: { type: "flexTune", value: -1 } } }],', + " ),", + " /event 0: resynthesis\\.correction\\.flexTune must be in 0\\.\\.=1/,", + " );", " assert.equal(f32Processor.feedback().processedFrames, framesBeforeError);", " assert.equal(views.left[0], savedLeft0);", "", @@ -560,6 +669,51 @@ function verifyRuntimeImport(consumerDir, packageName) { "assert.equal(disposableViews.disposed, true);", 'assert.equal(typeof disposableProcessor[Symbol.dispose], "function");', "disposableProcessor[Symbol.dispose]();", + "disposableProcessor[Symbol.dispose]();", + "disposableProcessor.free();", + "for (const getter of [", + ' "inputF32Ptr",', + ' "leftF32Ptr",', + ' "rightF32Ptr",', + ' "sampleRate",', + ' "maxBlockFrames",', + ' "latencyFrames",', + "]) {", + " assert.throws(", + " () => disposableProcessor[getter],", + " /Tunelet instance is disposed\\. Do not use it after free\\(\\)\\./,", + " );", + "}", + "for (const callDisposed of [", + " () => disposableProcessor.config(),", + " () => disposableProcessor.setConfig(rootModule.defaultConfig()),", + " () => disposableProcessor.process(new Int16Array(0), new Int16Array(0), new Int16Array(0)),", + " () => disposableProcessor.processMono(new Int16Array(0)),", + " () => disposableProcessor.processF32(new Float32Array(0), new Float32Array(0), new Float32Array(0)),", + " () => disposableProcessor.processMonoF32(new Float32Array(0)),", + " () => disposableProcessor.processF32InPlace(0),", + " () => disposableProcessor.processMonoF32InPlace(0),", + " () => disposableProcessor.beginDrain(),", + " () => disposableProcessor.tailFrames(),", + " () => disposableProcessor.drain(new Int16Array(0), new Int16Array(0)),", + " () => disposableProcessor.drainMono(new Int16Array(0)),", + " () => disposableProcessor.drainF32(new Float32Array(0), new Float32Array(0)),", + " () => disposableProcessor.drainMonoF32(new Float32Array(0)),", + " () => disposableProcessor.drainF32InPlace(0),", + " () => disposableProcessor.drainMonoF32InPlace(0),", + " () => disposableProcessor.feedback(),", + " () => disposableProcessor.takeFeedback(),", + " () => disposableProcessor.controlActivity(),", + " () => disposableProcessor.telemetry(),", + " () => disposableProcessor.takeTelemetry(),", + " () => disposableProcessor.formantEnvelope(8000, new Float32Array(16), new Float32Array(16)),", + " () => disposableProcessor.reset(),", + "]) {", + " assert.throws(", + " callDisposed,", + " /Tunelet instance is disposed\\. Do not use it after free\\(\\)\\./,", + " );", + "}", "", ].join("\n"), ); @@ -669,7 +823,15 @@ function verifyRuntimeImport(consumerDir, packageName) { "const wasmBytes = fs.readFileSync(", " fileURLToPath(import.meta.resolve(`${packageName}/tunelet_bg.wasm`)),", ");", - "const { initSync, Tunelet } = await import(packageName);", + "const { defaultConfig, initSync, Tunelet } = await import(packageName);", + "assert.throws(", + " () => defaultConfig(),", + " /Tunelet Wasm is not initialized\\. Call loadTunelet\\(\\) or initSync\\(\\) first\\./,", + ");", + "assert.throws(", + " () => new Tunelet(48000, 128),", + " /Tunelet Wasm is not initialized\\. Call loadTunelet\\(\\) or initSync\\(\\) first\\./,", + ");", "const exportsFromSync = initSync({ module: wasmBytes });", "assert.ok(exportsFromSync);", "const processor = new Tunelet(48000, 128);",