From 518cfc52ef7942fa3522915507ab42412d2f8ddb Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Sat, 21 Nov 2026 02:07:32 +0000 Subject: [PATCH 1/3] feat(processor): add f32 process and drain methods - Add interleaved, planar and mono f32 process methods. - Add interleaved, planar and mono f32 drain methods. - Map NaN to zero and clamp f32 inputs to -1.0..=1.0. - Scale rendered PCM samples by 1/32768 and zero unused drain frames. - Preserve the fixed-point chain and i16 PCM output. --- src/error.rs | 6 +- src/lib.rs | 33 +++++--- src/processor.rs | 210 ++++++++++++++++++++++++++++++++++++++++++++--- 3 files changed, 223 insertions(+), 26 deletions(-) diff --git a/src/error.rs b/src/error.rs index b971968..0385aea 100644 --- a/src/error.rs +++ b/src/error.rs @@ -35,9 +35,9 @@ pub enum Error { /// A buffer length is not equal to the input length or to the length of /// the other output channel. BufferLength { - /// 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. + /// The necessary slice length. For `[[i16; 2]]` or `[[f32; 2]]`, this + /// is the number of stereo frames. For planar or mono audio, it is the + /// number of samples for each channel. expected: usize, /// The actual slice length, in the same units as `expected`. actual: usize, diff --git a/src/lib.rs b/src/lib.rs index 0e29119..265e08d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,10 +1,11 @@ //! A crate for vocal pitch correction, choir, harmony, formant control and effects. //! -//! [`Processor`] changes mono signed 16-bit PCM into the same number of stereo -//! or mono frames. The sample rate is 44.1 kHz or 48 kHz. The signal chain is -//! Punch → Warm → pitch tracking and resynthesis → Alien → reverb → output -//! gain. The default configuration enables chromatic pitch correction and one -//! choir voice. The optional effects and the formant stage are disabled. +//! [`Processor`] changes mono signed 16-bit PCM or 32-bit float audio into the +//! same number of stereo or mono frames. The sample rate is 44.1 kHz or +//! 48 kHz. The signal chain is Punch → Warm → pitch tracking and resynthesis +//! → Alien → reverb → output gain. The default configuration enables chromatic +//! pitch correction and one choir voice. The optional effects and the formant +//! stage are disabled. //! //! # Preparing and configuring //! @@ -26,15 +27,21 @@ //! //! # Audio and timed controls //! -//! There are three process methods: +//! There are three output layouts for `i16` and `f32` audio: //! -//! - [`Processor::process`] writes `[left, right]` frames. -//! - [`Processor::process_planar`] writes separate channels. -//! - [`Processor::process_mono_in_place`] replaces the input with the stereo +//! - [`Processor::process`] and [`Processor::process_f32`] write `[left, right]` +//! frames. +//! - [`Processor::process_planar`] and [`Processor::process_planar_f32`] write +//! separate channels. +//! - [`Processor::process_mono_in_place`] and +//! [`Processor::process_mono_in_place_f32`] replace the input with the stereo //! downmix. //! //! These layouts do not depend on [`ResynthesisConfig::stereo_output`], which -//! controls voice panning. The output is clipped to -32767..=32767. +//! controls voice panning. `f32` inputs map `NaN` to zero, clamp to +//! `-1.0..=1.0` and quantize into the fixed-point chain. The PCM output is +//! clipped to `-32767..=32767`, and `f32` output scales each rendered `i16` +//! sample by `1.0 / 32768.0`. //! //! An event applies before its selected frame. Offsets must be in the current //! block and must not decrease. Events with equal offsets execute in slice @@ -92,9 +99,9 @@ //! //! To export JavaScript bindings and generated TypeScript definitions, enable //! the optional `wasm` feature for `wasm32-unknown-unknown`. The binding owns -//! PCM buffers that it uses again. Configuration conversion, event conversion, -//! feedback objects and errors cause more allocation at the JavaScript -//! boundary. +//! `i16` and `f32` audio buffers that it uses again. Configuration conversion, +//! event conversion, feedback objects and errors cause more allocation at the +//! JavaScript boundary. //! Refer to the README for how to build the shared package for browsers and //! Node.js. diff --git a/src/processor.rs b/src/processor.rs index cc910f4..299a35d 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -199,14 +199,101 @@ impl Processor { audio: &mut [i16], events: &[TimedEvent], ) -> Result<(), Error> { - let mut events = self.validate(audio, events)?; + let mut events = self.validate(audio.len(), events)?; self.drain_remaining = None; for (index, sample) in audio.iter_mut().enumerate() { while let Some(event) = events.next_at(index) { self.apply(event); } let output = self.next(*sample); - *sample = ((output[0] as i32 + output[1] as i32) >> 1) as i16; + *sample = downmix_mono(output); + } + Ok(()) + } + + /// Processes mono `f32` audio into `[left, right]` stereo frames. + /// + /// If an input sample is `NaN`, it becomes zero. Otherwise, this method + /// clamps the sample to `-1.0..=1.0` and quantizes it to signed 16-bit PCM + /// before the fixed-point chain. Each rendered PCM sample scales by + /// `1.0 / 32768.0`, in `-32767.0 / 32768.0..=32767.0 / 32768.0`. + /// + /// The frame counts, the block limit, the event order and the drain + /// cancellation are the same as for [`process`](Self::process). + /// + /// # Errors + /// + /// The call checks [`Error::BufferLength`] first and + /// [`Error::BlockTooLarge`] second. Then it checks [`Error::InvalidEvent`] + /// for the first invalid event. All validation finishes before the state + /// or the output changes. + pub fn process_f32( + &mut self, + input: &[f32], + output: &mut [[f32; 2]], + events: &[TimedEvent], + ) -> Result<(), Error> { + Error::check_length(input.len(), output.len())?; + self.process_frames(input, events, quantize_f32, |index, frame| { + output[index] = frame.map(sample_to_f32); + }) + } + + /// Processes mono `f32` audio into separate left and right `f32` slices. + /// + /// The three slices must have equal frame counts. Input quantization, + /// output scale in `-32767.0 / 32768.0..=32767.0 / 32768.0`, event order + /// and drain cancellation are the same as for + /// [`process_f32`](Self::process_f32). + /// + /// # Errors + /// + /// The call checks [`Error::BufferLength`] for the left channel, then for + /// the right channel. Next, it checks [`Error::BlockTooLarge`], then + /// [`Error::InvalidEvent`]. If an error occurs, the two output buffers and + /// all processor state do not change. + pub fn process_planar_f32( + &mut self, + input: &[f32], + left: &mut [f32], + right: &mut [f32], + events: &[TimedEvent], + ) -> Result<(), Error> { + Error::check_length(input.len(), left.len())?; + Error::check_length(input.len(), right.len())?; + self.process_frames(input, events, quantize_f32, |index, frame| { + left[index] = sample_to_f32(frame[0]); + right[index] = sample_to_f32(frame[1]); + }) + } + + /// Replaces mono `f32` audio with the stereo downmix. + /// + /// The method reads and quantizes each input sample as in + /// [`process_f32`](Self::process_f32) before it writes over that location. + /// It computes the fixed-point downmix of + /// [`process_mono_in_place`](Self::process_mono_in_place), then scales the + /// rendered `i16` sample by `1.0 / 32768.0`. Peak feedback measures the + /// stereo samples before the downmix. + /// + /// # Errors + /// + /// Returns [`Error::BlockTooLarge`] for a slice that is too large. Returns + /// [`Error::InvalidEvent`] for the first invalid event. All checks finish + /// before the audio slice or the processor state changes. + pub fn process_mono_in_place_f32( + &mut self, + audio: &mut [f32], + events: &[TimedEvent], + ) -> Result<(), Error> { + let mut events = self.validate(audio.len(), events)?; + self.drain_remaining = None; + for (index, sample) in audio.iter_mut().enumerate() { + while let Some(event) = events.next_at(index) { + self.apply(event); + } + let output = self.next(quantize_f32(*sample)); + *sample = sample_to_f32(downmix_mono(output)); } Ok(()) } @@ -285,12 +372,76 @@ impl Processor { /// returns [`Error::BlockTooLarge`] before it changes output or state. pub fn drain_mono(&mut self, output: &mut [i16]) -> Result { let count = self.drain_into(output.len(), |index, frame| { - output[index] = ((i32::from(frame[0]) + i32::from(frame[1])) >> 1) as i16; + output[index] = downmix_mono(frame); })?; output[count..].fill(0); Ok(count) } + /// Renders the next stereo tail frames as `f32` pairs and returns their + /// count. + /// + /// Call [`begin_drain`](Self::begin_drain) first. Each rendered PCM sample + /// scales by `1.0 / 32768.0`, and unused frames fill with `[0.0, 0.0]`. + /// Empty buffers, completion and reset follow [`drain`](Self::drain). + /// + /// # Errors + /// + /// If the output is larger than the prepared block limit, the method + /// returns [`Error::BlockTooLarge`] and does not change state or output. + pub fn drain_f32(&mut self, output: &mut [[f32; 2]]) -> Result { + let count = self.drain_into(output.len(), |index, frame| { + output[index] = frame.map(sample_to_f32); + })?; + output[count..].fill([0.0; 2]); + Ok(count) + } + + /// Renders the tail into separate `f32` channels of equal size. + /// + /// Each rendered PCM sample scales by `1.0 / 32768.0`, and unused samples + /// fill with `0.0`. Return values, empty buffers and completion follow + /// [`drain_planar`](Self::drain_planar). + /// + /// # Errors + /// + /// The method checks [`Error::BufferLength`] before + /// [`Error::BlockTooLarge`]. If either error occurs, the two channels and + /// the drain state do not change. + pub fn drain_planar_f32( + &mut self, + left: &mut [f32], + right: &mut [f32], + ) -> Result { + Error::check_length(left.len(), right.len())?; + let count = self.drain_into(left.len(), |index, frame| { + left[index] = sample_to_f32(frame[0]); + right[index] = sample_to_f32(frame[1]); + })?; + left[count..].fill(0.0); + right[count..].fill(0.0); + Ok(count) + } + + /// Renders the tail as mono `f32` audio and returns the number of rendered + /// frames. + /// + /// Each frame uses the fixed-point downmix of [`drain_mono`](Self::drain_mono) + /// and scales by `1.0 / 32768.0`. Unused samples fill with `0.0`. Empty + /// buffers and completion follow [`drain_mono`](Self::drain_mono). + /// + /// # Errors + /// + /// If the output is larger than the prepared block limit, the method + /// returns [`Error::BlockTooLarge`] before it changes output or state. + pub fn drain_mono_f32(&mut self, output: &mut [f32]) -> Result { + let count = self.drain_into(output.len(), |index, frame| { + output[index] = sample_to_f32(downmix_mono(frame)); + })?; + output[count..].fill(0.0); + Ok(count) + } + /// Returns the finite tail budget for the current configuration. /// /// This value is a configured limit. It is not the number of drain frames @@ -553,11 +704,11 @@ impl Processor { /// The returned cursor is the only source of validated control tokens. fn validate<'a>( &self, - input: &[i16], + frames: usize, events: &'a [TimedEvent], ) -> Result, Error> { - self.check_block(input.len())?; - ValidatedEvents::new(events, input.len()) + self.check_block(frames)?; + ValidatedEvents::new(events, frames) } /// Enforces the prepared block limit for each call. @@ -638,22 +789,34 @@ impl Processor { } /// Checks the block, applies all controls at each offset and writes each - /// rendered frame. + /// rendered PCM frame. /// /// A callback for the buffer layout writes the frames. fn process_into( &mut self, input: &[i16], events: &[TimedEvent], + write: impl FnMut(usize, [i16; 2]), + ) -> Result<(), Error> { + self.process_frames(input, events, |sample| sample, write) + } + + /// Checks the block, converts each input sample to PCM, applies controls + /// at each offset and writes each rendered frame. + fn process_frames( + &mut self, + input: &[T], + events: &[TimedEvent], + mut to_pcm: impl FnMut(T) -> i16, mut write: impl FnMut(usize, [i16; 2]), ) -> Result<(), Error> { - let mut events = self.validate(input, events)?; + let mut events = self.validate(input.len(), events)?; self.drain_remaining = None; - for (index, sample) in input.iter().enumerate() { + for (index, sample) in input.iter().copied().enumerate() { while let Some(event) = events.next_at(index) { self.apply(event); } - write(index, self.next(*sample)); + write(index, self.next(to_pcm(sample))); } Ok(()) } @@ -696,6 +859,33 @@ impl Processor { } } +/// Quantizes one `f32` sample into signed 16-bit PCM. +/// +/// If `sample` is `NaN`, this function returns zero. Otherwise, it clamps +/// `sample` to `-1.0..=1.0`, multiplies by 32,768, rounds half away from zero +/// and saturates to `-32768..=32767`. +#[inline] +fn quantize_f32(sample: f32) -> i16 { + if sample.is_nan() { + 0 + } else { + (sample.clamp(-1.0, 1.0) * 32_768.0).round() as i16 + } +} + +/// Scales one rendered 16-bit PCM sample by `1.0 / 32768.0`. +#[inline] +fn sample_to_f32(sample: i16) -> f32 { + f32::from(sample) * (1.0 / 32_768.0) +} + +/// Averages a stereo PCM frame with an arithmetic shift toward negative +/// infinity. +#[inline] +fn downmix_mono(frame: [i16; 2]) -> i16 { + ((i32::from(frame[0]) + i32::from(frame[1])) >> 1) as i16 +} + /// A snapshot of the pitch analysis and the output level that you can copy. /// /// Get it with [`Processor::feedback`] or [`Processor::take_feedback`]. The From 4fb753b6eeef6be2df3250d0bbbcc32ddc7490a0 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Sat, 21 Nov 2026 02:07:32 +0000 Subject: [PATCH 2/3] feat(wasm): add Float32Array process and drain methods - Preallocate reusable Vec buffers in WasmProcessor. - Add processF32, processMonoF32, drainF32 and drainMonoF32. - Validate lengths, block limits and events before state changes. --- src/wasm.rs | 158 +++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 149 insertions(+), 9 deletions(-) diff --git a/src/wasm.rs b/src/wasm.rs index c9cec08..db4e091 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -9,10 +9,11 @@ //! wasm-pack can do the two steps in one command. The npm entry point uses //! `loadTunelet()` to initialize these bindings in browsers and in Node.js. //! -//! The exported `Tunelet` class owns a native [`Processor`] and three reusable -//! PCM buffers. JavaScript gives the `Int16Array` input and output buffers. The -//! PCM API does not give buffer pointers or long-lived memory views to -//! JavaScript. The class copies the input before it writes the output. +//! The exported `Tunelet` class owns a native [`Processor`] and reusable `i16` +//! and `f32` audio buffers. JavaScript gives `Int16Array` or `Float32Array` +//! input and output buffers. The audio API does not give buffer pointers or +//! long-lived memory views to JavaScript. The class copies the input before it +//! writes the output. //! //! Configuration objects obey these rules: //! @@ -76,12 +77,12 @@ pub fn default_config() -> Result, JsError> { Ok(ProcessorConfig::default().into_ts()?) } -/// A stateful PCM processor that JavaScript uses as the `Tunelet` class. +/// A stateful audio processor that JavaScript uses as the `Tunelet` class. /// -/// The input is signed 16-bit mono PCM. The output is planar stereo or an -/// in-place mono downmix. The quantization, latency and configuration behavior -/// are the same as in the native processor. Buffer lengths count frames, not -/// bytes. +/// The input is mono signed 16-bit PCM (`Int16Array`) or 32-bit float audio +/// (`Float32Array`). The output is planar stereo or an in-place mono downmix. +/// The quantization, latency and configuration behavior are the same as in the +/// native processor. Buffer lengths count frames, not bytes. /// /// These rules apply to the buffers: /// @@ -109,6 +110,15 @@ pub struct WasmProcessor { /// The reusable PCM buffer for the right channel, which the class copies to /// the caller only after a successful call. right: Vec, + /// The reusable `f32` buffer for input or in-place mono audio, with a + /// length equal to the prepared block limit. + float_input: Vec, + /// The reusable `f32` buffer for the left channel, which the class copies + /// to the caller only after a successful call. + float_left: Vec, + /// The reusable `f32` buffer for the right channel, which the class copies + /// to the caller only after a successful call. + float_right: Vec, /// The reusable buffers for the two formant envelopes. They become longer /// when a call needs more points, and they do not become shorter. envelope_input: Vec, @@ -170,6 +180,9 @@ impl WasmProcessor { input: pcm_buffer(max_block_frames)?, left: pcm_buffer(max_block_frames)?, right: pcm_buffer(max_block_frames)?, + float_input: float_buffer(max_block_frames)?, + float_left: float_buffer(max_block_frames)?, + float_right: float_buffer(max_block_frames)?, envelope_input: Vec::new(), envelope_output: Vec::new(), }) @@ -294,6 +307,72 @@ impl WasmProcessor { Ok(()) } + /// Processes mono `Float32Array` input into left and right `Float32Array` + /// buffers of equal length. + /// + /// Each `NaN` input sample becomes zero, and each other value clamps to + /// `-1.0..=1.0` before quantization into the fixed-point chain. Each + /// rendered PCM sample scales by `1.0 / 32768.0`, in + /// `-32767.0 / 32768.0..=32767.0 / 32768.0`. Optional events, empty blocks + /// and drain cancellation follow `process`. The call uses the preallocated + /// Rust `f32` buffers again. + /// + /// # Errors + /// + /// The method throws if the channel lengths are not equal, if the block is + /// larger than `maxBlockFrames` or if an event is not valid. If an error + /// occurs, the output buffers and the DSP state do not change. + #[wasm_bindgen(js_name = processF32)] + pub fn process_f32( + &mut self, + input: &Float32Array, + left: &Float32Array, + right: &Float32Array, + 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)?; + self.check_frames(frames)?; + let events = decode_events(events)?; + input.copy_to(&mut self.float_input[..frames]); + self.processor.process_planar_f32( + &self.float_input[..frames], + &mut self.float_left[..frames], + &mut self.float_right[..frames], + &events.0, + )?; + left.copy_from(&self.float_left[..frames]); + right.copy_from(&self.float_right[..frames]); + Ok(()) + } + + /// Replaces the audio in a mono `Float32Array` with the stereo downmix. + /// + /// Input quantization, fixed-point downmix, `1.0 / 32768.0` output scale, + /// events and drain cancellation follow `processF32` and `processMono`. + /// Peak feedback measures the stereo output before the downmix. + /// + /// # Errors + /// + /// The method throws if the block is too large or an event is not valid. + /// It throws before the audio of the caller or the DSP state changes. + #[wasm_bindgen(js_name = processMonoF32)] + pub fn process_mono_f32( + &mut self, + audio: &Float32Array, + events: Option>, + ) -> Result<(), JsError> { + let frames = audio.length() as usize; + self.check_frames(frames)?; + let events = decode_events(events)?; + audio.copy_to(&mut self.float_input[..frames]); + self.processor + .process_mono_in_place_f32(&mut self.float_input[..frames], &events.0)?; + audio.copy_from(&self.float_input[..frames]); + Ok(()) + } + /// Starts a finite tail budget and returns its frame count as a number. /// /// Call this method one time after the final input block. Another call @@ -354,6 +433,56 @@ impl WasmProcessor { Ok(count) } + /// Renders stereo tail frames into `Float32Array` buffers of equal length. + /// + /// Each rendered PCM sample scales by `1.0 / 32768.0`, and unused frames + /// fill with `0.0`. Return values, empty buffers and reset on completion + /// follow `drain`. + /// + /// # Errors + /// + /// The method throws if the channel lengths are not equal or if a block is + /// larger than `maxBlockFrames`. After an error, both output arrays and the + /// drain state do not change. + #[wasm_bindgen(js_name = drainF32)] + pub fn drain_f32( + &mut self, + left: &Float32Array, + right: &Float32Array, + ) -> Result { + let frames = left.length() as usize; + Error::check_length(frames, right.length() as usize)?; + self.check_frames(frames)?; + let count = self.processor.drain_planar_f32( + &mut self.float_left[..frames], + &mut self.float_right[..frames], + )?; + left.copy_from(&self.float_left[..frames]); + right.copy_from(&self.float_right[..frames]); + Ok(count) + } + + /// Renders a mono `Float32Array` tail block and returns its frame count. + /// + /// Each rendered frame uses the fixed-point mono downmix scaled by + /// `1.0 / 32768.0`, and unused samples fill with `0.0`. Completion and + /// feedback follow `drainMono`. + /// + /// # Errors + /// + /// If the block is larger than `maxBlockFrames`, this method throws before + /// the output or the state changes. + #[wasm_bindgen(js_name = drainMonoF32)] + pub fn drain_mono_f32(&mut self, audio: &Float32Array) -> Result { + let frames = audio.length() as usize; + self.check_frames(frames)?; + let count = self + .processor + .drain_mono_f32(&mut self.float_input[..frames])?; + audio.copy_from(&self.float_input[..frames]); + Ok(count) + } + /// Returns a new feedback object and does not clear the peak window. /// /// `processedFrames` is a `bigint`, so its 64-bit count stays exact. @@ -522,6 +651,17 @@ fn pcm_buffer(frames: usize) -> Result, JsError> { Ok(buffer) } +/// Allocates `f32` audio storage that contains zeros. +/// +/// If the capacity overflows or the allocation fails, this function returns a +/// JavaScript error. It does not panic. +fn float_buffer(frames: usize) -> Result, JsError> { + let mut buffer = Vec::new(); + buffer.try_reserve_exact(frames)?; + buffer.resize(frames, 0.0); + Ok(buffer) +} + /// Serializes the bounded Wasm frame count as a JavaScript number. /// /// The serializer of the feedback structure keeps its other counter, a `u64`, From 625239edc9997331c5c56cb2bb3cd29fbc60b1e0 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Sat, 21 Nov 2026 02:07:32 +0000 Subject: [PATCH 3/3] feat(npm): add the AudioWorklet module and Wasm compiler - Export loadTuneletModule from the package entry point. - Reject loadTunelet without a source in AudioWorkletGlobalScope. - Add UTF-8 text codecs for AudioWorkletGlobalScope. - Add TuneletWorkletProcessor with initSync and MessagePort controls. - Add TuneletWorkletNode and createTuneletWorkletNode. - Export the ./worklet and ./worklet-processor subpaths. - Document the Float32 APIs, AudioWorklet and glue limits. --- README.md | 155 ++++++--- package.json | 13 +- src/index.ts | 182 ++++++++-- src/text-codec.ts | 232 +++++++++++++ src/worklet-processor.ts | 707 +++++++++++++++++++++++++++++++++++++++ src/worklet.ts | 365 ++++++++++++++++++++ tsconfig.json | 7 +- 7 files changed, 1579 insertions(+), 82 deletions(-) create mode 100644 src/text-codec.ts create mode 100644 src/worklet-processor.ts create mode 100644 src/worklet.ts diff --git a/README.md b/README.md index d2993dc..bd13b36 100644 --- a/README.md +++ b/README.md @@ -50,8 +50,8 @@ browsers and Node.js. - **No dependencies**: The default Rust build has no dependencies and uses only safe Rust. -The input is mono signed 16-bit PCM at 44.1 kHz or 48 kHz. The output is -stereo or mono 16-bit PCM. +The input is mono signed 16-bit PCM or 32-bit float audio at 44.1 kHz or +48 kHz. The output is stereo or mono 16-bit PCM or 32-bit float audio. ## Installation @@ -143,16 +143,31 @@ const config = defaultConfig(); config.resynthesis.pitchRatio = 1.25; const processor = new Tunelet(48000, 1024, config); -const input = new Int16Array(1024); -const left = new Int16Array(1024); -const right = new Int16Array(1024); -// Fill input with mono PCM before each call; reuse all three arrays. -processor.process(input, left, right); +const input = new Float32Array(1024); +const left = new Float32Array(1024); +const right = new Float32Array(1024); +// Fill input with mono samples in -1..=1; reuse all three arrays. +processor.processF32(input, left, right); -// After all processing and optional drain calls: +// After all blocks and optional drainF32 calls: processor.free(); ``` +### Web Audio + +```ts +import { defaultConfig, loadTunelet } from "tunelet"; +import { createTuneletWorkletNode } from "tunelet/worklet"; + +const context = new AudioContext({ sampleRate: 48000 }); +await loadTunelet(); +const config = defaultConfig(); +config.resynthesis.correction.retuneMs = 20; + +const node = await createTuneletWorkletNode(context, { config }); +sourceNode.connect(node).connect(context.destination); +``` + ## Signal chain The processor sends each sample through these stages, in this order. The @@ -209,11 +224,19 @@ processor. Select the process function for your output layout: -| Output layout | Function for input | Function for the tail | -| ------------------------------ | ----------------------- | --------------------- | -| `[[i16; 2]]` stereo frames | `process` | `drain` | -| Separate left and right slices | `process_planar` | `drain_planar` | -| Mono slice | `process_mono_in_place` | `drain_mono` | +| Output layout | Function for input | Function for the tail | +| --------------------------------- | --------------------------- | --------------------- | +| `[[i16; 2]]` stereo frames | `process` | `drain` | +| `[[f32; 2]]` stereo frames | `process_f32` | `drain_f32` | +| Separate `i16` left/right slices | `process_planar` | `drain_planar` | +| Separate `f32` left/right slices | `process_planar_f32` | `drain_planar_f32` | +| Mono `i16` slice | `process_mono_in_place` | `drain_mono` | +| Mono `f32` slice | `process_mono_in_place_f32` | `drain_mono_f32` | + +Each `f32` input sample maps `NaN` to zero, clamps to `-1.0..=1.0` and +quantizes into the fixed-point chain. Each rendered `i16` sample scales by +`1.0 / 32768.0` into `f32` output, and unused `f32` drain frames contain +`0.0`. These rules apply to each call: @@ -352,21 +375,28 @@ For `wasm32-unknown-unknown`, the optional `wasm` feature of the crate gives JavaScript bindings and generated TypeScript declarations. The npm package contains these bindings. -The npm package is one ES module for both browsers and Node.js. It contains -these items: +The npm package has zero runtime dependencies and uses ES modules for both +browsers and Node.js. It contains these items: - One Wasm binary. -- The generated bindings. -- A shared `loadTunelet` entry point. +- The generated bindings (`tunelet` and `tunelet/wasm`). +- The main-thread loaders (`loadTunelet` and `loadTuneletModule`). +- The `AudioWorklet` node and processor (`tunelet/worklet` and + `tunelet/worklet-processor`). ### Load the module -Both environments use the same imports and the same initialization call. An -import of the package does not load the binary. Call `loadTunelet()` before -you use `Tunelet` or `defaultConfig()`. +An import of the package does not load the binary. Call `loadTunelet()` before +you use `Tunelet` or `defaultConfig()`. To compile a `WebAssembly.Module` on +the main thread for `AudioWorklet` or custom instantiation, call +`loadTuneletModule()`. - Node.js reads the packaged binary from a file URL relative to the module. -- Browsers fetch the served Wasm asset. +- Browsers fetch and compile the served Wasm asset on the main thread. +- In `AudioWorkletGlobalScope`, a call to `loadTunelet()` or + `loadTuneletModule()` with no source rejects with an `Error` and does not + call `fetch()`. Give a `WebAssembly.Module` or `BufferSource`, or call + `initSync({ module })`. Concurrent calls share one initialization promise. The package keeps the result of a successful initialization. If a load fails, the promise rejects, @@ -406,33 +436,59 @@ page that opens the JavaScript. ### TypeScript API -| Operation | TypeScript API | -| --------------------------------- | -------------------------------------------------------- | -| Shared initialization | `loadTunelet(source?)` | -| Mono PCM to planar stereo | `process(input, left, right, events?)` | -| In-place mono downmix | `processMono(audio, events?)` | -| Configuration | `config()`, `setConfig(config)`, `defaultConfig()` | -| Information about the preparation | `sampleRate`, `maxBlockFrames`, `latencyFrames` | -| Feedback | `feedback()`, `takeFeedback()` | -| Telemetry | `telemetry()`, `takeTelemetry()` | -| Formant envelopes | `formantEnvelope(maxFrequencyHz, input, output)` | -| Finite tail | `beginDrain()`, `drain(left, right)`, `drainMono(audio)` | -| Configured tail budget | `tailFrames()` | -| Reset or release memory | `reset()`, `free()` | +| Operation | TypeScript API | +| --------------------------------- | ---------------------------------------------------------------- | +| Shared initialization | `loadTunelet(source?)`, `loadTuneletModule(source?)` | +| Web Audio worklet node | `createTuneletWorkletNode(context, options?)` | +| Mono PCM to planar stereo | `process(input, left, right, events?)` | +| Mono Float32 to planar stereo | `processF32(input, left, right, events?)` | +| In-place mono downmix | `processMono(audio, events?)`, `processMonoF32(audio, events?)` | +| Configuration | `config()`, `setConfig(config)`, `defaultConfig()` | +| Information about the preparation | `sampleRate`, `maxBlockFrames`, `latencyFrames` | +| Feedback | `feedback()`, `takeFeedback()` | +| Telemetry | `telemetry()`, `takeTelemetry()` | +| Formant envelopes | `formantEnvelope(maxFrequencyHz, input, output)` | +| Finite PCM tail | `beginDrain()`, `drain(left, right)`, `drainMono(audio)` | +| Finite Float32 tail | `beginDrain()`, `drainF32(left, right)`, `drainMonoF32(audio)` | +| Configured tail budget | `tailFrames()` | +| Reset or release memory | `reset()`, `free()` | ### Audio buffers -All audio buffers are `Int16Array` buffers, and they must fit in the prepared -frame limit. These rules apply: +Audio buffers are `Int16Array` or `Float32Array` buffers, and they must fit in +the prepared frame limit. `Float32Array` inputs map `NaN` to zero, clamp values +to `-1.0..=1.0` and quantize into the fixed-point chain. `Float32Array` outputs +scale each rendered `i16` sample by `1.0 / 32768.0`, and unused drain frames +contain `0.0`. + +These rules apply to all audio buffers: - Stereo output arrays must not overlap. - The input can overlap an output, because the binding copies the input first. -- Buffers must stay attached during each call. - -Web Audio uses Float32 samples, which you must convert to and from 16-bit -PCM. This package does not install an AudioWorklet or an integration with an -audio device. +- Buffers must stay attached until each call is complete. + +### AudioWorklet + +`tunelet/worklet` exports `createTuneletWorkletNode` and `TuneletWorkletNode`. +`tunelet/worklet-processor` exports `TuneletWorkletProcessor` and registers +`"tunelet-processor"` in `AudioWorkletGlobalScope`. + +`createTuneletWorkletNode(context, options?)` checks that `context.sampleRate` +is `44100` or `48000` before it loads Wasm or registers the worklet module. It +compiles the Wasm binary on the main thread, registers the worklet module one +time on `context` and passes the `WebAssembly.Module` in `processorOptions`. +Inside the worklet, `TuneletWorkletProcessor` initializes synchronously with +`initSync` and processes `Float32Array` inputs in chunks of at most +`maxBlockFrames` frames (128 by default). + +Mono inputs go directly to the processor, stereo inputs mix to mono with equal +weights and disconnected inputs write zeros. `TuneletWorkletNode` provides +Promise methods over `MessagePort`: `config()`, `setConfig(config)`, +`sendMidi(event, offset?)`, `sendCorrectionMidi(event, offset?)`, +`sendEvents(events)`, `beginDrain()`, `tailFrames()`, `feedback()`, +`takeFeedback()`, `telemetry()`, `takeTelemetry()`, +`formantEnvelope(maxFrequencyHz, points)`, `reset()` and `dispose()`. ### Configuration objects @@ -495,10 +551,10 @@ call with more points than before reserve memory. ### Memory allocation -The constructor allocates reusable PCM buffers. A successful call that -processes audio without events does not allocate new Rust PCM storage. -However, the call copies the audio across the boundary between JavaScript and -Wasm. These items can allocate: +The constructor allocates reusable `Vec` and `Vec` buffers in Wasm +memory. A successful call that processes audio without events does not allocate +new Rust audio storage. However, the call copies the audio across the boundary +between JavaScript and Wasm. These items can allocate: - Object conversion. - Supplied events. @@ -506,10 +562,11 @@ Wasm. These items can allocate: - Feedback and telemetry. - The formant envelopes. -The generated glue can also make temporary views. This binding is for general -use, and it does not guarantee hard real-time behavior for allocation or -scheduling. Drain completion and reset keep the same state as the equivalent -Rust functions. +The generated JavaScript glue can also make temporary views when it copies +data. Thus, this generic binding does not guarantee an `AudioWorklet` callback +that is free of JavaScript allocation. Drain completion and reset keep the same +state as the equivalent Rust functions. When you do not need a processor any +more, call `free()` on `Tunelet` or `dispose()` on `TuneletWorkletNode`. ## Build from source diff --git a/package.json b/package.json index 511ddfa..b119698 100644 --- a/package.json +++ b/package.json @@ -15,6 +15,14 @@ "types": "./dist/index.d.ts", "import": "./dist/index.js" }, + "./worklet": { + "types": "./dist/worklet.d.ts", + "import": "./dist/worklet.js" + }, + "./worklet-processor": { + "types": "./dist/worklet-processor.d.ts", + "import": "./dist/worklet-processor.js" + }, "./wasm": { "types": "./pkg/tunelet.d.ts", "import": "./pkg/tunelet.js" @@ -26,7 +34,10 @@ "pkg/tunelet.d.ts", "pkg/tunelet_bg.wasm" ], - "sideEffects": false, + "sideEffects": [ + "./dist/text-codec.js", + "./dist/worklet-processor.js" + ], "scripts": { "build": "npm run build:wasm && npm run build:ts", "build:wasm": "wasm-pack build --target web --out-dir pkg --release --no-opt --features wasm --locked", diff --git a/src/index.ts b/src/index.ts index da35a57..641baed 100644 --- a/src/index.ts +++ b/src/index.ts @@ -2,11 +2,12 @@ * 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. + * configuration. To compile a `WebAssembly.Module` for `tunelet/worklet`, call + * `loadTuneletModule()` on the main thread. 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. */ +import "./text-codec.js"; import init, { initSync } from "../pkg/tunelet.js"; import type { InitInput, InitOutput } from "../pkg/tunelet.js"; @@ -15,35 +16,34 @@ export * from "../pkg/tunelet.js"; /** The shared initialization promise, which a failure clears. */ let initialization: Promise | undefined; +/** The cached compilation promise for the packaged Wasm binary. */ +let packagedModule: Promise | undefined; + /** * Initializes the Wasm module one time for this imported package instance. * - * If you give no argument, the function finds the packaged binary relative to - * this module. Node.js reads a `file:` URL, and browsers fetch the served - * asset. An import of the package does not load Wasm. In browsers, serve the - * assets over HTTP(S), or give the bytes or a compiled module as the source. + * If you give no argument on the main thread or in Node.js, the function + * compiles and instantiates the packaged binary relative to this module. + * Node.js reads a `file:` URL, and browsers fetch the served asset. If you + * call `loadTunelet()` with no argument in `AudioWorkletGlobalScope`, the + * returned promise rejects with an `Error` and does not call `fetch()`. * - * For a custom deployment, you can give one of these sources: + * For a custom deployment or an `AudioWorkletGlobalScope`, you can give one of + * these sources: * - * - A URL. - * - A fetch Response. - * - A byte buffer (BufferSource). - * - A compiled WebAssembly.Module. + * - A URL (on the main thread or in Node.js). + * - A fetch Response (on the main thread). + * - A byte buffer (`BufferSource`). + * - A compiled `WebAssembly.Module`. * - A promise for one of these. * - * A string source obeys fetch rules. For a Node.js `file:` source, use a - * URL object. A compiled module must use imports that agree with the packaged - * bindings. - * * Concurrent calls share one promise, and the first call selects the source. * After a successful initialization, later calls use it again and do not load * Wasm again, whatever their arguments are. If an attempt fails, the promise * rejects and the function clears the cached promise. Then you can try again. - * File, network and Wasm errors go to the caller. The function does not try a - * different load method after an error. * * @param source The optional Wasm source. The default is the binary in this - * package. + * package on the main thread or in Node.js. * @returns The initialized Wasm exports. Use the re-exported `Tunelet` class * for processors. */ @@ -57,24 +57,144 @@ export function loadTunelet( return initialization; } +/** + * Loads or compiles a `WebAssembly.Module` on the main thread or in Node.js. + * + * Give the returned `WebAssembly.Module` to `tunelet/worklet`, to + * `initSync({ module })` or to `loadTunelet(module)`. If you omit `source`, + * this function compiles the packaged binary one time and caches the promise. + * If compilation fails, the function clears the cached promise so you can try + * again. + * + * If you call `loadTuneletModule()` with no argument in + * `AudioWorkletGlobalScope`, the returned promise rejects with an `Error`. + * + * @param source The optional Wasm source. The default is the binary in this + * package. + * @returns The compiled `WebAssembly.Module`. + */ +export function loadTuneletModule( + source?: InitInput | Promise, +): Promise { + if (source !== undefined) { + return compileSource(source); + } + packagedModule ??= compileDefaultModule().catch((error: unknown) => { + packagedModule = undefined; + throw error; + }); + return packagedModule; +} + +/** Checks if the current global scope is an `AudioWorkletGlobalScope`. */ +function isAudioWorkletScope(): boolean { + const scope = globalThis as { + AudioWorkletGlobalScope?: abstract new () => object; + }; + return ( + typeof scope.AudioWorkletGlobalScope === "function" && + globalThis instanceof scope.AudioWorkletGlobalScope + ); +} + +/** Reads a `file:` URL with the Node.js file system module. */ +async function readFileUrl(url: URL): Promise { + // Keep the Node.js built-in module out of browser bundles. The runtime + // import runs only for `file:` URLs. + const moduleName = "node:fs/promises"; + const fs: typeof import("node:fs/promises") = await import( + /* webpackIgnore: true */ /* @vite-ignore */ moduleName + ); + return fs.readFile(url); +} + +/** Compiles a Wasm `Response` through `WebAssembly.compileStreaming` when available. */ +async function compileResponse( + response: Response, +): Promise { + if (!response.ok) { + throw new Error( + `Failed to fetch Wasm: ${response.status} ${response.statusText} from '${response.url}'`, + ); + } + if (typeof WebAssembly.compileStreaming === "function") { + const contentType = response.headers.get("Content-Type") ?? ""; + if (contentType.toLowerCase().includes("application/wasm")) { + return WebAssembly.compileStreaming(response); + } + } + return WebAssembly.compile(await response.arrayBuffer()); +} + +/** Compiles the packaged Wasm binary from a `file:` or HTTP(S) URL. */ +async function compileDefaultModule(): Promise { + if (isAudioWorkletScope()) { + throw new Error( + "loadTuneletModule() without a source cannot run in AudioWorkletGlobalScope because fetch() is unavailable. Compile the module on the main thread and pass it in processorOptions.", + ); + } + return compileInput(new URL("../pkg/tunelet_bg.wasm", import.meta.url)); +} + +/** Resolves a custom `source` and compiles it to a `WebAssembly.Module`. */ +async function compileSource( + source: InitInput | Promise, +): Promise { + return compileInput(await source); +} + +/** Compiles one resolved `InitInput` into a `WebAssembly.Module`. */ +async function compileInput(input: InitInput): Promise { + if (input instanceof WebAssembly.Module) { + return input; + } + if (input instanceof ArrayBuffer || ArrayBuffer.isView(input)) { + return WebAssembly.compile(input as BufferSource); + } + if (input instanceof URL && input.protocol === "file:") { + const bytes = await readFileUrl(input); + return WebAssembly.compile(bytes as unknown as BufferSource); + } + if (typeof Response === "function" && input instanceof Response) { + return compileResponse(input); + } + if (typeof fetch !== "function") { + throw new Error( + "fetch() is not available in this scope. Give a WebAssembly.Module or BufferSource instead.", + ); + } + return compileResponse(await fetch(input as RequestInfo | URL)); +} + /** Awaits the source one time, then initializes the Wasm module from it. */ async function initialize( source: InitInput | Promise | undefined, ): Promise { - const input = - source === undefined - ? new URL("../pkg/tunelet_bg.wasm", import.meta.url) - : await source; + if (source === undefined) { + if (isAudioWorkletScope()) { + throw new Error( + "loadTunelet() without a source cannot run in AudioWorkletGlobalScope because fetch() is unavailable. Compile the module on the main thread with loadTuneletModule(), or call initSync({ module }).", + ); + } + const module = await loadTuneletModule(); + return init({ module_or_path: module }); + } + + const input = await source; if (input instanceof URL && input.protocol === "file:") { - // Keep the Node.js built-in module out of browser bundles. TypeScript - // removes the type-only import. The runtime import runs only for `file:` - // URLs. - const moduleName = "node:fs/promises"; - const fs: typeof import("node:fs/promises") = await import( - /* webpackIgnore: true */ /* @vite-ignore */ moduleName + return initSync({ module: (await readFileUrl(input)) as unknown as BufferSource }); + } + + if ( + typeof fetch !== "function" && + (typeof input === "string" || + (typeof URL === "function" && input instanceof URL) || + (typeof Request === "function" && input instanceof Request)) + ) { + throw new Error( + "fetch() is not available in this scope. Give a WebAssembly.Module or BufferSource instead.", ); - return initSync({ module: await fs.readFile(input) }); } return init({ module_or_path: input }); diff --git a/src/text-codec.ts b/src/text-codec.ts new file mode 100644 index 0000000..8e85e8f --- /dev/null +++ b/src/text-codec.ts @@ -0,0 +1,232 @@ +/** + * Installs UTF-8 `TextDecoder` and `TextEncoder` in `AudioWorkletGlobalScope` + * before the generated `wasm-bindgen` module runs. + * + * Browsers expose `TextDecoder` and `TextEncoder` on `Window` and `Worker`, + * but omit them from `AudioWorkletGlobalScope`. If the host already defines + * them, this module does nothing. + */ + +interface TextCodecGlobal { + TextDecoder?: unknown; + TextEncoder?: unknown; +} + +class WorkletTextDecoder { + readonly encoding = "utf-8"; + readonly fatal: boolean; + readonly ignoreBOM: boolean; + + constructor( + label = "utf-8", + options?: { fatal?: boolean; ignoreBOM?: boolean }, + ) { + const normalized = String(label).trim().toLowerCase(); + if ( + normalized !== "utf-8" && + normalized !== "utf8" && + normalized !== "unicode-1-1-utf-8" + ) { + throw new RangeError(`Unsupported encoding label: ${label}`); + } + this.fatal = Boolean(options?.fatal); + this.ignoreBOM = Boolean(options?.ignoreBOM); + } + + decode(input?: BufferSource): string { + if (input === undefined) { + return ""; + } + const bytes = ArrayBuffer.isView(input) + ? new Uint8Array(input.buffer, input.byteOffset, input.byteLength) + : new Uint8Array(input); + let index = 0; + if ( + !this.ignoreBOM && + bytes.length >= 3 && + bytes[0] === 0xef && + bytes[1] === 0xbb && + bytes[2] === 0xbf + ) { + index = 3; + } + + let output = ""; + const units: number[] = []; + const flush = (): void => { + if (units.length > 0) { + output += String.fromCharCode(...units); + units.length = 0; + } + }; + const invalid = (): void => { + if (this.fatal) { + throw new TypeError("Invalid UTF-8 byte sequence"); + } + units.push(0xfffd); + }; + + while (index < bytes.length) { + const b0 = bytes[index++]; + if (b0 < 0x80) { + units.push(b0); + } else if (b0 >= 0xc2 && b0 <= 0xdf) { + if (index >= bytes.length) { + invalid(); + break; + } + const b1 = bytes[index]; + if ((b1 & 0xc0) !== 0x80) { + invalid(); + } else { + index++; + units.push(((b0 & 0x1f) << 6) | (b1 & 0x3f)); + } + } else if (b0 >= 0xe0 && b0 <= 0xef) { + if (index + 1 >= bytes.length) { + invalid(); + break; + } + const b1 = bytes[index]; + const b2 = bytes[index + 1]; + const badLead = + (b0 === 0xe0 && b1 < 0xa0) || (b0 === 0xed && b1 >= 0xa0); + if (badLead || (b1 & 0xc0) !== 0x80 || (b2 & 0xc0) !== 0x80) { + invalid(); + } else { + index += 2; + units.push(((b0 & 0x0f) << 12) | ((b1 & 0x3f) << 6) | (b2 & 0x3f)); + } + } else if (b0 >= 0xf0 && b0 <= 0xf4) { + if (index + 2 >= bytes.length) { + invalid(); + break; + } + const b1 = bytes[index]; + const b2 = bytes[index + 1]; + const b3 = bytes[index + 2]; + const bad4 = + (b0 === 0xf0 && b1 < 0x90) || (b0 === 0xf4 && b1 >= 0x90); + if ( + bad4 || + (b1 & 0xc0) !== 0x80 || + (b2 & 0xc0) !== 0x80 || + (b3 & 0xc0) !== 0x80 + ) { + invalid(); + } else { + index += 3; + const cp = + (((b0 & 0x07) << 18) | + ((b1 & 0x3f) << 12) | + ((b2 & 0x3f) << 6) | + (b3 & 0x3f)) - + 0x10000; + units.push(0xd800 + (cp >> 10), 0xdc00 + (cp & 0x3ff)); + } + } else { + invalid(); + } + if (units.length >= 4096) { + flush(); + } + } + flush(); + return output; + } +} + +class WorkletTextEncoder { + readonly encoding = "utf-8"; + + encode(input = ""): Uint8Array { + const out: number[] = []; + for (let i = 0; i < input.length; i++) { + const code = input.charCodeAt(i); + if (code < 0x80) { + out.push(code); + } else if (code < 0x800) { + out.push(0xc0 | (code >> 6), 0x80 | (code & 0x3f)); + } else if (code >= 0xd800 && code <= 0xdbff && i + 1 < input.length) { + const next = input.charCodeAt(i + 1); + if (next >= 0xdc00 && next <= 0xdfff) { + const cp = ((code - 0xd800) << 10) + (next - 0xdc00) + 0x10000; + out.push( + 0xf0 | (cp >> 18), + 0x80 | ((cp >> 12) & 0x3f), + 0x80 | ((cp >> 6) & 0x3f), + 0x80 | (cp & 0x3f), + ); + i++; + } else { + out.push(0xef, 0xbf, 0xbd); + } + } else if (code >= 0xd800 && code <= 0xdfff) { + out.push(0xef, 0xbf, 0xbd); + } else { + out.push( + 0xe0 | (code >> 12), + 0x80 | ((code >> 6) & 0x3f), + 0x80 | (code & 0x3f), + ); + } + } + return new Uint8Array(out); + } + + encodeInto( + source: string, + destination: Uint8Array, + ): { read: number; written: number } { + let read = 0; + let written = 0; + while (read < source.length) { + const code = source.charCodeAt(read); + if (code < 0x80) { + if (written + 1 > destination.length) break; + destination[written++] = code; + read += 1; + } else if (code < 0x800) { + if (written + 2 > destination.length) break; + destination[written++] = 0xc0 | (code >> 6); + destination[written++] = 0x80 | (code & 0x3f); + read += 1; + } else if (code >= 0xd800 && code <= 0xdbff && read + 1 < source.length) { + const next = source.charCodeAt(read + 1); + if (next >= 0xdc00 && next <= 0xdfff) { + if (written + 4 > destination.length) break; + const cp = ((code - 0xd800) << 10) + (next - 0xdc00) + 0x10000; + destination[written++] = 0xf0 | (cp >> 18); + destination[written++] = 0x80 | ((cp >> 12) & 0x3f); + destination[written++] = 0x80 | ((cp >> 6) & 0x3f); + destination[written++] = 0x80 | (cp & 0x3f); + read += 2; + } else { + if (written + 3 > destination.length) break; + destination[written++] = 0xef; + destination[written++] = 0xbf; + destination[written++] = 0xbd; + read += 1; + } + } else { + if (written + 3 > destination.length) break; + const val = code >= 0xd800 && code <= 0xdfff ? 0xfffd : code; + destination[written++] = 0xe0 | (val >> 12); + destination[written++] = 0x80 | ((val >> 6) & 0x3f); + destination[written++] = 0x80 | (val & 0x3f); + read += 1; + } + } + return { read, written }; + } +} + +const codecGlobal = globalThis as unknown as TextCodecGlobal; +if (typeof codecGlobal.TextDecoder === "undefined") { + codecGlobal.TextDecoder = WorkletTextDecoder; +} +if (typeof codecGlobal.TextEncoder === "undefined") { + codecGlobal.TextEncoder = WorkletTextEncoder; +} + +export {}; diff --git a/src/worklet-processor.ts b/src/worklet-processor.ts new file mode 100644 index 0000000..257e940 --- /dev/null +++ b/src/worklet-processor.ts @@ -0,0 +1,707 @@ +/** + * The `AudioWorkletProcessor` module for Web Audio graphs. + * + * Load this module with `audioContext.audioWorklet.addModule(...)` or with + * `createTuneletWorkletNode` from `tunelet/worklet`. The processor calls + * `initSync` with the `WebAssembly.Module` or `BufferSource` in + * `processorOptions.module` and does not call `fetch()`. + */ +import "./text-codec.js"; +import { initSync, Tunelet } from "../pkg/tunelet.js"; +import type { + Feedback, + MidiEvent, + ProcessorConfig, + SyncInitInput, + Telemetry, + TimedEvent, +} from "../pkg/tunelet.js"; + +/** The registered Web Audio processor name for `TuneletWorkletProcessor`. */ +export const TUNELET_WORKLET_PROCESSOR_NAME = "tunelet-processor"; + +/** The default maximum frame count for one internal DSP chunk. */ +const DEFAULT_MAX_BLOCK_FRAMES = 128; + +/** The options inside `AudioWorkletNodeOptions.processorOptions`. */ +export interface TuneletWorkletProcessorOptions { + /** The precompiled `WebAssembly.Module` or raw Wasm bytes for `initSync`. */ + module: SyncInitInput; + /** The maximum frame count for one DSP call. The default is 128. */ + maxBlockFrames?: number; + /** The optional initial processor configuration. */ + config?: ProcessorConfig; +} + +/** The options object that Web Audio passes to the processor constructor. */ +export interface TuneletAudioWorkletNodeInit { + /** The `Tunelet` initialization options from the main thread. */ + processorOptions?: TuneletWorkletProcessorOptions; +} + +/** The LPC formant envelopes that `formantEnvelope` writes. */ +export interface FormantEnvelopeResult { + /** `true` if the envelopes come from an active LPC synthesis filter. */ + valid: boolean; + /** The vocal-tract envelope from the LPC analysis. */ + input: Float32Array; + /** The vocal-tract envelope after the formant width and stretch controls. */ + output: Float32Array; +} + +/** A control or query message sent to `TuneletWorkletProcessor` over `port`. */ +export type TuneletWorkletRequest = + | { type: "config"; requestId?: number } + | { type: "setConfig"; requestId?: number; config: ProcessorConfig } + | { type: "midi"; requestId?: number; event: MidiEvent; offset?: number } + | { + type: "correctionMidi"; + requestId?: number; + event: MidiEvent; + offset?: number; + } + | { type: "events"; requestId?: number; events: TimedEvent[] } + | { type: "reset"; requestId?: number } + | { type: "beginDrain"; requestId?: number } + | { type: "drain"; requestId?: number } + | { type: "tailFrames"; requestId?: number } + | { type: "feedback"; requestId?: number } + | { type: "takeFeedback"; requestId?: number } + | { type: "telemetry"; requestId?: number } + | { type: "takeTelemetry"; requestId?: number } + | { + type: "formantEnvelope"; + requestId?: number; + maxFrequencyHz: number; + points: number; + } + | { type: "dispose"; requestId?: number }; + +/** A reply or event message posted from `TuneletWorkletProcessor` on `port`. */ +export type TuneletWorkletResponse = + | { type: "config"; requestId?: number; value: ProcessorConfig } + | { type: "setConfig"; requestId?: number } + | { type: "midi"; requestId?: number } + | { type: "correctionMidi"; requestId?: number } + | { type: "events"; requestId?: number } + | { type: "reset"; requestId?: number } + | { type: "beginDrain"; requestId?: number; value: number } + | { type: "drain"; requestId?: number; value: number } + | { type: "drainComplete" } + | { type: "tailFrames"; requestId?: number; value: number } + | { type: "feedback"; requestId?: number; value: Feedback } + | { type: "takeFeedback"; requestId?: number; value: Feedback } + | { type: "telemetry"; requestId?: number; value: Telemetry } + | { type: "takeTelemetry"; requestId?: number; value: Telemetry } + | { + type: "formantEnvelope"; + requestId?: number; + value: FormantEnvelopeResult; + } + | { type: "dispose"; requestId?: number } + | { type: "error"; requestId?: number; message: string }; + +/** Minimal interface of the host `AudioWorkletProcessor` base class. */ +export interface AudioWorkletProcessorBase { + /** The bidirectional `MessagePort` connected to the `AudioWorkletNode`. */ + readonly port: MessagePort; +} + +interface AudioWorkletGlobalBindings { + sampleRate?: number; + AudioWorkletProcessor?: new ( + options?: TuneletAudioWorkletNodeInit, + ) => AudioWorkletProcessorBase; + registerProcessor?: ( + name: string, + processorCtor: new ( + options?: TuneletAudioWorkletNodeInit, + ) => AudioWorkletProcessorBase, + ) => void; +} + +const workletGlobal = globalThis as unknown as AudioWorkletGlobalBindings; + +const BaseAudioWorkletProcessor: new ( + options?: TuneletAudioWorkletNodeInit, +) => AudioWorkletProcessorBase = + typeof workletGlobal.AudioWorkletProcessor === "function" + ? workletGlobal.AudioWorkletProcessor + : class { + readonly port!: MessagePort; + constructor() { + throw new Error( + "TuneletWorkletProcessor must run in AudioWorkletGlobalScope", + ); + } + }; + +/** Checks that a number is an integer in `min..=max`. */ +function isIntegerInRange(value: unknown, min: number, max: number): boolean { + return ( + typeof value === "number" && + Number.isInteger(value) && + value >= min && + value <= max + ); +} + +/** Validates a `MidiEvent` object before it enters the block queue. */ +function validateMidiEvent(event: MidiEvent): void { + if (typeof event !== "object" || event === null) { + throw new Error("MIDI message is not valid"); + } + switch (event.type) { + case "noteOn": + if ( + !isIntegerInRange(event.channel, 0, 15) || + !isIntegerInRange(event.note, 0, 127) || + !isIntegerInRange(event.velocity, 0, 127) + ) { + throw new Error("MIDI message is not valid"); + } + return; + case "noteOff": + if ( + !isIntegerInRange(event.channel, 0, 15) || + !isIntegerInRange(event.note, 0, 127) + ) { + throw new Error("MIDI message is not valid"); + } + return; + case "allNotesOff": + return; + default: + throw new Error("MIDI message is not valid"); + } +} + +/** Validates a non-negative integer frame offset. */ +function validateOffset(offset: unknown): number { + if (!isIntegerInRange(offset, 0, 0xffff_ffff)) { + throw new Error("event offset must be a non-negative integer"); + } + return offset as number; +} + +/** Converts an unknown error value to a readable message string. */ +function errorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +/** + * Processes Web Audio `Float32Array` channels with a synchronous `Tunelet` + * instance. + * + * Stereo and multi-channel inputs mix to mono with equal channel weights + * before `Tunelet` renders stereo (or mono) output. Disconnected inputs output + * silence unless a tail drain or queued control event is active. If a host + * block is larger than `maxBlockFrames`, this processor splits the block into + * chunks of at most `maxBlockFrames` frames. + */ +export class TuneletWorkletProcessor extends BaseAudioWorkletProcessor { + private readonly processor: Tunelet; + private readonly maxBlockFrames: number; + private readonly monoChunk: Float32Array; + private readonly monoChunk128: Float32Array | undefined; + private readonly silentChunk: Float32Array; + private readonly silentChunk128: Float32Array | undefined; + private pendingEvents: TimedEvent[] = []; + private draining = false; + private disposed = false; + + constructor(options?: TuneletAudioWorkletNodeInit) { + super(options); + const procOptions = options?.processorOptions; + if (!procOptions || procOptions.module === undefined || procOptions.module === null) { + throw new Error( + "TuneletWorkletProcessor requires processorOptions.module for initSync", + ); + } + const hostSampleRate = workletGlobal.sampleRate; + if (hostSampleRate !== 44100 && hostSampleRate !== 48000) { + throw new Error( + `Unsupported AudioWorklet sampleRate ${String(hostSampleRate)} Hz; sampleRate must be 44100 or 48000`, + ); + } + const maxBlockFrames = + procOptions.maxBlockFrames ?? DEFAULT_MAX_BLOCK_FRAMES; + initSync({ module: procOptions.module }); + this.processor = new Tunelet( + hostSampleRate, + maxBlockFrames, + procOptions.config, + ); + this.maxBlockFrames = this.processor.maxBlockFrames; + this.monoChunk = new Float32Array(this.maxBlockFrames); + this.silentChunk = new Float32Array(this.maxBlockFrames); + if (this.maxBlockFrames > 128) { + this.monoChunk128 = this.monoChunk.subarray(0, 128); + this.silentChunk128 = this.silentChunk.subarray(0, 128); + } + this.port.onmessage = (event: MessageEvent) => { + this.handleMessage(event.data); + }; + } + + /** Renders one Web Audio block of `Float32Array` channels. */ + process(inputs: Float32Array[][], outputs: Float32Array[][]): boolean { + if (this.disposed) { + this.clearOutputs(outputs); + return false; + } + const outputChannels = outputs[0]; + if (!outputChannels || outputChannels.length === 0) { + return true; + } + const out0 = outputChannels[0]; + const frames = out0.length; + if (frames === 0) { + return true; + } + for (let ch = 2; ch < outputChannels.length; ch++) { + outputChannels[ch].fill(0); + } + + const inputChannels = inputs[0]; + const hasConnectedInput = + inputChannels !== undefined && + inputChannels.length > 0 && + inputChannels[0].length === frames; + + if (this.draining && this.pendingEvents.length === 0) { + this.renderDrain(outputChannels, frames); + return true; + } + + if (!hasConnectedInput && this.pendingEvents.length === 0) { + for (let ch = 0; ch < outputChannels.length; ch++) { + outputChannels[ch].fill(0); + } + return true; + } + + const events = this.takeBlockEvents(frames); + this.renderProcess( + hasConnectedInput ? inputChannels : undefined, + outputChannels, + frames, + events, + ); + return true; + } + + /** Handles one control, drain or feedback message from `this.port`. */ + private handleMessage(message: TuneletWorkletRequest): void { + if (typeof message !== "object" || message === null) { + return; + } + const requestId = message.requestId; + if (this.disposed && message.type !== "dispose") { + this.postResponse({ + type: "error", + requestId, + message: "TuneletWorkletProcessor is disposed", + }); + return; + } + try { + switch (message.type) { + case "config": + this.postResponse({ + type: "config", + requestId, + value: this.processor.config(), + }); + return; + case "setConfig": + this.processor.setConfig(message.config); + this.draining = false; + this.postResponse({ type: "setConfig", requestId }); + return; + case "midi": { + const offset = validateOffset(message.offset ?? 0); + validateMidiEvent(message.event); + this.enqueueEvent({ + offset, + event: { type: "midi", value: message.event }, + }); + this.draining = false; + this.postResponse({ type: "midi", requestId }); + return; + } + case "correctionMidi": { + const offset = validateOffset(message.offset ?? 0); + validateMidiEvent(message.event); + this.enqueueEvent({ + offset, + event: { type: "correctionMidi", value: message.event }, + }); + this.draining = false; + this.postResponse({ type: "correctionMidi", requestId }); + return; + } + case "events": { + if (!Array.isArray(message.events)) { + throw new Error("events must be an array of TimedEvent objects"); + } + let previous = 0; + for (const item of message.events) { + const offset = validateOffset(item?.offset); + if (offset < previous) { + throw new Error( + "event offset is below the previous event's offset", + ); + } + if ( + item.event?.type === "midi" || + item.event?.type === "correctionMidi" + ) { + validateMidiEvent(item.event.value); + } + previous = offset; + } + for (const item of message.events) { + this.enqueueEvent(item); + } + if (message.events.length > 0) { + this.draining = false; + } + this.postResponse({ type: "events", requestId }); + return; + } + case "reset": + this.pendingEvents.length = 0; + this.draining = false; + this.processor.reset(); + this.postResponse({ type: "reset", requestId }); + return; + case "beginDrain": + case "drain": { + this.pendingEvents.length = 0; + const tailFrames = this.processor.beginDrain(); + this.draining = tailFrames > 0; + this.postResponse({ type: message.type, requestId, value: tailFrames }); + if (tailFrames === 0) { + this.postResponse({ type: "drainComplete" }); + } + return; + } + case "tailFrames": + this.postResponse({ + type: "tailFrames", + requestId, + value: this.processor.tailFrames(), + }); + return; + case "feedback": + this.postResponse({ + type: "feedback", + requestId, + value: this.processor.feedback(), + }); + return; + case "takeFeedback": + this.postResponse({ + type: "takeFeedback", + requestId, + value: this.processor.takeFeedback(), + }); + return; + case "telemetry": + this.postResponse({ + type: "telemetry", + requestId, + value: this.processor.telemetry(), + }); + return; + case "takeTelemetry": + this.postResponse({ + type: "takeTelemetry", + requestId, + value: this.processor.takeTelemetry(), + }); + return; + case "formantEnvelope": { + if (!isIntegerInRange(message.points, 0, 0x0fff_ffff)) { + throw new Error("points must be a non-negative integer"); + } + const input = new Float32Array(message.points); + const output = new Float32Array(message.points); + const valid = this.processor.formantEnvelope( + message.maxFrequencyHz, + input, + output, + ); + this.port.postMessage( + { + type: "formantEnvelope", + requestId, + value: { valid, input, output }, + } satisfies TuneletWorkletResponse, + [input.buffer, output.buffer], + ); + return; + } + case "dispose": + if (!this.disposed) { + this.pendingEvents.length = 0; + this.draining = false; + this.disposed = true; + this.processor.free(); + } + this.postResponse({ type: "dispose", requestId }); + return; + } + } catch (error: unknown) { + this.postResponse({ + type: "error", + requestId, + message: errorMessage(error), + }); + } + } + + /** Inserts one `TimedEvent` in non-decreasing offset order. */ + private enqueueEvent(item: TimedEvent): void { + const list = this.pendingEvents; + if (list.length === 0 || list[list.length - 1].offset <= item.offset) { + list.push(item); + return; + } + let index = list.length; + while (index > 0 && list[index - 1].offset > item.offset) { + index--; + } + list.splice(index, 0, item); + } + + /** Takes the queued events for a block of `frames` samples. */ + private takeBlockEvents(frames: number): TimedEvent[] | undefined { + if (this.pendingEvents.length === 0) { + return undefined; + } + const events = this.pendingEvents; + this.pendingEvents = []; + for (const item of events) { + if (item.offset >= frames) { + this.postResponse({ + type: "error", + message: `event offset ${item.offset} is outside block of ${frames} frames`, + }); + return undefined; + } + } + return events; + } + + /** Renders active or silent input in chunks of at most `maxBlockFrames`. */ + private renderProcess( + inputChannels: Float32Array[] | undefined, + outputChannels: Float32Array[], + frames: number, + events: TimedEvent[] | undefined, + ): void { + const stereoOut = outputChannels.length >= 2; + const outLeft = outputChannels[0]; + const outRight = stereoOut ? outputChannels[1] : undefined; + let eventCursor = 0; + + for (let pos = 0; pos < frames; pos += this.maxBlockFrames) { + const chunkLen = Math.min(this.maxBlockFrames, frames - pos); + const monoIn = this.prepareMonoChunk(inputChannels, pos, chunkLen, frames); + let chunkEvents: TimedEvent[] | undefined; + if (events !== undefined && eventCursor < events.length) { + const chunkEnd = pos + chunkLen; + if (pos === 0 && chunkLen === frames) { + chunkEvents = events; + eventCursor = events.length; + } else if (events[eventCursor].offset < chunkEnd) { + chunkEvents = []; + while ( + eventCursor < events.length && + events[eventCursor].offset < chunkEnd + ) { + const current = events[eventCursor]; + chunkEvents.push({ + offset: current.offset - pos, + event: current.event, + }); + eventCursor++; + } + } + } + + if (stereoOut && outRight !== undefined) { + const leftSlice = + pos === 0 && chunkLen === frames + ? outLeft + : outLeft.subarray(pos, pos + chunkLen); + const rightSlice = + pos === 0 && chunkLen === frames + ? outRight + : outRight.subarray(pos, pos + chunkLen); + this.runProcessStereo(monoIn, leftSlice, rightSlice, chunkEvents); + } else { + const monoSlice = + pos === 0 && chunkLen === frames + ? outLeft + : outLeft.subarray(pos, pos + chunkLen); + monoSlice.set(monoIn); + this.runProcessMono(monoSlice, chunkEvents); + } + } + } + + /** Calls `processF32` and isolates event payload errors from the audio graph. */ + private runProcessStereo( + input: Float32Array, + left: Float32Array, + right: Float32Array, + events: TimedEvent[] | undefined, + ): void { + if (events === undefined) { + this.processor.processF32(input, left, right); + return; + } + try { + this.processor.processF32(input, left, right, events); + } catch (error: unknown) { + this.postResponse({ type: "error", message: errorMessage(error) }); + this.processor.processF32(input, left, right); + } + } + + /** Calls `processMonoF32` and isolates event payload errors from the audio graph. */ + private runProcessMono( + audio: Float32Array, + events: TimedEvent[] | undefined, + ): void { + if (events === undefined) { + this.processor.processMonoF32(audio); + return; + } + try { + this.processor.processMonoF32(audio, events); + } catch (error: unknown) { + this.postResponse({ type: "error", message: errorMessage(error) }); + this.processor.processMonoF32(audio); + } + } + + /** Renders tail blocks across chunks until the drain budget completes. */ + private renderDrain(outputChannels: Float32Array[], frames: number): void { + const stereoOut = outputChannels.length >= 2; + const outLeft = outputChannels[0]; + const outRight = stereoOut ? outputChannels[1] : undefined; + + for (let pos = 0; pos < frames; pos += this.maxBlockFrames) { + const chunkLen = Math.min(this.maxBlockFrames, frames - pos); + const leftSlice = + pos === 0 && chunkLen === frames + ? outLeft + : outLeft.subarray(pos, pos + chunkLen); + + if (!this.draining) { + leftSlice.fill(0); + if (stereoOut && outRight !== undefined) { + const rightSlice = + pos === 0 && chunkLen === frames + ? outRight + : outRight.subarray(pos, pos + chunkLen); + rightSlice.fill(0); + } + continue; + } + + let rendered: number; + if (stereoOut && outRight !== undefined) { + const rightSlice = + pos === 0 && chunkLen === frames + ? outRight + : outRight.subarray(pos, pos + chunkLen); + rendered = this.processor.drainF32(leftSlice, rightSlice); + } else { + rendered = this.processor.drainMonoF32(leftSlice); + } + + if (rendered < chunkLen) { + this.draining = false; + this.postResponse({ type: "drainComplete" }); + } + } + } + + /** Returns a mono `Float32Array` view for one chunk without heap allocation. */ + private prepareMonoChunk( + inputChannels: Float32Array[] | undefined, + pos: number, + chunkLen: number, + totalFrames: number, + ): Float32Array { + if (inputChannels === undefined || inputChannels.length === 0) { + if (chunkLen === this.maxBlockFrames) { + return this.silentChunk; + } + if (chunkLen === 128 && this.silentChunk128 !== undefined) { + return this.silentChunk128; + } + return this.silentChunk.subarray(0, chunkLen); + } + + if (inputChannels.length === 1) { + const ch0 = inputChannels[0]; + return pos === 0 && chunkLen === totalFrames + ? ch0 + : ch0.subarray(pos, pos + chunkLen); + } + + const target = + chunkLen === this.maxBlockFrames + ? this.monoChunk + : chunkLen === 128 && this.monoChunk128 !== undefined + ? this.monoChunk128 + : this.monoChunk.subarray(0, chunkLen); + + if (inputChannels.length === 2) { + const left = inputChannels[0]; + const right = inputChannels[1]; + for (let i = 0; i < chunkLen; i++) { + target[i] = (left[pos + i] + right[pos + i]) * 0.5; + } + return target; + } + + const scale = 1 / inputChannels.length; + for (let i = 0; i < chunkLen; i++) { + let sum = 0; + for (let ch = 0; ch < inputChannels.length; ch++) { + sum += inputChannels[ch][pos + i]; + } + target[i] = sum * scale; + } + return target; + } + + /** Fills all output channels with zeros. */ + private clearOutputs(outputs: Float32Array[][]): void { + for (let i = 0; i < outputs.length; i++) { + const channels = outputs[i]; + for (let ch = 0; ch < channels.length; ch++) { + channels[ch].fill(0); + } + } + } + + /** Sends a typed response message on `this.port`. */ + private postResponse(response: TuneletWorkletResponse): void { + this.port.postMessage(response); + } +} + +if (typeof workletGlobal.registerProcessor === "function") { + workletGlobal.registerProcessor( + TUNELET_WORKLET_PROCESSOR_NAME, + TuneletWorkletProcessor, + ); +} diff --git a/src/worklet.ts b/src/worklet.ts new file mode 100644 index 0000000..4eaf429 --- /dev/null +++ b/src/worklet.ts @@ -0,0 +1,365 @@ +/** + * Main-thread Web Audio helpers for `TuneletWorkletNode`. + * + * Call `createTuneletWorkletNode(context, options)` on the main thread. The + * helper validates `context.sampleRate` (44.1 kHz or 48 kHz), compiles the + * packaged Wasm binary, registers `tunelet/worklet-processor` on the context + * and returns a live stereo `TuneletWorkletNode`. + */ +import { loadTuneletModule } from "./index.js"; +import type { + Feedback, + InitInput, + MidiEvent, + ProcessorConfig, + SyncInitInput, + Telemetry, + TimedEvent, +} from "./index.js"; +import { TUNELET_WORKLET_PROCESSOR_NAME } from "./worklet-processor.js"; +import type { + FormantEnvelopeResult, + TuneletWorkletProcessorOptions, + TuneletWorkletRequest, + TuneletWorkletResponse, +} from "./worklet-processor.js"; + +export { TUNELET_WORKLET_PROCESSOR_NAME }; +export type { + FormantEnvelopeResult, + TuneletWorkletProcessorOptions, + TuneletWorkletRequest, + TuneletWorkletResponse, +}; + +/** Options for the synchronous `new TuneletWorkletNode(context, options)` constructor. */ +export interface TuneletWorkletNodeOptions + extends Omit { + /** The compiled `WebAssembly.Module` or Wasm bytes for `initSync` in the worklet. */ + module: SyncInitInput; + /** The maximum frame count for one DSP call in the worklet. The default is 128. */ + maxBlockFrames?: number; + /** The optional initial processor configuration. */ + config?: ProcessorConfig; +} + +/** Options for `createTuneletWorkletNode(context, options)`. */ +export interface CreateTuneletWorkletNodeOptions + extends Omit { + /** An optional precompiled `WebAssembly.Module` or raw `BufferSource`. */ + module?: SyncInitInput; + /** An optional Wasm source for `loadTuneletModule` if `module` is omitted. */ + wasmSource?: InitInput | Promise; + /** An optional custom URL for the worklet processor module. */ + processorUrl?: string | URL; +} + +/** Cached `addModule` promises per `BaseAudioContext` and processor URL. */ +const registeredModules = new WeakMap< + BaseAudioContext, + Map> +>(); + +const BaseWorkletNode: typeof AudioWorkletNode = + typeof AudioWorkletNode === "function" + ? AudioWorkletNode + : (class { + constructor() { + throw new Error( + "TuneletWorkletNode requires Web Audio AudioWorkletNode support", + ); + } + } as unknown as typeof AudioWorkletNode); + +/** Rejects sample rates outside 44.1 kHz and 48 kHz before Wasm or worklet setup. */ +function validateSampleRate(sampleRate: number): void { + if (sampleRate !== 44100 && sampleRate !== 48000) { + throw new RangeError( + `Unsupported AudioContext sampleRate ${sampleRate} Hz; tunelet supports 44100 or 48000 Hz`, + ); + } +} + +/** Validates an optional `maxBlockFrames` option before worklet setup. */ +function validateMaxBlockFrames(maxBlockFrames: number | undefined): void { + if ( + maxBlockFrames !== undefined && + (!Number.isInteger(maxBlockFrames) || + maxBlockFrames < 1 || + maxBlockFrames > 0xffff_ffff) + ) { + throw new RangeError( + "maxBlockFrames must be an integer in 1..=4294967295", + ); + } +} + +/** Registers the worklet module one time per `BaseAudioContext` and URL. */ +function ensureWorkletModule( + context: BaseAudioContext, + processorUrl?: string | URL, +): Promise { + if (!context.audioWorklet) { + return Promise.reject( + new Error( + "AudioContext.audioWorklet is unavailable; use a secure context (HTTPS or localhost)", + ), + ); + } + const resolvedUrl = + processorUrl ?? new URL("./worklet-processor.js", import.meta.url); + const key = String(resolvedUrl); + let byUrl = registeredModules.get(context); + if (!byUrl) { + byUrl = new Map>(); + registeredModules.set(context, byUrl); + } + let registration = byUrl.get(key); + if (!registration) { + const currentMap = byUrl; + registration = context.audioWorklet + .addModule(resolvedUrl) + .catch((error: unknown) => { + currentMap.delete(key); + throw error; + }); + byUrl.set(key, registration); + } + return registration; +} + +interface PendingRequest { + resolve: (value: unknown) => void; + reject: (reason: unknown) => void; +} + +type TuneletRequestPayload = TuneletWorkletRequest extends infer Item + ? Item extends unknown + ? Omit + : never + : never; + +/** + * An `AudioWorkletNode` that runs `Tunelet` in the Web Audio thread. + * + * By default, the node accepts one mono or stereo input and writes one stereo + * (`[left, right]`) output. Control, MIDI, reset, drain, feedback and + * telemetry methods communicate with `TuneletWorkletProcessor` over + * `this.port`. + */ +export class TuneletWorkletNode extends BaseWorkletNode { + private nextRequestId = 1; + private readonly pending = new Map(); + private isDisposed = false; + + /** + * Compiles the Wasm module, registers the worklet module and creates a + * `TuneletWorkletNode`. + */ + static create( + context: BaseAudioContext, + options?: CreateTuneletWorkletNodeOptions, + ): Promise { + return createTuneletWorkletNode(context, options); + } + + constructor(context: BaseAudioContext, options: TuneletWorkletNodeOptions) { + validateSampleRate(context.sampleRate); + validateMaxBlockFrames(options?.maxBlockFrames); + if (!options || options.module === undefined || options.module === null) { + throw new Error( + "TuneletWorkletNode requires options.module; use createTuneletWorkletNode() to compile it automatically", + ); + } + const { module, maxBlockFrames, config, ...nodeOptions } = options; + const processorOptions: TuneletWorkletProcessorOptions = { + module, + maxBlockFrames, + config, + }; + super(context, TUNELET_WORKLET_PROCESSOR_NAME, { + numberOfInputs: 1, + numberOfOutputs: 1, + outputChannelCount: [2], + ...nodeOptions, + processorOptions, + }); + + this.port.addEventListener( + "message", + (event: MessageEvent) => { + this.handleResponse(event.data); + }, + ); + this.port.start(); + + this.addEventListener("processorerror", () => { + this.rejectAll(new Error("TuneletWorkletProcessor encountered a runtime error")); + }); + } + + /** Reads a copy of the active `ProcessorConfig` from the worklet. */ + config(): Promise { + return this.request({ type: "config" }); + } + + /** Validates and applies a complete `ProcessorConfig` in the worklet. */ + setConfig(config: ProcessorConfig): Promise { + return this.request({ type: "setConfig", config }); + } + + /** Queues a harmony `MidiEvent` for the next audio block at `offset` (default 0). */ + sendMidi(event: MidiEvent, offset = 0): Promise { + return this.request({ type: "midi", event, offset }); + } + + /** Queues a correction `MidiEvent` for the next audio block at `offset` (default 0). */ + sendCorrectionMidi(event: MidiEvent, offset = 0): Promise { + return this.request({ type: "correctionMidi", event, offset }); + } + + /** Queues a sorted `TimedEvent[]` slice for the next audio block. */ + sendEvents(events: TimedEvent[]): Promise { + return this.request({ type: "events", events }); + } + + /** Starts the finite tail drain in the worklet and returns its frame budget. */ + beginDrain(): Promise { + return this.request({ type: "beginDrain" }); + } + + /** Returns the configured tail budget in frames without starting a drain. */ + tailFrames(): Promise { + return this.request({ type: "tailFrames" }); + } + + /** Reads the current `Feedback` snapshot without clearing the peak window. */ + feedback(): Promise { + return this.request({ type: "feedback" }); + } + + /** Reads the current `Feedback` snapshot and clears the stereo peak window. */ + takeFeedback(): Promise { + return this.request({ type: "takeFeedback" }); + } + + /** Reads the current `Telemetry` snapshot without clearing peak windows. */ + telemetry(): Promise { + return this.request({ type: "telemetry" }); + } + + /** Reads the current `Telemetry` snapshot and clears its three peak windows. */ + takeTelemetry(): Promise { + return this.request({ type: "takeTelemetry" }); + } + + /** Reads the LPC analysis and synthesis formant envelopes with `points` entries. */ + formantEnvelope( + maxFrequencyHz: number, + points: number, + ): Promise { + return this.request({ + type: "formantEnvelope", + maxFrequencyHz, + points, + }); + } + + /** Resets the audio histories and feedback in the worklet. */ + reset(): Promise { + return this.request({ type: "reset" }); + } + + /** Releases the Wasm `Tunelet` instance in the worklet and stops audio output. */ + async dispose(): Promise { + if (this.isDisposed) { + return; + } + await this.request({ type: "dispose" }); + this.isDisposed = true; + this.rejectAll(new Error("TuneletWorkletNode is disposed")); + } + + /** Sends one correlated request message over `this.port`. */ + private request(payload: TuneletRequestPayload): Promise { + if (this.isDisposed) { + return Promise.reject(new Error("TuneletWorkletNode is disposed")); + } + const requestId = this.nextRequestId++; + return new Promise((resolve, reject) => { + this.pending.set(requestId, { + resolve: resolve as (value: unknown) => void, + reject, + }); + this.port.postMessage({ + ...payload, + requestId, + } as TuneletWorkletRequest); + }); + } + + /** Resolves or rejects a pending request when a reply arrives on `this.port`. */ + private handleResponse(message: TuneletWorkletResponse): void { + if ( + typeof message !== "object" || + message === null || + !("requestId" in message) || + message.requestId === undefined + ) { + return; + } + const entry = this.pending.get(message.requestId); + if (!entry) { + return; + } + this.pending.delete(message.requestId); + if (message.type === "error") { + entry.reject(new Error(message.message)); + return; + } + if ("value" in message) { + entry.resolve(message.value); + } else { + entry.resolve(undefined); + } + } + + /** Rejects all unfinished requests when the node stops or fails. */ + private rejectAll(error: Error): void { + for (const entry of this.pending.values()) { + entry.reject(error); + } + this.pending.clear(); + } +} + +/** + * Compiles the Wasm module, registers the processor module on `context` and + * returns a live `TuneletWorkletNode`. + * + * `context.sampleRate` must be 44100 or 48000. If the rate is not supported, + * this function rejects before it loads Wasm or registers the worklet module. + * + * @param context The `AudioContext` or `OfflineAudioContext` at 44.1 kHz or 48 kHz. + * @param options Optional initial configuration, block limit or custom module source. + * @returns A configured `TuneletWorkletNode` ready to connect in the audio graph. + */ +export async function createTuneletWorkletNode( + context: BaseAudioContext, + options?: CreateTuneletWorkletNodeOptions, +): Promise { + validateSampleRate(context.sampleRate); + validateMaxBlockFrames(options?.maxBlockFrames); + const { module: providedModule, wasmSource, processorUrl, ...rest } = + options ?? {}; + const [module] = await Promise.all([ + providedModule !== undefined + ? Promise.resolve(providedModule) + : loadTuneletModule(wasmSource), + ensureWorkletModule(context, processorUrl), + ]); + return new TuneletWorkletNode(context, { + ...rest, + module, + }); +} diff --git a/tsconfig.json b/tsconfig.json index 27aa560..c2e22e9 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -11,5 +11,10 @@ "rootDir": "src", "outDir": "dist" }, - "include": ["src/index.ts"] + "include": [ + "src/index.ts", + "src/text-codec.ts", + "src/worklet.ts", + "src/worklet-processor.ts" + ] }