From 3115db839d7e85ba68facde2f8e6163894e7dce1 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:17:30 +0000 Subject: [PATCH 1/2] feat: add f32 audio and drain methods to Processor and Tunelet - Add f32 process and drain methods to Processor in src/processor.rs - Quantize f32 input to symmetric i16 PCM on the stack - Divide clipped i16 and downmix output by 32768.0 for f32 calls - Reserve reusable f32 buffers in WasmProcessor::new - Add processF32, processMonoF32, drainF32 and drainMonoF32 to Tunelet - Check the Float32Array methods and types in scripts/verify-pack.mjs - Document the f32 and Float32Array methods in src/lib.rs and README.md --- README.md | 55 ++++++++------ scripts/verify-pack.mjs | 28 +++++++ src/lib.rs | 22 ++++-- src/processor.rs | 163 ++++++++++++++++++++++++++++++++++++++++ src/wasm.rs | 159 ++++++++++++++++++++++++++++++++++++--- 5 files changed, 389 insertions(+), 38 deletions(-) diff --git a/README.md b/README.md index 83a8f47..94537e7 100644 --- a/README.md +++ b/README.md @@ -216,11 +216,14 @@ 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 and right slices | `process_planar` | `drain_planar` | +| Separate `f32` left and 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` | These rules apply to each call: @@ -413,33 +416,39 @@ page that opens the JavaScript. ### TypeScript API -| Operation | TypeScript API | -| --------------------------------- | -------------------------------------------------------- | -| Shared initialization | `loadTunelet(source?)` | -| Mono PCM to planar stereo | `process(input, left, right, events?)` | -| In-place mono downmix | `processMono(audio, events?)` | -| Configuration | `config()`, `setConfig(config)`, `defaultConfig()` | -| Information about the preparation | `sampleRate`, `maxBlockFrames`, `latencyFrames` | -| Feedback | `feedback()`, `takeFeedback()` | -| Telemetry | `telemetry()`, `takeTelemetry()` | -| Formant envelopes | `formantEnvelope(maxFrequencyHz, input, output)` | -| Finite tail | `beginDrain()`, `drain(left, right)`, `drainMono(audio)` | -| Configured tail budget | `tailFrames()` | -| Reset or release memory | `reset()`, `free()` | +| Operation | TypeScript API | +| --------------------------------- | -------------------------------------------------------------- | +| Shared initialization | `loadTunelet(source?)` | +| Mono `Int16Array` to stereo | `process(input, left, right, events?)` | +| Mono `Float32Array` to stereo | `processF32(input, left, right, events?)` | +| In-place `Int16Array` mono | `processMono(audio, events?)` | +| In-place `Float32Array` mono | `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)` | +| `Int16Array` finite tail | `beginDrain()`, `drain(left, right)`, `drainMono(audio)` | +| `Float32Array` finite 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 methods accept `Int16Array` buffers or `Float32Array` buffers, and all +buffers must fit in `maxBlockFrames`. These rules apply: - 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. +For `Float32Array` input, `NaN` becomes `0`, and other values clamp to +`-1..=1`, multiply by `32767` and round to `-32767..=32767`. Each +`Float32Array` output sample divides the clipped `i16` sample or downmix by +`32768`, and unused drain frames get `0`. Web Audio channels can go directly +to `processF32` or `processMonoF32`. This package does not install an +AudioWorklet or an integration with an audio device. ### Configuration objects diff --git a/scripts/verify-pack.mjs b/scripts/verify-pack.mjs index 921fa6f..cb2d23a 100644 --- a/scripts/verify-pack.mjs +++ b/scripts/verify-pack.mjs @@ -175,6 +175,18 @@ function verifyRuntimeImport(consumerDir, packageName) { " const left = new Int16Array(128);", " const right = new Int16Array(128);", " processor.process(input, left, right);", + " processor.processMono(input);", + " processor.beginDrain();", + " assert.equal(typeof processor.drain(left, right), \"number\");", + " assert.equal(typeof processor.drainMono(input), \"number\");", + " const inputF32 = new Float32Array(128);", + " const leftF32 = new Float32Array(128);", + " const rightF32 = new Float32Array(128);", + " processor.processF32(inputF32, leftF32, rightF32);", + " processor.processMonoF32(inputF32);", + " processor.beginDrain();", + " assert.equal(typeof processor.drainF32(leftF32, rightF32), \"number\");", + " assert.equal(typeof processor.drainMonoF32(inputF32), \"number\");", "} finally {", " processor.free();", "}", @@ -219,7 +231,23 @@ function verifyTypeDeclarations(consumerDir, packageName) { " const left = new Int16Array(128);", " const right = new Int16Array(128);", " processor.process(input, left, right);", + " processor.processMono(input);", + " processor.beginDrain();", + " const drained: number = processor.drain(left, right);", + " const drainedMono: number = processor.drainMono(input);", + " const inputF32 = new Float32Array(128);", + " const leftF32 = new Float32Array(128);", + " const rightF32 = new Float32Array(128);", + " processor.processF32(inputF32, leftF32, rightF32);", + " processor.processMonoF32(inputF32);", + " processor.beginDrain();", + " const drainedF32: number = processor.drainF32(leftF32, rightF32);", + " const drainedMonoF32: number = processor.drainMonoF32(inputF32);", " processor.free();", + " void drained;", + " void drainedMono;", + " void drainedF32;", + " void drainedMonoF32;", " void rootInitSync;", " void wasmInitSync;", " void exportsFromRoot;", diff --git a/src/lib.rs b/src/lib.rs index f17bc85..ecab71f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -26,15 +26,25 @@ //! //! # Audio and timed controls //! -//! There are three process methods: -//! -//! - [`Processor::process`] writes `[left, right]` frames. -//! - [`Processor::process_planar`] writes separate channels. -//! - [`Processor::process_mono_in_place`] replaces the input with the stereo +//! Each buffer layout has an `i16` method and an `f32` method: +//! +//! - [`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. //! +//! [`Processor::drain`], [`Processor::drain_planar`] and +//! [`Processor::drain_mono`] have the equivalents [`Processor::drain_f32`], +//! [`Processor::drain_planar_f32`] and [`Processor::drain_mono_f32`]. //! These layouts do not depend on [`ResynthesisConfig::stereo_output`], which -//! controls voice panning. The output is clipped to -32767..=32767. +//! controls voice panning. The `i16` output is clipped to `-32767..=32767`. +//! For `f32` calls, `NaN` input becomes `0`, and other values clamp to +//! `-1.0..=1.0`, multiply by `32767.0` and round to `-32767..=32767`. Each +//! `f32` output sample divides the clipped `i16` sample or downmix by +//! `32768.0`, and unused drain frames get `0.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 diff --git a/src/processor.rs b/src/processor.rs index 83bccf6..19d7350 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -208,6 +208,90 @@ impl Processor { }) } + /// Processes mono `f32` audio into `[left, right]` stereo frames. + /// + /// For each input sample, `NaN` becomes `0`, and other values clamp to + /// `-1.0..=1.0`, multiply by `32767.0` and round to `-32767..=32767`. Each + /// clipped stereo `i16` sample then divides by `32768.0`, so each output + /// value is in `-32767.0 / 32768.0..=32767.0 / 32768.0`. + /// + /// The frame counts, the block limit, the events and the drain cancellation + /// obey the same rules as in [`process`](Self::process). If the call + /// succeeds, it writes all output frames. + /// + /// # Errors + /// + /// The call checks [`Error::BufferLength`] first and + /// [`Error::BlockTooLarge`] second. Then it checks [`Error::InvalidEvent`] + /// for the first invalid event. The validation of the full event slice + /// 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_into(input.len(), events, |processor, index| { + output[index] = processor.next(pcm_from_f32(input[index])).map(pcm_to_f32); + }) + } + + /// Processes mono `f32` audio into separate left and right `f32` slices. + /// + /// The three slices must have equal frame counts and fit in + /// [`PrepareConfig::max_block_frames`]. Input quantization, the output + /// range `-32767.0 / 32768.0..=32767.0 / 32768.0`, events and drain + /// cancellation are the same as in [`process_f32`](Self::process_f32). If + /// the call succeeds, it writes all output samples. + /// + /// # 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_into(input.len(), events, |processor, index| { + let frame = processor.next(pcm_from_f32(input[index])); + left[index] = pcm_to_f32(frame[0]); + right[index] = pcm_to_f32(frame[1]); + }) + } + + /// Replaces mono `f32` audio with the stereo result after the downmix. + /// + /// The method quantizes each input sample before it writes over that + /// location, as in [`process_f32`](Self::process_f32). It divides the `i16` + /// downmix of [`process_mono_in_place`](Self::process_mono_in_place) by + /// `32768.0`, so each output sample is in + /// `-32767.0 / 32768.0..=32767.0 / 32768.0`. Peak feedback measures the + /// stereo samples, and events and drain cancellation obey the same rules. + /// + /// # 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> { + self.process_into(audio.len(), events, |processor, index| { + let output = processor.next(pcm_from_f32(audio[index])); + audio[index] = pcm_to_f32(downmix(output)); + }) + } + /// Starts a tail with the current [`tail_frames`](Self::tail_frames) /// budget and returns that budget. /// @@ -288,6 +372,72 @@ impl Processor { Ok(count) } + /// Renders the next stereo tail frames as `f32` pairs and returns their + /// count. + /// + /// Call [`begin_drain`](Self::begin_drain) first. Each rendered sample is + /// in `-32767.0 / 32768.0..=32767.0 / 32768.0`, and unused frames get + /// `0.0`. Return values, empty buffers and completion are the same as in + /// [`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(pcm_to_f32); + })?; + output[count..].fill([0.0; 2]); + Ok(count) + } + + /// Renders the tail into separate `f32` output channels of equal size. + /// + /// Each rendered sample is in `-32767.0 / 32768.0..=32767.0 / 32768.0`, + /// and unused samples get `0.0`. The return values, empty buffers and + /// completion are the same as in [`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] = pcm_to_f32(frame[0]); + right[index] = pcm_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. + /// + /// The downmix and `1 / 32768` output scale are the same as in + /// [`process_mono_in_place_f32`](Self::process_mono_in_place_f32). Unused + /// samples get `0.0`. The return values, empty buffers and completion are + /// the same as in [`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] = pcm_to_f32(downmix(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 @@ -701,6 +851,19 @@ fn downmix(frame: [i16; 2]) -> i16 { ((i32::from(frame[0]) + i32::from(frame[1])) >> 1) as i16 } +/// Quantizes one `f32` sample to symmetric `-32767..=32767` PCM. +fn pcm_from_f32(sample: f32) -> i16 { + if sample.is_nan() { + return 0; + } + (f64::from(sample.clamp(-1.0, 1.0)) * 32_767.0).round() as i16 +} + +/// Divides one 16-bit PCM sample by `32768.0`. +fn pcm_to_f32(sample: i16) -> f32 { + f32::from(sample) / 32_768.0 +} + /// A snapshot of the pitch analysis and the output level that you can copy. /// /// Get it with [`Processor::feedback`] or [`Processor::take_feedback`]. The diff --git a/src/wasm.rs b/src/wasm.rs index 15262e2..a0df149 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 vocal 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 `Int16Array` PCM or mono `Float32Array` audio. 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. + input_f32: Vec, + /// The reusable `f32` buffer for the left channel, which the class copies + /// to the caller only after a successful call. + left_f32: Vec, + /// The reusable `f32` buffer for the right channel, which the class copies + /// to the caller only after a successful call. + right_f32: 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)?, + input_f32: f32_buffer(max_block_frames)?, + left_f32: f32_buffer(max_block_frames)?, + right_f32: f32_buffer(max_block_frames)?, envelope_input: Vec::new(), envelope_output: Vec::new(), }) @@ -295,6 +308,73 @@ impl WasmProcessor { Ok(()) } + /// Processes mono `Float32Array` input into left and right `Float32Array` + /// buffers of equal length. + /// + /// For each input sample, `NaN` becomes `0`, and other values clamp to + /// `-1..=1`, multiply by `32767` and round to `-32767..=32767`. Each + /// clipped stereo sample divides by `32768`, so each output value is in + /// `-32767 / 32768..=32767 / 32768`. Events, empty blocks, drain + /// cancellation and buffer reuse obey the same rules as in `process`. + /// + /// # Errors + /// + /// The method throws if the channel lengths are not equal. It also throws + /// if the block is larger than `maxBlockFrames` or an event is not valid. + /// The call checks the lengths and the block size before it decodes and + /// validates the events. 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.processor.check_block(frames)?; + let events = decode_events(events)?; + input.copy_to(&mut self.input_f32[..frames]); + self.processor.process_planar_f32( + &self.input_f32[..frames], + &mut self.left_f32[..frames], + &mut self.right_f32[..frames], + &events.0, + )?; + left.copy_from(&self.left_f32[..frames]); + right.copy_from(&self.right_f32[..frames]); + Ok(()) + } + + /// Replaces the audio in a mono `Float32Array` with the stereo downmix. + /// + /// Input quantization, `1 / 32768` output division, events and drain + /// cancellation are the same as for `processF32`. Peak feedback measures + /// the stereo output before the downmix, as in the native processor. + /// + /// # 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.processor.check_block(frames)?; + let events = decode_events(events)?; + audio.copy_to(&mut self.input_f32[..frames]); + self.processor + .process_mono_in_place_f32(&mut self.input_f32[..frames], &events.0)?; + audio.copy_from(&self.input_f32[..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 @@ -356,6 +436,56 @@ impl WasmProcessor { Ok(count) } + /// Renders stereo tail frames into `Float32Array` buffers of equal length. + /// + /// Each rendered sample is in `-32767 / 32768..=32767 / 32768`, and unused + /// output frames get `0`. The return values, empty arrays and completion + /// are the same as for `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.processor.check_block(frames)?; + let count = self + .processor + .drain_planar_f32(&mut self.left_f32[..frames], &mut self.right_f32[..frames])?; + left.copy_from(&self.left_f32[..frames]); + right.copy_from(&self.right_f32[..frames]); + Ok(count) + } + + /// Renders a mono `Float32Array` tail block and returns its frame count. + /// + /// The method fills the unused output with `0`. The downmix, the `1 / 32768` + /// output division and the peak feedback are the same as for + /// `processMonoF32`. The return values, empty arrays and completion are the + /// same as for `drain`. + /// + /// # 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.processor.check_block(frames)?; + let count = self + .processor + .drain_mono_f32(&mut self.input_f32[..frames])?; + audio.copy_from(&self.input_f32[..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. @@ -512,6 +642,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 f32_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 bc032ee7330b8600c20a0015a124dac9af7d3dca Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Tue, 24 Nov 2026 04:03:42 +0000 Subject: [PATCH 2/2] feat: expose Float32 buffers in Wasm for in-place audio - Add f32 process and drain methods to Processor - Convert f32 audio with exact i16 quantization and scale - Allocate fixed-capacity f32 buffers in WasmProcessor::new - Expose inputF32Ptr, leftF32Ptr and rightF32Ptr offsets - Add in-place Float32 process and drain methods to Tunelet - Export TuneletAudioViews to refresh detached memory views - Check Float32 runtime and type exports in verify-pack.mjs - Document Float32 view lifetimes in README and rustdoc --- README.md | 124 ++++++++++++++++++-------- scripts/verify-pack.mjs | 145 ++++++++++++++++++++++++++++-- src/index.ts | 124 +++++++++++++++++++++++++- src/lib.rs | 22 +++-- src/processor.rs | 169 +++++++++++++++++++++++++++++++++++ src/wasm.rs | 190 +++++++++++++++++++++++++++++++++++++--- 6 files changed, 705 insertions(+), 69 deletions(-) diff --git a/README.md b/README.md index 83a8f47..7b8e563 100644 --- a/README.md +++ b/README.md @@ -50,8 +50,9 @@ 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 normalized 32-bit floating-point audio +at 44.1 kHz or 48 kHz. The output is stereo or mono in 16-bit PCM or 32-bit +floating-point form. ## Installation @@ -216,11 +217,18 @@ 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` | +| Separate `i16` left and right slices | `process_planar` | `drain_planar` | +| Mono `i16` slice | `process_mono_in_place` | `drain_mono` | +| `[[f32; 2]]` stereo frames | `process_f32` | `drain_f32` | +| Separate `f32` left and right slices | `process_planar_f32` | `drain_planar_f32` | +| Mono `f32` slice | `process_mono_in_place_f32` | `drain_mono_f32` | + +The `f32` methods convert `NaN` input samples to `0`. They clamp other input +values to `-1.0..=1.0`, multiply by `32767.0` and round to `i16`. They divide +each `i16` output sample by `32768.0` and fill unused tail frames with `0.0`. These rules apply to each call: @@ -276,7 +284,7 @@ The drain gives the tail of the reverb and the voices after the last input block. To get the tail, do these steps: 1. Call `begin_drain()` one time. -2. Call `drain`, `drain_planar` or `drain_mono` until the call returns zero. +2. Call the drain method for your layout until the call returns zero. 3. From each drain call, use only the frames that the call returns. The drain fills the unused output with zeros. The drain has a finite budget, @@ -413,33 +421,72 @@ page that opens the JavaScript. ### TypeScript API -| Operation | TypeScript API | -| --------------------------------- | -------------------------------------------------------- | -| Shared initialization | `loadTunelet(source?)` | -| Mono PCM to planar stereo | `process(input, left, right, events?)` | -| In-place mono downmix | `processMono(audio, events?)` | -| Configuration | `config()`, `setConfig(config)`, `defaultConfig()` | -| Information about the preparation | `sampleRate`, `maxBlockFrames`, `latencyFrames` | -| Feedback | `feedback()`, `takeFeedback()` | -| Telemetry | `telemetry()`, `takeTelemetry()` | -| Formant envelopes | `formantEnvelope(maxFrequencyHz, input, output)` | -| Finite tail | `beginDrain()`, `drain(left, right)`, `drainMono(audio)` | -| Configured tail budget | `tailFrames()` | -| Reset or release memory | `reset()`, `free()` | +| Operation | TypeScript API | +| --------------------------------- | ---------------------------------------------------------------------- | +| Shared initialization | `loadTunelet(source?)` | +| Mono PCM to planar stereo | `process(input, left, right, events?)` | +| In-place mono PCM downmix | `processMono(audio, events?)` | +| Fixed `Float32` buffer offsets | `inputF32Ptr`, `leftF32Ptr`, `rightF32Ptr` | +| Cached `Float32` memory views | `new TuneletAudioViews(memory, processor)` | +| In-place `Float32` stereo | `processF32InPlace(frames, events?)` | +| In-place `Float32` mono downmix | `processMonoF32InPlace(frames, 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()`, `drainF32InPlace(frames)`, `drainMonoF32InPlace(frames)` | +| Configured tail budget | `tailFrames()` | +| Reset or release memory | `reset()`, `free()`, `views.dispose()` | ### Audio buffers -All audio buffers are `Int16Array` buffers, and they must fit in the prepared -frame limit. These rules apply: +The package offers copied `Int16Array` calls and in-place `Float32` calls. All +blocks must fit in `maxBlockFrames`. This package does not install an +AudioWorklet or an integration with an audio device. + +For `process`, `processMono`, `drain` and `drainMono`, pass `Int16Array` +buffers. These rules apply: - 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. +For Web Audio and zero-copy blocks, bind `TuneletAudioViews` to +`InitOutput.memory` and a `Tunelet` instance: + +```ts +const wasm = await loadTunelet(); +const processor = new Tunelet(48000, 128); +const views = new TuneletAudioViews(wasm.memory, processor); + +views.input.set(monoChunk); // monoChunk.length <= 128 +processor.processF32InPlace(monoChunk.length); +const left = views.left; +const right = views.right; + +views.dispose(); +processor.free(); +``` + +`inputF32Ptr`, `leftF32Ptr` and `rightF32Ptr` stay at fixed byte offsets until +`processor.free()`. Mono in-place calls read and write `views.input`. Stereo +in-place calls read `views.input` and write `views.left` and `views.right`. +The quantization and the output scale match the native `f32` methods. + +These lifetime rules apply to `Float32` views: + +- A new `Tunelet`, `setConfig`, `events`, feedback, telemetry or + `formantEnvelope` can grow Wasm memory and detach `memory.buffer`. +- Read `views.input` before each input write so `TuneletAudioViews` checks + `memory.buffer` and refreshes detached views. +- If an in-place call supplies `events`, read `views.left` and `views.right` + (or `views.input` for mono) again after that call. +- When you finish with the views, call `views.dispose()`. +- Do not read or write the views or pointers of an instance after + `processor.free()`, because `free()` returns those buffers to the allocator. ### Configuration objects @@ -502,21 +549,26 @@ 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 `i16` and `f32` buffers of length +`maxBlockFrames`. `processF32InPlace`, `processMonoF32InPlace`, +`drainF32InPlace` and `drainMonoF32InPlace` without `events` do not allocate +Rust storage, make JavaScript views or call JavaScript imports. If Wasm memory +does not grow, `TuneletAudioViews` also allocates no new `Float32Array` views +after construction. + +`Int16Array` audio calls copy samples across the boundary and make temporary +views in the generated glue. These operations can also allocate and grow Wasm +memory: -- Object conversion. +- A new `Tunelet` instance. +- Configuration conversion. - Supplied events. - Errors. - Feedback and telemetry. -- The formant envelopes. +- Formant envelopes with more points than before. -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. +Drain completion and reset keep the same state as the equivalent Rust +functions. ## Build from source diff --git a/scripts/verify-pack.mjs b/scripts/verify-pack.mjs index 921fa6f..cec6f6f 100644 --- a/scripts/verify-pack.mjs +++ b/scripts/verify-pack.mjs @@ -145,7 +145,7 @@ function installArchive( ); } -/** Import the installed package in Node.js and process one audio block. */ +/** Import the installed package in Node.js and verify PCM and Float32 paths. */ function verifyRuntimeImport(consumerDir, packageName) { const checkPath = path.join(consumerDir, "check.mjs"); fs.writeFileSync( @@ -161,22 +161,133 @@ function verifyRuntimeImport(consumerDir, packageName) { "assert.equal(rootModule.default, rootModule.loadTunelet);", 'assert.equal(typeof rootModule.initSync, "function");', 'assert.equal(typeof rootModule.Tunelet, "function");', + 'assert.equal(typeof rootModule.TuneletAudioViews, "function");', 'assert.equal(typeof rootModule.defaultConfig, "function");', 'assert.equal(typeof wasmModule.default, "function");', 'assert.equal(typeof wasmModule.initSync, "function");', "", "const wasmExports = await rootModule.loadTunelet();", "assert.ok(wasmExports);", + "assert.ok(wasmExports.memory instanceof WebAssembly.Memory);", "", "const config = rootModule.defaultConfig();", - "const processor = new rootModule.Tunelet(48000, 128, config);", + "config.resynthesis.formant.enabled = true;", + "config.reverb.enabled = true;", + "const pcmProcessor = new rootModule.Tunelet(48000, 128, config);", + "const f32Processor = new rootModule.Tunelet(48000, 128, config);", + "const views = new rootModule.TuneletAudioViews(wasmExports.memory, f32Processor);", "try {", - " const input = new Int16Array(128);", - " const left = new Int16Array(128);", - " const right = new Int16Array(128);", - " processor.process(input, left, right);", + " assert.equal(views.maxBlockFrames, 128);", + " assert.equal(views.disposed, false);", + " assert.equal(f32Processor.inputF32Ptr % 4, 0);", + " assert.equal(f32Processor.leftF32Ptr % 4, 0);", + " assert.equal(f32Processor.rightF32Ptr % 4, 0);", + " assert.equal(views.input.length, 128);", + " assert.equal(views.left.length, 128);", + " assert.equal(views.right.length, 128);", + " assert.equal(views.input, views.input);", + "", + " const pcmInput = new Int16Array(128);", + " const pcmLeft = new Int16Array(128);", + " const pcmRight = new Int16Array(128);", + " for (let block = 0; block < 20; block++) {", + " const f32In = views.input;", + " for (let i = 0; i < 128; i++) {", + " const sample = Math.fround(0.6 * Math.sin(((block * 128 + i) * 2 * Math.PI * 220) / 48000));", + " f32In[i] = sample;", + " pcmInput[i] = Math.round(Math.max(-1, Math.min(1, sample)) * 32767);", + " }", + " pcmProcessor.process(pcmInput, pcmLeft, pcmRight);", + " f32Processor.processF32InPlace(128);", + " const f32Left = views.left;", + " const f32Right = views.right;", + " for (let i = 0; i < 128; i++) {", + " assert.equal(f32Left[i], Math.fround(pcmLeft[i] / 32768));", + " assert.equal(f32Right[i], Math.fround(pcmRight[i] / 32768));", + " }", + " }", + "", + " const beforeBuffer = wasmExports.memory.buffer;", + " const standby = new rootModule.Tunelet(48000, 2048, config);", + " try {", + " const envIn = new Float32Array(262144);", + " const envOut = new Float32Array(262144);", + " f32Processor.formantEnvelope(12000, envIn, envOut);", + " } finally {", + " standby.free();", + " }", + " assert.notEqual(wasmExports.memory.buffer, beforeBuffer);", + "", + " const reboundInput = views.input;", + " reboundInput.fill(0.25, 0, 64);", + " f32Processor.processF32InPlace(64, [{ offset: 0, event: { type: \"outputGain\", value: 0.75 } }]);", + " pcmInput.fill(Math.round(Math.fround(0.25) * 32767), 0, 64);", + " pcmProcessor.process(", + " pcmInput.subarray(0, 64),", + " pcmLeft.subarray(0, 64),", + " pcmRight.subarray(0, 64),", + " [{ offset: 0, event: { type: \"outputGain\", value: 0.75 } }],", + " );", + " for (let i = 0; i < 64; i++) {", + " assert.equal(views.left[i], Math.fround(pcmLeft[i] / 32768));", + " assert.equal(views.right[i], Math.fround(pcmRight[i] / 32768));", + " }", + "", + " const framesBeforeError = f32Processor.feedback().processedFrames;", + " const savedLeft0 = views.left[0];", + " assert.throws(() => f32Processor.processF32InPlace(129));", + " assert.throws(() => f32Processor.processF32InPlace(-1));", + " assert.throws(() => f32Processor.processF32InPlace(1.5));", + " assert.throws(() =>", + " f32Processor.processF32InPlace(64, [{ offset: 64, event: { type: \"reset\" } }]),", + " );", + " assert.equal(f32Processor.feedback().processedFrames, framesBeforeError);", + " assert.equal(views.left[0], savedLeft0);", + "", + " pcmProcessor.beginDrain();", + " f32Processor.beginDrain();", + " const pcmCount = pcmProcessor.drain(pcmLeft, pcmRight);", + " const f32Count = f32Processor.drainF32InPlace(128);", + " assert.equal(f32Count, pcmCount);", + " for (let i = 0; i < 128; i++) {", + " assert.equal(views.left[i], Math.fround(pcmLeft[i] / 32768));", + " assert.equal(views.right[i], Math.fround(pcmRight[i] / 32768));", + " }", + "", + " const monoPcm = new rootModule.Tunelet(48000, 64, config);", + " const monoF32 = new rootModule.Tunelet(48000, 64, config);", + " const monoViews = new rootModule.TuneletAudioViews(wasmExports.memory, monoF32);", + " try {", + " const monoBuf = new Int16Array(64);", + " for (let i = 0; i < 64; i++) {", + " monoViews.input[i] = 0.5;", + " monoBuf[i] = Math.round(0.5 * 32767);", + " }", + " monoPcm.processMono(monoBuf);", + " monoF32.processMonoF32InPlace(64);", + " for (let i = 0; i < 64; i++) {", + " assert.equal(monoViews.input[i], Math.fround(monoBuf[i] / 32768));", + " }", + " monoPcm.beginDrain();", + " monoF32.beginDrain();", + " assert.equal(monoF32.drainMonoF32InPlace(64), monoPcm.drainMono(monoBuf));", + " for (let i = 0; i < 64; i++) {", + " assert.equal(monoViews.input[i], Math.fround(monoBuf[i] / 32768));", + " }", + " } finally {", + " monoViews.dispose();", + " monoPcm.free();", + " monoF32.free();", + " }", "} finally {", - " processor.free();", + " views.dispose();", + " assert.equal(views.disposed, true);", + " assert.throws(() => views.input);", + " assert.throws(() => views.left);", + " assert.throws(() => views.right);", + " assert.throws(() => views.refresh());", + " pcmProcessor.free();", + " f32Processor.free();", "}", "", ].join("\n"), @@ -201,6 +312,7 @@ function verifyTypeDeclarations(consumerDir, packageName) { " initSync as rootInitSync,", " loadTunelet as namedLoadTunelet,", " Tunelet,", + " TuneletAudioViews,", " type ProcessorConfig,", `} from ${pkgLiteral};`, "import init, {", @@ -215,11 +327,30 @@ function verifyTypeDeclarations(consumerDir, packageName) { " const exportsFromWasm: InitOutput = await init(source);", " const config: ProcessorConfig = defaultConfig();", " const processor = new Tunelet(48000, 128, config);", + " const views = new TuneletAudioViews(exportsFromRoot.memory, processor);", + " const ptrs: [number, number, number] = [", + " processor.inputF32Ptr,", + " processor.leftF32Ptr,", + " processor.rightF32Ptr,", + " ];", + " views.input.fill(0);", + " processor.processF32InPlace(128);", + " const stereoOut: [Float32Array, Float32Array] = [views.left, views.right];", + " processor.processMonoF32InPlace(128);", + " processor.beginDrain();", + " const stereoTail: number = processor.drainF32InPlace(128);", + " const monoTail: number = processor.drainMonoF32InPlace(128);", + " views.refresh();", " const input = new Int16Array(128);", " const left = new Int16Array(128);", " const right = new Int16Array(128);", " processor.process(input, left, right);", + " views.dispose();", " processor.free();", + " void ptrs;", + " void stereoOut;", + " void stereoTail;", + " void monoTail;", " void rootInitSync;", " void wasmInitSync;", " void exportsFromRoot;", diff --git a/src/index.ts b/src/index.ts index 8526d77..2b1a4e0 100644 --- a/src/index.ts +++ b/src/index.ts @@ -3,15 +3,131 @@ * * 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. + * same Wasm binary. This module exports `TuneletAudioViews` and re-exports all + * named exports from wasm-bindgen. Those exports include `Tunelet`, + * `defaultConfig`, `initSync` and the configuration, event and feedback types. */ import init from "../pkg/tunelet.js"; -import type { InitInput, InitOutput } from "../pkg/tunelet.js"; +import type { InitInput, InitOutput, Tunelet } from "../pkg/tunelet.js"; export * from "../pkg/tunelet.js"; +/** + * Cached `Float32Array` views over the in-place `Tunelet` buffers in Wasm + * linear memory. + * + * Each access to `input`, `left` or `right` checks `memory.buffer`. If Wasm + * memory grew and detached the previous `ArrayBuffer`, the helper binds the + * three fixed pointers of `processor` to the new buffer. If `memory.buffer` did + * not change, the helper returns the cached views with no allocation. + * + * Read `input` before you write input samples. If an in-place call passes + * `events`, read `left` and `right` (or `input` for mono) after that call. + * When you call `processor.free()`, also call `dispose()`. Do not use the views + * after `processor.free()`. + */ +export class TuneletAudioViews { + private readonly memory: WebAssembly.Memory; + private processor: Tunelet | null; + /** The fixed frame capacity of `input`, `left` and `right`. */ + readonly maxBlockFrames: number; + private cachedBuffer: ArrayBuffer | null = null; + private inputView: Float32Array | null = null; + private leftView: Float32Array | null = null; + private rightView: Float32Array | null = null; + + /** + * Binds `Float32Array` views for `processor` over `memory`. + * + * @param memory The `WebAssembly.Memory` from `InitOutput.memory`. + * @param processor The live `Tunelet` instance that owns the buffers. + */ + constructor(memory: WebAssembly.Memory, processor: Tunelet) { + this.memory = memory; + this.processor = processor; + this.maxBlockFrames = processor.maxBlockFrames; + this.refresh(); + } + + /** Returns `true` after `dispose()` clears the cached views. */ + get disposed(): boolean { + return this.processor === null; + } + + /** + * Returns the `Float32Array` view for mono input and in-place mono output. + * + * If `memory.buffer` changed, this getter refreshes all three views first. + */ + get input(): Float32Array { + this.refresh(); + return this.inputView!; + } + + /** + * Returns the `Float32Array` view for the left stereo output channel. + * + * If `memory.buffer` changed, this getter refreshes all three views first. + */ + get left(): Float32Array { + this.refresh(); + return this.leftView!; + } + + /** + * Returns the `Float32Array` view for the right stereo output channel. + * + * If `memory.buffer` changed, this getter refreshes all three views first. + */ + get right(): Float32Array { + this.refresh(); + return this.rightView!; + } + + /** + * If Wasm memory grew, this method refreshes the three `Float32Array` views + * from `memory.buffer`. + */ + refresh(): void { + const processor = this.processor; + if (processor === null) { + throw new Error("TuneletAudioViews is disposed"); + } + const buffer = this.memory.buffer; + if (this.cachedBuffer !== buffer) { + const frames = this.maxBlockFrames; + const inputPtr = processor.inputF32Ptr; + const leftPtr = processor.leftF32Ptr; + const rightPtr = processor.rightF32Ptr; + const input = new Float32Array(buffer, inputPtr, frames); + const left = new Float32Array(buffer, leftPtr, frames); + const right = new Float32Array(buffer, rightPtr, frames); + this.inputView = input; + this.leftView = left; + this.rightView = right; + this.cachedBuffer = buffer; + } + } + + /** Clears the cached `ArrayBuffer`, `Float32Array` views and processor link. */ + dispose(): void { + this.processor = null; + this.cachedBuffer = null; + this.inputView = null; + this.leftView = null; + this.rightView = null; + } +} + +export interface TuneletAudioViews { + [Symbol.dispose](): void; +} + +if (Symbol.dispose) { + TuneletAudioViews.prototype[Symbol.dispose] = + TuneletAudioViews.prototype.dispose; +} + /** The shared initialization promise, which a failure clears. */ let initialization: Promise | undefined; diff --git a/src/lib.rs b/src/lib.rs index f17bc85..7695ac4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -26,15 +26,19 @@ //! //! # Audio and timed controls //! -//! There are three process methods: -//! -//! - [`Processor::process`] writes `[left, right]` frames. -//! - [`Processor::process_planar`] writes separate channels. -//! - [`Processor::process_mono_in_place`] replaces the input with the stereo +//! There are three output layouts for `i16` PCM and `f32` audio: +//! +//! - [`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. PCM output is clipped to -32767..=32767. The `f32` +//! methods quantize inputs to `i16` and divide `i16` outputs by `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 +96,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. +//! reusable `i16` and `f32` buffers, and exposes fixed `f32` pointers for +//! in-place audio. 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 83bccf6..b5ba298 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -208,6 +208,90 @@ impl Processor { }) } + /// Processes mono floating-point audio into `[left, right]` stereo frames. + /// + /// If an input sample is NaN, the method uses `0` for PCM. It clamps other + /// input values to `-1.0..=1.0`, multiplies by `32767.0` and rounds to the + /// nearest `i16`. It divides each `i16` output sample by `32768.0`, so + /// output samples stay in `-32767.0 / 32768.0..=32767.0 / 32768.0`. + /// + /// Frame counts, block limits, event rules and 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 checks finish 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_into(input.len(), events, |processor, index| { + output[index] = processor + .next(quantize_f32(input[index])) + .map(sample_to_f32); + }) + } + + /// Processes mono floating-point audio into separate left and right slices. + /// + /// The three slices must have equal frame counts. Input quantization, + /// the output scale, event order and drain cancellation are the same as for + /// [`process_f32`](Self::process_f32). If the call succeeds, it writes all + /// output samples. + /// + /// # 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_into(input.len(), events, |processor, index| { + let frame = processor.next(quantize_f32(input[index])); + left[index] = sample_to_f32(frame[0]); + right[index] = sample_to_f32(frame[1]); + }) + } + + /// Replaces mono floating-point audio with the scaled stereo downmix. + /// + /// Input quantization is the same as in [`process_f32`](Self::process_f32). + /// The method computes the integer downmix as in + /// [`process_mono_in_place`](Self::process_mono_in_place), then divides by + /// `32768.0`. Peak feedback measures the stereo samples before the downmix. + /// Events and drain cancellation are the same as for + /// [`process`](Self::process). + /// + /// # 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> { + self.process_into(audio.len(), events, |processor, index| { + let output = processor.next(quantize_f32(audio[index])); + audio[index] = sample_to_f32(downmix(output)); + }) + } + /// Starts a tail with the current [`tail_frames`](Self::tail_frames) /// budget and returns that budget. /// @@ -288,6 +372,72 @@ impl Processor { Ok(count) } + /// Renders the next stereo tail frames as `f32` pairs and returns their + /// count. + /// + /// Call [`begin_drain`](Self::begin_drain) first. The method divides each + /// `i16` tail sample by `32768.0` and fills unused frames with `[0.0, 0.0]`. + /// Empty buffers, return values and completion are the same as for + /// [`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` output channels of equal size. + /// + /// The output scale and the `0.0` values in unused samples are the same as + /// in [`drain_f32`](Self::drain_f32). Empty buffers, return values and + /// completion are the same as for [`drain`](Self::drain). + /// + /// # 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 rendered frame + /// count. + /// + /// The downmix and the output scale are the same as in + /// [`process_mono_in_place_f32`](Self::process_mono_in_place_f32). The + /// method fills unused samples with `0.0`. Empty buffers, return values and + /// completion are the same as for [`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(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 @@ -701,6 +851,25 @@ fn downmix(frame: [i16; 2]) -> i16 { ((i32::from(frame[0]) + i32::from(frame[1])) >> 1) as i16 } +/// Quantizes one floating-point input sample to signed 16-bit PCM. +/// +/// If `sample` is NaN, this function returns `0`. It clamps other values to +/// `-1.0..=1.0`, multiplies by `32767.0` and rounds to the nearest integer. +#[inline] +fn quantize_f32(sample: f32) -> i16 { + if sample.is_nan() { + 0 + } else { + (sample.clamp(-1.0, 1.0) * 32_767.0).round() as i16 + } +} + +/// Divides one signed 16-bit PCM output sample by `32768.0`. +#[inline] +fn sample_to_f32(sample: i16) -> f32 { + f32::from(sample) / 32_768.0 +} + /// A snapshot of the pitch analysis and the output level that you can copy. /// /// Get it with [`Processor::feedback`] or [`Processor::take_feedback`]. The diff --git a/src/wasm.rs b/src/wasm.rs index 15262e2..6999cca 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`], three reusable +//! `i16` PCM buffers and three fixed-capacity `f32` buffers. JavaScript can +//! pass `Int16Array` buffers, which the class copies in and out on each call. +//! JavaScript can also read `inputF32Ptr`, `leftF32Ptr` and `rightF32Ptr` to +//! process `Float32Array` views over Wasm linear memory in place. //! //! Configuration objects obey these rules: //! @@ -36,10 +37,12 @@ //! - The buffers of the formant envelopes. //! - Errors. //! -//! The JavaScript glue can also make temporary views when it copies data. This -//! generic binding does not guarantee an AudioWorklet callback that is free of -//! allocation. If you do not need a processor any more, call the generated -//! `free()` method. +//! When the JavaScript glue copies `Int16Array` or `Float32Array` arguments, +//! it makes temporary views. By contrast, in-place `Float32` calls without +//! events do not allocate or call JavaScript imports. If Wasm memory grows, +//! previous `ArrayBuffer` views detach, so recheck `memory.buffer` before you +//! read or write views. If you do not need a processor any more, call `free()` +//! and do not touch its views again. use crate::{ Error, Feedback, PrepareConfig, Processor, ProcessorConfig, SampleRate, Telemetry, TimedEvent, @@ -76,20 +79,29 @@ 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 +/// The input is mono signed 16-bit PCM or normalized 32-bit floating-point +/// audio. The output is planar stereo or an in-place mono downmix. The +/// quantization, the output scale, the latency and the configuration behavior +/// match [`Processor`]. Buffer lengths and frame arguments count frames, not /// bytes. /// -/// These rules apply to the buffers: +/// These rules apply to `Int16Array` calls: /// /// - Separate stereo output arrays must not overlap. /// - The input can overlap an output, because the class copies the input /// first. /// - All buffers must stay attached until each call is complete. /// +/// These rules apply to in-place `Float32` calls: +/// +/// - `inputF32Ptr`, `leftF32Ptr` and `rightF32Ptr` are fixed byte offsets for +/// `maxBlockFrames` `f32` samples until `free()`. +/// - Check `memory.buffer` before input writes and after calls that pass +/// `events`, because Wasm memory growth detaches old views. +/// - Do not read or write the views of an instance after `free()`. +/// /// If a call that processes audio fails, it throws a JavaScript `Error` before /// the audio state or the output changes. The class rejects malformed /// configuration objects and malformed event objects. It also rejects values @@ -109,6 +121,12 @@ 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 fixed-capacity `f32` buffer for mono input and in-place mono output. + input_f32: Vec, + /// The fixed-capacity `f32` buffer for the left stereo output channel. + left_f32: Vec, + /// The fixed-capacity `f32` buffer for the right stereo output channel. + right_f32: 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,11 +188,42 @@ impl WasmProcessor { input: pcm_buffer(max_block_frames)?, left: pcm_buffer(max_block_frames)?, right: pcm_buffer(max_block_frames)?, + input_f32: f32_buffer(max_block_frames)?, + left_f32: f32_buffer(max_block_frames)?, + right_f32: f32_buffer(max_block_frames)?, envelope_input: Vec::new(), envelope_output: Vec::new(), }) } + /// The byte offset in Wasm memory of the `maxBlockFrames` `f32` input + /// buffer. + /// + /// Mono in-place calls also write their output to this buffer. This offset + /// stays constant until `free()`. + #[wasm_bindgen(getter, js_name = inputF32Ptr)] + pub fn input_f32_ptr(&self) -> usize { + self.input_f32.as_ptr() as usize + } + + /// The byte offset in Wasm memory of the `maxBlockFrames` left `f32` + /// output buffer. + /// + /// This offset stays constant until `free()`. + #[wasm_bindgen(getter, js_name = leftF32Ptr)] + pub fn left_f32_ptr(&self) -> usize { + self.left_f32.as_ptr() as usize + } + + /// The byte offset in Wasm memory of the `maxBlockFrames` right `f32` + /// output buffer. + /// + /// This offset stays constant until `free()`. + #[wasm_bindgen(getter, js_name = rightF32Ptr)] + pub fn right_f32_ptr(&self) -> usize { + self.right_f32.as_ptr() as usize + } + /// The sample rate of the input and the output in hertz. /// /// The constructor sets this value, and the value does not change. @@ -295,6 +344,61 @@ impl WasmProcessor { Ok(()) } + /// Processes `frames` samples from `inputF32Ptr` into `leftF32Ptr` and + /// `rightF32Ptr`. + /// + /// `frames` must be an integer in `0..=maxBlockFrames`. Input quantization, + /// the output scale, timed events and drain cancellation match + /// [`Processor::process_planar_f32`]. If you pass `events`, recheck + /// `memory.buffer` before you read the output views. + /// + /// # Errors + /// + /// If `frames` is not an integer in `0..=maxBlockFrames`, or if an event is + /// not valid, this method throws. All checks finish before the buffers or + /// the DSP state change. + #[wasm_bindgen(js_name = processF32InPlace)] + pub fn process_f32_in_place( + &mut self, + frames: f64, + events: Option>, + ) -> Result<(), JsError> { + let frames = self.check_frames(frames)?; + let events = decode_events(events)?; + self.processor.process_planar_f32( + &self.input_f32[..frames], + &mut self.left_f32[..frames], + &mut self.right_f32[..frames], + &events.0, + )?; + Ok(()) + } + + /// Replaces `frames` samples at `inputF32Ptr` with the mono `f32` downmix. + /// + /// `frames` must be an integer in `0..=maxBlockFrames`. Input quantization, + /// the output scale, peak measurement, events and drain cancellation match + /// [`Processor::process_mono_in_place_f32`]. If you pass `events`, recheck + /// `memory.buffer` before you read the output view. + /// + /// # Errors + /// + /// If `frames` is not an integer in `0..=maxBlockFrames`, or if an event is + /// not valid, this method throws. All checks finish before the buffer or + /// the DSP state changes. + #[wasm_bindgen(js_name = processMonoF32InPlace)] + pub fn process_mono_f32_in_place( + &mut self, + frames: f64, + events: Option>, + ) -> Result<(), JsError> { + let frames = self.check_frames(frames)?; + let events = decode_events(events)?; + self.processor + .process_mono_in_place_f32(&mut self.input_f32[..frames], &events.0)?; + 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 @@ -356,6 +460,44 @@ impl WasmProcessor { Ok(count) } + /// Renders up to `frames` stereo tail frames into `leftF32Ptr` and + /// `rightF32Ptr`. + /// + /// `frames` must be an integer in `0..=maxBlockFrames`. The method returns + /// the rendered frame count and fills unused frames up to `frames` with + /// `0.0`. Empty blocks and drain completion match `drain`. + /// + /// # Errors + /// + /// If `frames` is not an integer in `0..=maxBlockFrames`, this method + /// throws. On error, the output buffers and the drain state do not change. + #[wasm_bindgen(js_name = drainF32InPlace)] + pub fn drain_f32_in_place(&mut self, frames: f64) -> Result { + let frames = self.check_frames(frames)?; + Ok(self + .processor + .drain_planar_f32(&mut self.left_f32[..frames], &mut self.right_f32[..frames])?) + } + + /// Renders up to `frames` mono tail frames into `inputF32Ptr` and returns + /// their count. + /// + /// `frames` must be an integer in `0..=maxBlockFrames`. The method fills + /// unused samples up to `frames` with `0.0`. The downmix, the output scale, + /// empty blocks and drain completion match `drainMono`. + /// + /// # Errors + /// + /// If `frames` is not an integer in `0..=maxBlockFrames`, this method + /// throws. On error, the output buffer and the drain state do not change. + #[wasm_bindgen(js_name = drainMonoF32InPlace)] + pub fn drain_mono_f32_in_place(&mut self, frames: f64) -> Result { + let frames = self.check_frames(frames)?; + Ok(self + .processor + .drain_mono_f32(&mut self.input_f32[..frames])?) + } + /// Returns a new feedback object and does not clear the peak window. /// /// `processedFrames` is a `bigint`, so its 64-bit count stays exact. @@ -475,6 +617,17 @@ impl WasmProcessor { pub fn reset(&mut self) { self.processor.reset(); } + + /// Validates a JavaScript frame count before buffer slices or DSP state + /// change. + fn check_frames(&self, frames: f64) -> Result { + if !(0.0..=f64::from(u32::MAX)).contains(&frames) || frames.fract() != 0.0 { + return Err(JsError::new("frames must be an integer in 0..=4294967295")); + } + let frames = frames as usize; + self.processor.check_block(frames)?; + Ok(frames) + } } /// Decodes the optional block controls before the audio state changes. @@ -512,6 +665,17 @@ fn pcm_buffer(frames: usize) -> Result, JsError> { Ok(buffer) } +/// Allocates fixed-capacity `f32` storage that contains zeros. +/// +/// If the capacity overflows or the allocation fails, this function returns a +/// JavaScript error. It does not panic. +fn f32_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`,