diff --git a/README.md b/README.md index 791cb8d..3c6a92c 100644 --- a/README.md +++ b/README.md @@ -217,11 +217,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: @@ -415,33 +418,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 90859f6..b84a2b7 100644 --- a/scripts/verify-pack.mjs +++ b/scripts/verify-pack.mjs @@ -274,6 +274,24 @@ 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.processF32(inputF32, leftF32, rightF32, [", + ' { offset: 0, event: { type: "outputGain", value: 1 } },', + " ]);", + " processor.processMonoF32(inputF32);", + " processor.processMonoF32(inputF32, [", + ' { offset: 0, event: { type: "reset" } },', + " ]);", + " processor.beginDrain();", + " assert.equal(typeof processor.drainF32(leftF32, rightF32), \"number\");", + " assert.equal(typeof processor.drainMonoF32(inputF32), \"number\");", "} finally {", " processor.free();", "}", @@ -326,7 +344,26 @@ 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.processF32(inputF32, leftF32, rightF32, [", + ' { offset: 0, event: { type: "outputGain", value: 1 } },', + " ]);", + " 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;", " if (syncSource !== undefined) {", " const syncExportsFromRoot: InitOutput = rootInitSync({", " module: syncSource,", diff --git a/src/lib.rs b/src/lib.rs index 94c4cc2..3f56590 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 ea56dec..07b1985 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -215,6 +215,93 @@ 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]), OutputLayout::Stereo) + .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]), OutputLayout::Stereo); + 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 and output + /// telemetry measure the mono samples after this 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(pcm_from_f32(audio[index]), OutputLayout::Mono); + audio[index] = pcm_to_f32(output[0]); + }) + } + /// Starts a tail with the current [`tail_frames`](Self::tail_frames) /// budget and returns that budget. /// @@ -297,6 +384,73 @@ 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(), OutputLayout::Stereo, |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(), OutputLayout::Stereo, |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, the peak measurements and the `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(), OutputLayout::Mono, |index, frame| { + output[index] = pcm_to_f32(frame[0]); + })?; + 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 @@ -714,6 +868,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 f3fafb0..b932bc8 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: //! @@ -80,12 +81,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: /// @@ -113,6 +114,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, @@ -177,6 +187,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(), events: Vec::new(), @@ -309,6 +322,80 @@ 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 = match events { + Some(events) => decode_events(&mut self.events, events, frames)?, + None => &[], + }; + 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, + )?; + 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 and + /// telemetry measure the mono signal after 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 = match events { + Some(events) => decode_events(&mut self.events, events, frames)?, + None => &[], + }; + audio.copy_to(&mut self.input_f32[..frames]); + self.processor + .process_mono_in_place_f32(&mut self.input_f32[..frames], events)?; + 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 @@ -370,6 +457,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 measurements 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. @@ -718,6 +855,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`,