Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 32 additions & 23 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down Expand Up @@ -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

Expand Down
37 changes: 37 additions & 0 deletions scripts/verify-pack.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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();",
"}",
Expand Down Expand Up @@ -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,",
Expand Down
22 changes: 16 additions & 6 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
167 changes: 167 additions & 0 deletions src/processor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
///
Expand Down Expand Up @@ -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<usize, Error> {
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<usize, Error> {
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<usize, Error> {
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
Expand Down Expand Up @@ -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
Expand Down
Loading