diff --git a/README.md b/README.md index 83a8f47..4e385c0 100644 --- a/README.md +++ b/README.md @@ -50,8 +50,8 @@ browsers and Node.js. - **No dependencies**: The default Rust build has no dependencies and uses only safe Rust. -The input is mono signed 16-bit PCM at 44.1 kHz or 48 kHz. The output is -stereo or mono 16-bit PCM. +The input is mono signed 16-bit PCM or `f32` audio at 44.1 kHz or 48 kHz. The +output is stereo or mono 16-bit PCM or `f32` audio. ## Installation @@ -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: @@ -248,8 +251,10 @@ events. A stage event replaces all settings of that stage. To change one field, start from `processor.config()`. Harmony MIDI uses `ControlEvent::Midi`. MIDI for the correction keyboard uses -`ControlEvent::CorrectionMidi`. For example, this event starts a harmony note -at frame 256: +`ControlEvent::CorrectionMidi`. To apply packed 3-byte MIDI messages directly +between blocks, call `processor.apply_midi(bytes)` or +`processor.apply_correction_midi(bytes)`. For example, this event starts a +harmony note at frame 256: ```rust use tunelet::{ControlEvent, MidiEvent, TimedEvent}; @@ -297,8 +302,10 @@ These calls read the state of the processor. They do not change the audio. | -------------------- | ----------------------------------------------------------------- | | `feedback()` | The pitch, the stereo peak, the correction ratio, the frame count | | `take_feedback()` | The same data as `feedback()`, and clears the peak window | +| `write_feedback()` | Writes the eight feedback fields into an `f32` slice | | `telemetry()` | Data for meters and displays (refer to the list below) | | `take_telemetry()` | The same data as `telemetry()`, and clears its three peak windows | +| `write_telemetry()` | Writes the 45 telemetry fields into an `f32` slice | | `latency_frames()` | 1,593 frames of nominal resynthesis latency at both sample rates | | `formant_envelope()` | The LPC envelopes before and after the formant controls | @@ -359,12 +366,12 @@ For `wasm32-unknown-unknown`, the optional `wasm` feature of the crate gives JavaScript bindings and generated TypeScript declarations. The npm package contains these bindings. -The npm package is one ES module for both browsers and Node.js. It contains -these items: +The npm package is one ES module for browsers, `AudioWorkletGlobalScope` and +Node.js. It contains these items: - One Wasm binary. -- The generated bindings. -- A shared `loadTunelet` entry point. +- The generated bindings and an internal UTF-8 fallback. +- The `loadTunelet` and `initTuneletSync` entry points. ### Load the module @@ -393,11 +400,14 @@ rules. The first concurrent call selects the source. Later arguments do not replace an initialized module. A custom binary must match the generated bindings. -The package root also exports `loadTunelet` as its default export. For direct -control of Wasm initialization, `tunelet/wasm` gives the generated default -initializer and `initSync`. The package root re-exports `initSync` too. Use -only one initialization entry point for each module instance. The package -gives only ESM exports. CommonJS applications can use `await import("tunelet")`. +The package root also exports `loadTunelet` as its default export. In +`AudioWorkletGlobalScope`, compile a `WebAssembly.Module` on the main thread, +transfer it to the worklet and call `initTuneletSync(module)`. If `TextDecoder` +or `TextEncoder` is undefined, the package installs an internal UTF-8 fallback +before the Wasm glue runs. For direct control of Wasm initialization, +`tunelet/wasm` gives the generated default initializer and `initSync`. Use only +one initialization entry point for each module instance. CommonJS applications +can use `await import("tunelet")`. ### Deployment @@ -413,33 +423,40 @@ 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?)`, `initTuneletSync(module)` | +| Mono PCM to planar stereo | `process(input, left, right, events?)` | +| Mono Float32 to planar stereo | `processFloat32(input, left, right, events?)` | +| In-place mono downmix | `processMono(audio, events?)`, `processMonoFloat32(audio, events?)` | +| Packed 3-byte MIDI | `applyMidi(bytes)`, `applyCorrectionMidi(bytes)` | +| Configuration | `config()`, `setConfig(config)`, `defaultConfig()` | +| Information about the preparation | `sampleRate`, `maxBlockFrames`, `latencyFrames` | +| Feedback | `feedback()`, `takeFeedback()`, `writeFeedback(output, clearPeak?)` | +| Telemetry | `telemetry()`, `takeTelemetry()`, `writeTelemetry(output, clearPeaks?)` | +| Formant envelopes | `formantEnvelope(maxFrequencyHz, input, output)` | +| Finite PCM tail | `beginDrain()`, `drain(left, right)`, `drainMono(audio)` | +| Finite Float32 tail | `drainFloat32(left, right)`, `drainMonoFloat32(audio)` | +| Configured tail budget | `tailFrames()` | +| Reset or release memory | `reset()`, `free()` | ### Audio buffers -All audio buffers are `Int16Array` buffers, and they must fit in the prepared -frame limit. These rules apply: +Audio buffers are `Int16Array` or `Float32Array` buffers, and they must fit in +the prepared frame limit. `Float32Array` inputs scale by 32,768 and saturate to +`-32768..=32767`, and `NaN` becomes zero. `Float32Array` outputs divide the +rendered 16-bit PCM samples by 32,768. 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. +Web Audio uses `Float32Array` channels, which `processFloat32` accepts +directly. The processor supports 44.1 kHz and 48 kHz. In Web Audio, construct +`new AudioContext({ sampleRate: 48000 })` or `{ sampleRate: 44100 }` so the +context rate matches the processor. This package does not install an +`AudioWorkletNode` or a sample-rate converter. ### Configuration objects @@ -478,14 +495,20 @@ A harmony Note On event has this form: Use `correctionMidi` for the separate correction keyboard. The native rules for event order and for the validation of the whole block also apply to these -bindings. +bindings. For packed 3-byte MIDI messages without object conversion, pass a +`Uint8Array` to `applyMidi(bytes)` or `applyCorrectionMidi(bytes)` before the +block. ### Feedback, telemetry and formant envelopes -`telemetry()` and `takeTelemetry()` return a `Telemetry` object. +`telemetry()` and `takeTelemetry()` return a `Telemetry` object. For meter +reads without object allocation, `writeFeedback(output, clearPeak?)` fills a +`Float32Array(8)` and `writeTelemetry(output, clearPeaks?)` fills a +`Float32Array(45)`. Pass `true` as the second argument to clear the peak +windows after the read. -In feedback, `targetMidiNote` is `undefined` in these cases, which are also -the cases where `voiced` is `false`: +In feedback, `targetMidiNote` is `undefined` (`NaN` in `writeFeedback`) in +these cases, which are also the cases where `voiced` is `false`: - The kept pitch estimate is unvoiced. This includes the time before the first detection and after a reset or a drain completion. @@ -502,16 +525,17 @@ 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` audio buffers. Calls to +`process`, `processFloat32`, `applyMidi`, `writeFeedback` and `writeTelemetry` +without `events` do not allocate on the Wasm heap. However, audio calls copy +samples across the boundary between JavaScript and Wasm. These items can +allocate: - Object conversion. -- Supplied events. +- Supplied `TimedEvent[]` arrays. - Errors. -- Feedback and telemetry. -- The formant envelopes. +- `feedback()` and `telemetry()` objects. +- The formant envelopes on the first call or a larger point count. 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 diff --git a/package.json b/package.json index 19c26a3..7405a94 100644 --- a/package.json +++ b/package.json @@ -26,7 +26,9 @@ "pkg/tunelet.d.ts", "pkg/tunelet_bg.wasm" ], - "sideEffects": false, + "sideEffects": [ + "./dist/utf8.js" + ], "scripts": { "build": "npm run build:wasm && npm run build:ts", "build:wasm": "wasm-pack build --target web --out-dir pkg --release --no-pack --features wasm --locked && node --input-type=module -e \"import fs from 'node:fs'; fs.rmSync('pkg/.gitignore', { force: true })\"", diff --git a/scripts/verify-pack.mjs b/scripts/verify-pack.mjs index 921fa6f..d94d771 100644 --- a/scripts/verify-pack.mjs +++ b/scripts/verify-pack.mjs @@ -1,5 +1,5 @@ /** - * This script packs the npm archive, checks its eight files, runs + * This script packs the npm archive, checks its ten files, runs * `loadTunelet()` and checks the TypeScript declarations. */ import assert from "node:assert/strict"; @@ -14,6 +14,8 @@ const EXPECTED_ARCHIVE_PATHS = [ "package/README.md", "package/dist/index.d.ts", "package/dist/index.js", + "package/dist/utf8.d.ts", + "package/dist/utf8.js", "package/package.json", "package/pkg/tunelet.d.ts", "package/pkg/tunelet.js", @@ -86,7 +88,7 @@ function packArchive(packDir) { return path.posix.join("pack", archives[0]); } -/** Check that the archive contains only the eight expected files. */ +/** Check that the archive contains only the ten expected files. */ function verifyArchiveEntries(tempDir, relativeArchivePath) { const rawList = execFileSync("tar", ["-tzf", relativeArchivePath], { cwd: tempDir, @@ -159,6 +161,7 @@ function verifyRuntimeImport(consumerDir, packageName) { "", 'assert.equal(typeof rootModule.loadTunelet, "function");', "assert.equal(rootModule.default, rootModule.loadTunelet);", + 'assert.equal(typeof rootModule.initTuneletSync, "function");', 'assert.equal(typeof rootModule.initSync, "function");', 'assert.equal(typeof rootModule.Tunelet, "function");', 'assert.equal(typeof rootModule.defaultConfig, "function");', @@ -198,6 +201,7 @@ function verifyTypeDeclarations(consumerDir, packageName) { [ "import loadTunelet, {", " defaultConfig,", + " initTuneletSync,", " initSync as rootInitSync,", " loadTunelet as namedLoadTunelet,", " Tunelet,", @@ -220,6 +224,7 @@ function verifyTypeDeclarations(consumerDir, packageName) { " const right = new Int16Array(128);", " processor.process(input, left, right);", " processor.free();", + " void initTuneletSync;", " void rootInitSync;", " void wasmInitSync;", " void exportsFromRoot;", diff --git a/src/error.rs b/src/error.rs index b971968..c2590a5 100644 --- a/src/error.rs +++ b/src/error.rs @@ -32,12 +32,12 @@ pub enum Error { /// The problem with the field. problem: ConfigProblem, }, - /// A buffer length is not equal to the input length or to the length of - /// the other output channel. + /// A buffer length is not equal to the expected length. BufferLength { - /// The necessary slice length. For `[[i16; 2]]`, this is the number of - /// stereo frames. For planar or mono audio, it is the number of samples - /// for each channel. + /// The necessary slice length. For `[[i16; 2]]` or `[[f32; 2]]`, this + /// is the number of stereo frames. For planar or mono audio, it is the + /// number of samples for each channel. For meter slices, it is the + /// fixed field count. expected: usize, /// The actual slice length, in the same units as `expected`. actual: usize, @@ -60,6 +60,7 @@ pub enum Error { /// /// The causes are: /// + /// - a byte slice whose length is not a multiple of three /// - a status byte below 0x80 /// - a data byte above 127 /// - a typed event with a channel, note or velocity out of range. diff --git a/src/index.ts b/src/index.ts index 8526d77..f79dbb0 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,20 +1,48 @@ /** - * The shared ESM entry point for browsers and Node.js. + * The shared ESM entry point for browsers, `AudioWorkletGlobalScope` and + * Node.js. * - * Call `loadTunelet()` before you construct processors or read the default - * configuration. Both environments use the same generated bindings and the - * same Wasm binary. This module re-exports all named exports of the module - * that wasm-bindgen generates, which include `Tunelet`, `defaultConfig`, - * `initSync` and the configuration, event and feedback types. + * Call `loadTunelet()` or `initTuneletSync(module)` before you construct + * processors or read the default configuration. All environments use the same + * generated bindings and the same Wasm binary. This module installs an + * internal UTF-8 fallback when `TextDecoder` or `TextEncoder` is undefined. + * It also re-exports all named exports of the module that wasm-bindgen + * generates, which include `Tunelet`, `defaultConfig`, `initSync` and the + * configuration, event and feedback types. */ -import init from "../pkg/tunelet.js"; -import type { InitInput, InitOutput } from "../pkg/tunelet.js"; +import "./utf8.js"; +import init, { initSync } from "../pkg/tunelet.js"; +import type { InitInput, InitOutput, SyncInitInput } from "../pkg/tunelet.js"; export * from "../pkg/tunelet.js"; +/** The initialized Wasm exports, kept after synchronous or asynchronous load. */ +let initialized: InitOutput | undefined; + /** The shared initialization promise, which a failure clears. */ let initialization: Promise | undefined; +/** + * Initializes the Wasm module synchronously for this imported package + * instance. + * + * Use this function in `AudioWorkletGlobalScope`, where `fetch` is not + * available. Compile a `WebAssembly.Module` on the main thread, send it to the + * worklet and pass it to `initTuneletSync(module)`. You can also give a byte + * buffer (`BufferSource`). + * + * After a successful initialization, later calls return the same exports and + * do not instantiate Wasm again. If instantiation fails, the function throws + * and does not cache the failure. + * + * @param module A compiled `WebAssembly.Module` or Wasm bytes. + * @returns The initialized Wasm exports. + */ +export function initTuneletSync(module: SyncInitInput): InitOutput { + initialized ??= initSync({ module }); + return initialized; +} + /** * Initializes the Wasm module one time for this imported package instance. * @@ -50,6 +78,10 @@ let initialization: Promise | undefined; export function loadTunelet( source?: InitInput | Promise, ): Promise { + if (initialized !== undefined) { + initialization ??= Promise.resolve(initialized); + return initialization; + } initialization ??= initialize(source).catch((error: unknown) => { initialization = undefined; throw error; @@ -74,10 +106,12 @@ async function initialize( const fs: typeof import("node:fs/promises") = await import( /* webpackIgnore: true */ /* @vite-ignore */ moduleName ); - return init({ module_or_path: await fs.readFile(input) }); + initialized = await init({ module_or_path: await fs.readFile(input) }); + return initialized; } - return init({ module_or_path: input }); + initialized = await init({ module_or_path: input }); + return initialized; } /** The default export is the same function as `loadTunelet`. */ diff --git a/src/lib.rs b/src/lib.rs index f17bc85..aaf3443 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 16-bit PCM process methods and three `f32` equivalents: +//! +//! - [`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. The 16-bit output is clipped to -32767..=32767, and +//! `f32` output divides those samples by 32768. //! //! 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 @@ -42,24 +46,27 @@ //! or its state. Thus, an invalid last event also rejects the full call. An //! empty block accepts no events. //! -//! [`ControlEvent::Midi`] controls harmony. [`ControlEvent::CorrectionMidi`] -//! selects the correction pitch classes independently. The processor does not +//! [`ControlEvent::Midi`] and [`Processor::apply_midi`] control harmony. +//! [`ControlEvent::CorrectionMidi`] and [`Processor::apply_correction_midi`] +//! select the correction pitch classes independently. The processor does not //! keep MIDI controls in a queue after the current call. //! //! # Feedback, latency and lifecycle //! //! [`Processor::feedback`] gives the pitch, the correction ratio, the //! accumulated stereo peak and the frame count. -//! [`Processor::take_feedback`] also clears the peak window. The pitch -//! reporting bounds change only the reports. They do not change the detection -//! or the audio signal. [`Processor::latency_frames`] gives a nominal +//! [`Processor::take_feedback`] also clears the peak window, and +//! [`Processor::write_feedback`] writes the values into an `f32` slice. The +//! pitch reporting bounds change only the reports. They do not change the +//! detection or the audio signal. [`Processor::latency_frames`] gives a nominal //! resynthesis delay. Voice delays, pitch changes and effects have their own //! timing. //! //! [`Processor::telemetry`] gives data for meters and displays: the ratio and //! the gain of each voice, the input and output peaks, the pitch clarity and //! the state of the effects. [`Processor::take_telemetry`] also clears the -//! peak windows of the telemetry. [`Processor::formant_envelope`] writes the +//! peak windows of the telemetry, and [`Processor::write_telemetry`] writes +//! the values into an `f32` slice. [`Processor::formant_envelope`] writes the //! LPC envelopes before and after the formant controls. These calls do not //! change the audio. //! diff --git a/src/processor.rs b/src/processor.rs index 83bccf6..76d24e8 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -8,7 +8,12 @@ use crate::events::{ValidatedEvent, ValidatedEvents}; use crate::numeric::rng::RandomStream; use crate::numeric::NumericContext; use crate::resynthesis::{self, Resynthesis}; -use crate::{ControlEvent, Error, PrepareConfig, ProcessorConfig, TimedEvent}; +use crate::{ControlEvent, Error, MidiEvent, PrepareConfig, ProcessorConfig, TimedEvent}; + +/// The number of `f32` entries that [`Processor::write_feedback`] writes. +pub(crate) const FEEDBACK_LEN: usize = 8; +/// The number of `f32` entries that [`Processor::write_telemetry`] writes. +pub(crate) const TELEMETRY_LEN: usize = 45; /// A prepared vocal processor with state, mono input and stereo synthesis. /// @@ -208,6 +213,85 @@ impl Processor { }) } + /// Processes mono `f32` audio into `[left, right]` stereo frames. + /// + /// Input samples convert to signed 16-bit PCM with + /// `(sample * 32768.0).round() as i16`. Finite values in `-1.0..=1.0` map + /// to `-32768..=32767`, values outside that range saturate and `NaN` + /// becomes zero. Each rendered PCM sample converts to `f32` as + /// `f32::from(sample) / 32768.0`, in `-32767/32768..=32767/32768`. The + /// internal DSP path, event order and drain cancellation are the same as + /// for [`process`](Self::process). + /// + /// # Errors + /// + /// The call checks [`Error::BufferLength`] first, + /// [`Error::BlockTooLarge`] second and [`Error::InvalidEvent`] third. 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] = frame_to_f32(processor.next(sample_from_f32(input[index]))); + }) + } + + /// Processes mono `f32` audio into separate left and right `f32` slices. + /// + /// The three slices must have equal frame counts. The sample conversion, + /// event order, empty-block behavior and drain cancellation are the same + /// as for [`process_f32`](Self::process_f32). + /// + /// # Errors + /// + /// The call checks [`Error::BufferLength`] for the left channel, then for + /// the right channel. Next, it checks [`Error::BlockTooLarge`], then + /// [`Error::InvalidEvent`]. If an error occurs, the two output slices 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(sample_from_f32(input[index])); + left[index] = sample_to_f32(frame[0]); + right[index] = sample_to_f32(frame[1]); + }) + } + + /// Replaces mono `f32` audio with the stereo downmix. + /// + /// Each input sample converts as in [`process_f32`](Self::process_f32). + /// The stereo output uses the fixed-point downmix of + /// [`process_mono_in_place`](Self::process_mono_in_place) before the + /// division by 32768. Peak feedback measures the stereo samples before the + /// downmix. + /// + /// # Errors + /// + /// Returns [`Error::BlockTooLarge`] for a slice that is too large. Returns + /// [`Error::InvalidEvent`] for the first invalid event. All checks finish + /// before the audio slice or the processor state changes. + pub fn process_mono_in_place_f32( + &mut self, + audio: &mut [f32], + events: &[TimedEvent], + ) -> Result<(), Error> { + self.process_into(audio.len(), events, |processor, index| { + let output = processor.next(sample_from_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,70 @@ impl Processor { Ok(count) } + /// Renders the next stereo tail frames as `f32` pairs and returns their + /// count. + /// + /// Output samples convert as `f32::from(sample) / 32768.0`. The method + /// fills unused frames with zeros. Completion and empty-buffer behavior + /// 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_to_f32(frame); + })?; + output[count..].fill([0.0; 2]); + Ok(count) + } + + /// Renders the tail into separate `f32` output channels of equal size. + /// + /// Output samples convert as `f32::from(sample) / 32768.0`. Return values, + /// zero fill in unused samples and completion are the same as for + /// [`drain_planar`](Self::drain_planar). + /// + /// # Errors + /// + /// The method checks [`Error::BufferLength`] before + /// [`Error::BlockTooLarge`]. If either error occurs, the two channels and + /// the drain state do not change. + pub fn drain_planar_f32( + &mut self, + left: &mut [f32], + right: &mut [f32], + ) -> Result { + Error::check_length(left.len(), right.len())?; + let count = self.drain_into(left.len(), |index, frame| { + left[index] = sample_to_f32(frame[0]); + right[index] = sample_to_f32(frame[1]); + })?; + left[count..].fill(0.0); + right[count..].fill(0.0); + Ok(count) + } + + /// Renders the tail as mono `f32` audio and returns the number of rendered + /// frames. + /// + /// The fixed-point downmix is the same as in + /// [`drain_mono`](Self::drain_mono) before the division by 32768. Unused + /// samples become `0.0`. + /// + /// # 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 @@ -352,6 +500,45 @@ impl Processor { result } + /// Writes the current feedback into an `f32` slice of length 8. + /// + /// If `clear_peak` is `true`, the method also clears the stereo peak + /// window, as [`take_feedback`](Self::take_feedback) does. The slice + /// entries are: + /// + /// - `0`: [`Feedback::resample_ratio`] + /// - `1`: [`Feedback::period_samples`] + /// - `2`: [`Feedback::frequency_hz`] + /// - `3`: [`Feedback::target_midi_note`], or `f32::NAN` if `None` + /// - `4`: `1.0` if [`Feedback::voiced`] is `true`, or `0.0` if `false` + /// - `5`: [`Feedback::peak_level`] + /// - `6`: [`Feedback::processed_frames`] as `f32` + /// - `7`: [`Feedback::latency_frames`] as `f32` + /// + /// Above `16_777_216`, `processed_frames` rounds to `f32` precision. + /// + /// # Errors + /// + /// Returns [`Error::BufferLength`] if `output.len()` is not 8. On error, + /// `output` and the peak window do not change. + pub fn write_feedback(&mut self, output: &mut [f32], clear_peak: bool) -> Result<(), Error> { + Error::check_length(FEEDBACK_LEN, output.len())?; + let feedback = if clear_peak { + self.take_feedback() + } else { + self.feedback() + }; + output[0] = feedback.resample_ratio; + output[1] = feedback.period_samples; + output[2] = feedback.frequency_hz; + output[3] = feedback.target_midi_note.unwrap_or(f32::NAN); + output[4] = if feedback.voiced { 1.0 } else { 0.0 }; + output[5] = feedback.peak_level; + output[6] = feedback.processed_frames as f32; + output[7] = feedback.latency_frames as f32; + Ok(()) + } + /// Returns the state of the voices, the levels and the effects, and does /// not clear the peak windows. /// @@ -399,6 +586,59 @@ impl Processor { result } + /// Writes the current telemetry into an `f32` slice of length 45. + /// + /// If `clear_peaks` is `true`, the method also clears the three peak + /// windows of the telemetry, as [`take_telemetry`](Self::take_telemetry) + /// does. The slice entries are: + /// + /// - `0`: [`Telemetry::processed_frames`] as `f32` + /// - `1`: [`Telemetry::input_peak`] + /// - `2..4`: [`Telemetry::output_peak`] (left, then right) + /// - `4`: [`Telemetry::reverb_wet_peak`] + /// - `5`: [`Telemetry::clarity`] + /// - `6`: `1.0` if [`Telemetry::tracking`] is `true`, or `0.0` if `false` + /// - `7`: [`Telemetry::voice_count`] as `f32` + /// - `8..24`: [`Telemetry::voice_ratios`] (16 entries) + /// - `24..40`: [`Telemetry::voice_gains`] (16 entries) + /// - `40`: [`Telemetry::punch_gain`] + /// - `41`: [`Telemetry::warm_gain`] + /// - `42`: [`Telemetry::alien_loop_frames`] as `f32` + /// - `43`: [`Telemetry::alien_phase_frames`] as `f32` + /// - `44`: [`Telemetry::formant_generation`] as `f32` + /// + /// Above `16_777_216`, `processed_frames` and `formant_generation` round + /// to `f32` precision. + /// + /// # Errors + /// + /// Returns [`Error::BufferLength`] if `output.len()` is not 45. On error, + /// `output` and the peak windows do not change. + pub fn write_telemetry(&mut self, output: &mut [f32], clear_peaks: bool) -> Result<(), Error> { + Error::check_length(TELEMETRY_LEN, output.len())?; + let telemetry = if clear_peaks { + self.take_telemetry() + } else { + self.telemetry() + }; + output[0] = telemetry.processed_frames as f32; + output[1] = telemetry.input_peak; + output[2] = telemetry.output_peak[0]; + output[3] = telemetry.output_peak[1]; + output[4] = telemetry.reverb_wet_peak; + output[5] = telemetry.clarity; + output[6] = if telemetry.tracking { 1.0 } else { 0.0 }; + output[7] = f32::from(telemetry.voice_count); + output[8..24].copy_from_slice(&telemetry.voice_ratios); + output[24..40].copy_from_slice(&telemetry.voice_gains); + output[40] = telemetry.punch_gain; + output[41] = telemetry.warm_gain; + output[42] = telemetry.alien_loop_frames as f32; + output[43] = telemetry.alien_phase_frames as f32; + output[44] = telemetry.formant_generation as f32; + Ok(()) + } + /// Starts new windows for the input peak, the output peaks and the wet /// peak of the reverb. fn clear_telemetry_peaks(&mut self) { @@ -477,6 +717,49 @@ impl Processor { Ok(()) } + /// Decodes packed 3-byte MIDI messages and applies them to harmony. + /// + /// `bytes` must have a length that is a multiple of three. Each group of + /// three bytes decodes with [`MidiEvent::from_bytes`]. Messages that + /// decode to `Ok(None)` have no effect. An empty slice is valid. An active + /// drain does not change. + /// + /// # Errors + /// + /// Returns [`Error::InvalidMidi`] if `bytes.len()` is not a multiple of + /// three or if any 3-byte message fails [`MidiEvent::from_bytes`]. All + /// messages are validated before any state changes. + pub fn apply_midi(&mut self, bytes: &[u8]) -> Result<(), Error> { + for &message in validate_midi_bytes(bytes)? { + if let Some(event) = MidiEvent::from_bytes(message)? { + self.resynthesis.apply_midi(event); + } + } + Ok(()) + } + + /// Decodes packed 3-byte MIDI messages and applies them to the correction + /// keyboard. + /// + /// `bytes` must have a length that is a multiple of three. Each group of + /// three bytes decodes with [`MidiEvent::from_bytes`]. The note-table + /// semantics are the same as for [`ControlEvent::CorrectionMidi`]. An + /// empty slice is valid, and an active drain does not change. + /// + /// # Errors + /// + /// Returns [`Error::InvalidMidi`] if `bytes.len()` is not a multiple of + /// three or if any 3-byte message fails [`MidiEvent::from_bytes`]. All + /// messages are validated before any state changes. + pub fn apply_correction_midi(&mut self, bytes: &[u8]) -> Result<(), Error> { + for &message in validate_midi_bytes(bytes)? { + if let Some(event) = MidiEvent::from_bytes(message)? { + self.resynthesis.apply_correction_midi(event); + } + } + Ok(()) + } + /// Applies a configuration that the public setter or the preflight checked. fn apply_config(&mut self, config: ProcessorConfig) { if self.config.punch != config.punch { @@ -701,6 +984,36 @@ fn downmix(frame: [i16; 2]) -> i16 { ((i32::from(frame[0]) + i32::from(frame[1])) >> 1) as i16 } +/// Converts a normalized `f32` sample to signed 16-bit PCM. +#[inline] +fn sample_from_f32(sample: f32) -> i16 { + (sample * 32_768.0).round() as i16 +} + +/// Converts a signed 16-bit PCM sample to normalized `f32`. +#[inline] +fn sample_to_f32(sample: i16) -> f32 { + f32::from(sample) / 32_768.0 +} + +/// Converts a stereo 16-bit PCM frame to normalized `f32`. +#[inline] +fn frame_to_f32(frame: [i16; 2]) -> [f32; 2] { + frame.map(sample_to_f32) +} + +/// Validates that `bytes` contains complete, valid 3-byte MIDI messages. +fn validate_midi_bytes(bytes: &[u8]) -> Result<&[[u8; 3]], Error> { + let (messages, remainder) = bytes.as_chunks::<3>(); + if !remainder.is_empty() { + return Err(Error::InvalidMidi); + } + for &message in messages { + MidiEvent::from_bytes(message)?; + } + Ok(messages) +} + /// 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/utf8.ts b/src/utf8.ts new file mode 100644 index 0000000..cea68c3 --- /dev/null +++ b/src/utf8.ts @@ -0,0 +1,280 @@ +/** + * Installs a UTF-8 fallback if `TextDecoder` or `TextEncoder` is undefined. + * + * `AudioWorkletGlobalScope` omits the WHATWG text classes in browsers. The + * generated Wasm glue constructs `TextDecoder` and `TextEncoder` when the + * module loads. Import this file before `pkg/tunelet.js`. + */ + +interface Utf8DecoderOptions { + fatal?: boolean; + ignoreBOM?: boolean; +} + +interface EncodeIntoResult { + read: number; + written: number; +} + +/** Checks if `byte` is a valid UTF-8 continuation byte (`10xxxxxx`). */ +function isContinuation(byte: number): boolean { + return (byte & 0xc0) === 0x80; +} + +/** Checks if `b1` is a valid first continuation byte after 3-byte `b0`. */ +function isValidThreeByteFirst(b0: number, b1: number): boolean { + if (b0 === 0xe0) { + return b1 >= 0xa0 && b1 <= 0xbf; + } + if (b0 === 0xed) { + return b1 >= 0x80 && b1 <= 0x9f; + } + return isContinuation(b1); +} + +/** Checks if `b1` is a valid first continuation byte after 4-byte `b0`. */ +function isValidFourByteFirst(b0: number, b1: number): boolean { + if (b0 === 0xf0) { + return b1 >= 0x90 && b1 <= 0xbf; + } + if (b0 === 0xf4) { + return b1 >= 0x80 && b1 <= 0x8f; + } + return isContinuation(b1); +} + +/** Minimal UTF-8 `TextDecoder` for scopes that omit it. */ +class FallbackTextDecoder { + readonly encoding = "utf-8"; + readonly fatal: boolean; + readonly ignoreBOM: boolean; + + constructor(label?: string, options?: Utf8DecoderOptions) { + if (label !== undefined) { + const normalized = String(label).trim().toLowerCase(); + if ( + normalized !== "utf-8" && + normalized !== "utf8" && + normalized !== "unicode-1-1-utf-8" + ) { + throw new RangeError("The label must select UTF-8"); + } + } + this.fatal = Boolean(options?.fatal); + this.ignoreBOM = Boolean(options?.ignoreBOM); + } + + decode(input?: AllowSharedBufferSource): string { + if (input === undefined) { + return ""; + } + const bytes = ArrayBuffer.isView(input) + ? new Uint8Array(input.buffer, input.byteOffset, input.byteLength) + : new Uint8Array(input); + + let index = 0; + if ( + !this.ignoreBOM && + bytes.length >= 3 && + bytes[0] === 0xef && + bytes[1] === 0xbb && + bytes[2] === 0xbf + ) { + index = 3; + } + + const parts: string[] = []; + const units: number[] = []; + + while (index < bytes.length) { + const b0 = bytes[index]; + if (b0 < 0x80) { + units.push(b0); + index += 1; + } else if (b0 >= 0xc2 && b0 <= 0xdf) { + if (index + 1 < bytes.length && isContinuation(bytes[index + 1])) { + units.push(((b0 & 0x1f) << 6) | (bytes[index + 1] & 0x3f)); + index += 2; + } else { + this.failOrReplace(units); + index += 1; + } + } else if (b0 >= 0xe0 && b0 <= 0xef) { + const hasB1 = + index + 1 < bytes.length && + isValidThreeByteFirst(b0, bytes[index + 1]); + const hasB2 = + hasB1 && index + 2 < bytes.length && isContinuation(bytes[index + 2]); + if (hasB2) { + units.push( + ((b0 & 0x0f) << 12) | + ((bytes[index + 1] & 0x3f) << 6) | + (bytes[index + 2] & 0x3f), + ); + index += 3; + } else { + this.failOrReplace(units); + index += hasB1 ? 2 : 1; + } + } else if (b0 >= 0xf0 && b0 <= 0xf4) { + const hasB1 = + index + 1 < bytes.length && + isValidFourByteFirst(b0, bytes[index + 1]); + const hasB2 = + hasB1 && index + 2 < bytes.length && isContinuation(bytes[index + 2]); + const hasB3 = + hasB2 && index + 3 < bytes.length && isContinuation(bytes[index + 3]); + if (hasB3) { + const point = + (((b0 & 0x07) << 18) | + ((bytes[index + 1] & 0x3f) << 12) | + ((bytes[index + 2] & 0x3f) << 6) | + (bytes[index + 3] & 0x3f)) - + 0x10000; + units.push(0xd800 | (point >> 10), 0xdc00 | (point & 0x3ff)); + index += 4; + } else { + this.failOrReplace(units); + index += hasB2 ? 3 : hasB1 ? 2 : 1; + } + } else { + this.failOrReplace(units); + index += 1; + } + + if (units.length >= 4096) { + parts.push(String.fromCharCode(...units)); + units.length = 0; + } + } + + if (units.length > 0) { + parts.push(String.fromCharCode(...units)); + } + return parts.join(""); + } + + private failOrReplace(units: number[]): void { + if (this.fatal) { + throw new TypeError("Invalid UTF-8 sequence"); + } + units.push(0xfffd); + } +} + +/** Minimal UTF-8 `TextEncoder` for scopes that omit it. */ +class FallbackTextEncoder { + readonly encoding = "utf-8"; + + encode(input = ""): Uint8Array { + const text = String(input); + const bytes: number[] = []; + for (let index = 0; index < text.length; index += 1) { + const code = text.charCodeAt(index); + if (code < 0x80) { + bytes.push(code); + } else if (code < 0x800) { + bytes.push(0xc0 | (code >> 6), 0x80 | (code & 0x3f)); + } else if (code >= 0xd800 && code <= 0xdbff) { + const next = index + 1 < text.length ? text.charCodeAt(index + 1) : 0; + if (next >= 0xdc00 && next <= 0xdfff) { + const point = 0x10000 + (((code & 0x3ff) << 10) | (next & 0x3ff)); + bytes.push( + 0xf0 | (point >> 18), + 0x80 | ((point >> 12) & 0x3f), + 0x80 | ((point >> 6) & 0x3f), + 0x80 | (point & 0x3f), + ); + index += 1; + } else { + bytes.push(0xef, 0xbf, 0xbd); + } + } else if (code >= 0xdc00 && code <= 0xdfff) { + bytes.push(0xef, 0xbf, 0xbd); + } else { + bytes.push( + 0xe0 | (code >> 12), + 0x80 | ((code >> 6) & 0x3f), + 0x80 | (code & 0x3f), + ); + } + } + return Uint8Array.from(bytes); + } + + encodeInto(source: string, destination: Uint8Array): EncodeIntoResult { + const text = String(source); + let read = 0; + let written = 0; + while (read < text.length) { + const code = text.charCodeAt(read); + if (code < 0x80) { + if (written + 1 > destination.length) { + break; + } + destination[written] = code; + written += 1; + read += 1; + } else if (code < 0x800) { + if (written + 2 > destination.length) { + break; + } + destination[written] = 0xc0 | (code >> 6); + destination[written + 1] = 0x80 | (code & 0x3f); + written += 2; + read += 1; + } else if (code >= 0xd800 && code <= 0xdbff) { + const next = read + 1 < text.length ? text.charCodeAt(read + 1) : 0; + if (next >= 0xdc00 && next <= 0xdfff) { + if (written + 4 > destination.length) { + break; + } + const point = 0x10000 + (((code & 0x3ff) << 10) | (next & 0x3ff)); + destination[written] = 0xf0 | (point >> 18); + destination[written + 1] = 0x80 | ((point >> 12) & 0x3f); + destination[written + 2] = 0x80 | ((point >> 6) & 0x3f); + destination[written + 3] = 0x80 | (point & 0x3f); + written += 4; + read += 2; + } else { + if (written + 3 > destination.length) { + break; + } + destination[written] = 0xef; + destination[written + 1] = 0xbf; + destination[written + 2] = 0xbd; + written += 3; + read += 1; + } + } else if (code >= 0xdc00 && code <= 0xdfff) { + if (written + 3 > destination.length) { + break; + } + destination[written] = 0xef; + destination[written + 1] = 0xbf; + destination[written + 2] = 0xbd; + written += 3; + read += 1; + } else { + if (written + 3 > destination.length) { + break; + } + destination[written] = 0xe0 | (code >> 12); + destination[written + 1] = 0x80 | ((code >> 6) & 0x3f); + destination[written + 2] = 0x80 | (code & 0x3f); + written += 3; + read += 1; + } + } + return { read, written }; + } +} + +const scope = globalThis as Record; +if (typeof scope.TextDecoder === "undefined") { + scope.TextDecoder = FallbackTextDecoder; +} +if (typeof scope.TextEncoder === "undefined") { + scope.TextEncoder = FallbackTextEncoder; +} +export {}; diff --git a/src/wasm.rs b/src/wasm.rs index 15262e2..328182a 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -7,12 +7,14 @@ //! 2. Run wasm-bindgen on the result. //! //! 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. +//! `loadTunelet()` in browsers and in Node.js, and `initTuneletSync(module)` in +//! `AudioWorkletGlobalScope`. //! -//! 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: //! @@ -36,15 +38,18 @@ //! - 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. +//! The JavaScript glue can also make temporary views when it copies data. For +//! an `AudioWorkletProcessor` callback without Wasm heap allocation, use +//! `processFloat32`, `applyMidi`, `writeFeedback` and `writeTelemetry` with +//! caller-owned typed arrays. If you do not need a processor any more, call +//! the generated `free()` method. +use crate::processor::{FEEDBACK_LEN, TELEMETRY_LEN}; use crate::{ - Error, Feedback, PrepareConfig, Processor, ProcessorConfig, SampleRate, Telemetry, TimedEvent, + Error, Feedback, MidiEvent, PrepareConfig, Processor, ProcessorConfig, SampleRate, Telemetry, + TimedEvent, }; -use js_sys::{Float32Array, Int16Array}; +use js_sys::{Float32Array, Int16Array, Uint8Array}; use serde::{Deserialize, Serialize}; use tsify::{Ts, Tsify}; use wasm_bindgen::prelude::*; @@ -76,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 audio processor that JavaScript uses as the `Tunelet` class. /// -/// The input is signed 16-bit mono PCM. The output is planar stereo or an -/// in-place mono downmix. The quantization, latency and configuration behavior -/// are the same as in the native processor. Buffer lengths count frames, not -/// bytes. +/// The input is mono `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 +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. + float_input: Vec, + /// The reusable `f32` buffer for the left channel, which the class copies + /// to the caller only after a successful call. + float_left: Vec, + /// The reusable `f32` buffer for the right channel, which the class copies + /// to the caller only after a successful call. + float_right: Vec, /// The reusable buffers for the two formant envelopes. They become longer /// when a call needs more points, and they do not become shorter. envelope_input: Vec, @@ -149,7 +163,11 @@ impl WasmProcessor { let rate = match sample_rate { 44100.0 => SampleRate::Hz44100, 48000.0 => SampleRate::Hz48000, - _ => return Err(JsError::new("sampleRate must be 44100 or 48000")), + _ => { + return Err(JsError::new(&format!( + "unsupported sampleRate {sample_rate}: must be 44100 or 48000 (for Web Audio, pass {{ sampleRate: 48000 }} to AudioContext)" + ))); + } }; if !(1.0..=f64::from(u32::MAX)).contains(&max_block_frames) || max_block_frames.fract() != 0.0 @@ -170,6 +188,9 @@ impl WasmProcessor { input: pcm_buffer(max_block_frames)?, left: pcm_buffer(max_block_frames)?, right: pcm_buffer(max_block_frames)?, + float_input: float_buffer(max_block_frames)?, + float_left: float_buffer(max_block_frames)?, + float_right: float_buffer(max_block_frames)?, envelope_input: Vec::new(), envelope_output: Vec::new(), }) @@ -295,6 +316,73 @@ impl WasmProcessor { Ok(()) } + /// Processes mono `Float32Array` input into left and right `Float32Array` + /// buffers of equal length. + /// + /// Input samples convert to 16-bit PCM as + /// `(sample * 32768.0).round() as i16`. Finite values in `-1.0..=1.0` map + /// to `-32768..=32767`, values outside that range saturate and `NaN` + /// becomes zero. Rendered samples convert to `Float32` as + /// `sample / 32768.0`. Optional events, empty blocks and drain + /// cancellation obey the same rules as `process`. If you omit `events`, + /// the call does not allocate on the Wasm heap. + /// + /// # Errors + /// + /// The method throws if the channel lengths are not equal, if the block is + /// larger than `maxBlockFrames` or if an event is not valid. On error, the + /// output buffers and the DSP state do not change. + #[wasm_bindgen(js_name = processFloat32)] + pub fn process_float32( + &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.float_input[..frames]); + self.processor.process_planar_f32( + &self.float_input[..frames], + &mut self.float_left[..frames], + &mut self.float_right[..frames], + &events.0, + )?; + left.copy_from(&self.float_left[..frames]); + right.copy_from(&self.float_right[..frames]); + Ok(()) + } + + /// Replaces the audio in a mono `Float32Array` with the stereo downmix. + /// + /// Sample conversion, timing, events and drain cancellation are the same + /// as for `processFloat32`. Peak feedback measures the stereo output + /// before the downmix. + /// + /// # Errors + /// + /// The method throws if the block is too large or an event is not valid. + /// It throws before the caller buffer or the DSP state changes. + #[wasm_bindgen(js_name = processMonoFloat32)] + pub fn process_mono_float32( + &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.float_input[..frames]); + self.processor + .process_mono_in_place_f32(&mut self.float_input[..frames], &events.0)?; + audio.copy_from(&self.float_input[..frames]); + Ok(()) + } + /// Starts a finite tail budget and returns its frame count as a number. /// /// Call this method one time after the final input block. Another call @@ -356,6 +444,55 @@ impl WasmProcessor { Ok(count) } + /// Renders stereo tail frames into `Float32Array` buffers of equal length. + /// + /// Rendered samples convert as `sample / 32768.0`, and unused frames + /// become `0.0`. Return values, empty arrays and completion reset are the + /// same as for `drain`. + /// + /// # Errors + /// + /// The method throws if the channel lengths are not equal or if the block + /// is larger than `maxBlockFrames`. After an error, both output arrays and + /// the drain state do not change. + #[wasm_bindgen(js_name = drainFloat32)] + pub fn drain_float32( + &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.float_left[..frames], + &mut self.float_right[..frames], + )?; + left.copy_from(&self.float_left[..frames]); + right.copy_from(&self.float_right[..frames]); + Ok(count) + } + + /// Renders a mono `Float32Array` tail block and returns its frame count. + /// + /// Unused samples become `0.0`. Downmix, completion and feedback behavior + /// are the same as for `drainMono`. + /// + /// # Errors + /// + /// If the block is larger than `maxBlockFrames`, this method throws before + /// the output or the state changes. + #[wasm_bindgen(js_name = drainMonoFloat32)] + pub fn drain_mono_float32(&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.float_input[..frames])?; + audio.copy_from(&self.float_input[..frames]); + Ok(count) + } + /// Returns a new feedback object and does not clear the peak window. /// /// `processedFrames` is a `bigint`, so its 64-bit count stays exact. @@ -422,6 +559,111 @@ impl WasmProcessor { Ok(telemetry) } + /// Writes the current feedback into a `Float32Array` of length 8 without + /// heap allocation. + /// + /// If `clear_peak` is `true`, the method also clears the stereo peak + /// window. The entries are: + /// + /// - `0`: `resampleRatio` + /// - `1`: `periodSamples` + /// - `2`: `frequencyHz` + /// - `3`: `targetMidiNote`, or `NaN` if unvoiced + /// - `4`: `1.0` if `voiced` is `true`, or `0.0` if `false` + /// - `5`: `peakLevel` + /// - `6`: `processedFrames` rounded to `Float32` + /// - `7`: `latencyFrames` + /// + /// # Errors + /// + /// Throws if `output.length` is not 8. On error, `output` and the peak + /// window do not change. + #[wasm_bindgen(js_name = writeFeedback)] + pub fn write_feedback( + &mut self, + output: &Float32Array, + clear_peak: Option, + ) -> Result<(), JsError> { + let mut values = [0.0_f32; FEEDBACK_LEN]; + Error::check_length(values.len(), output.length() as usize)?; + self.processor + .write_feedback(&mut values, clear_peak.unwrap_or(false))?; + output.copy_from(&values); + Ok(()) + } + + /// Writes the current telemetry into a `Float32Array` of length 45 without + /// heap allocation. + /// + /// If `clear_peaks` is `true`, the method also clears the three peak + /// windows of the telemetry. The entries are: + /// + /// - `0`: `processedFrames` rounded to `Float32` + /// - `1`: `inputPeak` + /// - `2..4`: `outputPeak` (left, then right) + /// - `4`: `reverbWetPeak` + /// - `5`: `clarity` + /// - `6`: `1.0` if `tracking` is `true`, or `0.0` if `false` + /// - `7`: `voiceCount` + /// - `8..24`: `voiceRatios` (16 entries) + /// - `24..40`: `voiceGains` (16 entries) + /// - `40`: `punchGain` + /// - `41`: `warmGain` + /// - `42`: `alienLoopFrames` + /// - `43`: `alienPhaseFrames` + /// - `44`: `formantGeneration` rounded to `Float32` + /// + /// # Errors + /// + /// Throws if `output.length` is not 45. On error, `output` and the peak + /// windows do not change. + #[wasm_bindgen(js_name = writeTelemetry)] + pub fn write_telemetry( + &mut self, + output: &Float32Array, + clear_peaks: Option, + ) -> Result<(), JsError> { + let mut values = [0.0_f32; TELEMETRY_LEN]; + Error::check_length(values.len(), output.length() as usize)?; + self.processor + .write_telemetry(&mut values, clear_peaks.unwrap_or(false))?; + output.copy_from(&values); + Ok(()) + } + + /// Decodes packed 3-byte MIDI messages from a `Uint8Array` and applies + /// them to harmony without Wasm heap allocation. + /// + /// `bytes.length` must be a multiple of three. Each 3-byte message decodes + /// with `MidiEvent::from_bytes`. Unsupported messages with valid byte + /// ranges have no effect. An empty `Uint8Array` is valid. + /// + /// # Errors + /// + /// Throws if `bytes.length` is not a multiple of three, if a status byte + /// is below `0x80` or if a data byte is above 127. All bytes are validated + /// before any state changes. + #[wasm_bindgen(js_name = applyMidi)] + pub fn apply_midi(&mut self, bytes: &Uint8Array) -> Result<(), JsError> { + apply_midi_bytes(bytes, |slice| self.processor.apply_midi(slice)) + } + + /// Decodes packed 3-byte MIDI messages from a `Uint8Array` and applies + /// them to the correction keyboard without Wasm heap allocation. + /// + /// `bytes.length` must be a multiple of three. Each 3-byte message decodes + /// with `MidiEvent::from_bytes`. An empty `Uint8Array` is valid. + /// + /// # Errors + /// + /// Throws if `bytes.length` is not a multiple of three, if a status byte + /// is below `0x80` or if a data byte is above 127. All bytes are validated + /// before any state changes. + #[wasm_bindgen(js_name = applyCorrectionMidi)] + pub fn apply_correction_midi(&mut self, bytes: &Uint8Array) -> Result<(), JsError> { + apply_midi_bytes(bytes, |slice| self.processor.apply_correction_midi(slice)) + } + /// Writes the formant envelopes of the current model into two /// `Float32Array` buffers of equal length. /// @@ -488,6 +730,48 @@ fn decode_events(events: Option>) -> Result Result<(), Error>, +) -> Result<(), JsError> { + let len = bytes.length() as usize; + if !len.is_multiple_of(3) { + return Err(Error::InvalidMidi.into()); + } + let mut stack = [0u8; 768]; + if len <= stack.len() { + let slice = &mut stack[..len]; + bytes.copy_to(slice); + apply(slice)?; + return Ok(()); + } + let mut offset = 0; + while offset < len { + let index = offset as u32; + let message = [ + bytes.get_index(index), + bytes.get_index(index + 1), + bytes.get_index(index + 2), + ]; + MidiEvent::from_bytes(message)?; + offset += 3; + } + offset = 0; + while offset < len { + let index = offset as u32; + let message = [ + bytes.get_index(index), + bytes.get_index(index + 1), + bytes.get_index(index + 2), + ]; + apply(&message)?; + offset += 3; + } + Ok(()) +} + /// Returns the first `points` entries of a reusable envelope buffer. If the /// buffer is shorter, it becomes `points` long first. /// @@ -512,6 +796,17 @@ fn pcm_buffer(frames: usize) -> Result, JsError> { Ok(buffer) } +/// Allocates `f32` audio storage that contains zeros. +/// +/// If the capacity overflows or the allocation fails, this function returns a +/// JavaScript error. It does not panic. +fn float_buffer(frames: usize) -> Result, JsError> { + let mut buffer = Vec::new(); + buffer.try_reserve_exact(frames)?; + buffer.resize(frames, 0.0); + Ok(buffer) +} + /// Serializes the bounded Wasm frame count as a JavaScript number. /// /// The serializer of the feedback structure keeps its other counter, a `u64`, diff --git a/tsconfig.json b/tsconfig.json index 27aa560..79563ed 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -11,5 +11,5 @@ "rootDir": "src", "outDir": "dist" }, - "include": ["src/index.ts"] + "include": ["src/index.ts", "src/utf8.ts"] }