diff --git a/README.md b/README.md index 1b821bc..e854512 100644 --- a/README.md +++ b/README.md @@ -50,8 +50,9 @@ browsers and Node.js. - **No dependencies**: The default Rust build has no dependencies and uses only safe Rust. -The input is mono signed 16-bit PCM at 44.1 kHz or 48 kHz. The output is -stereo or mono 16-bit PCM. +The input is mono signed 16-bit PCM or normalized 32-bit floating-point audio +at 44.1 kHz or 48 kHz. The output is stereo or mono in 16-bit PCM or 32-bit +floating-point form. ## Installation @@ -217,11 +218,19 @@ processor. Select the process function for your output layout: -| Output layout | Function for input | Function for the tail | -| ------------------------------ | ----------------------- | --------------------- | -| `[[i16; 2]]` stereo frames | `process` | `drain` | -| Separate left and right slices | `process_planar` | `drain_planar` | -| Mono slice | `process_mono_in_place` | `drain_mono` | +| Output layout | Function for input | Function for the tail | +| ------------------------------------ | --------------------------- | --------------------- | +| `[[i16; 2]]` stereo frames | `process` | `drain` | +| `[[f32; 2]]` stereo frames | `process_f32` | `drain_f32` | +| Separate `i16` left 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` | + +The `f32` methods convert `NaN` input samples to `0`. They clamp other input +values to `-1.0..=1.0`, multiply by `32767.0` in `f64` and round to `i16`. They +divide each `i16` output sample by `32768.0` and fill unused tail frames with +`0.0`. These rules apply to each call: @@ -277,7 +286,7 @@ The drain gives the tail of the reverb and the voices after the last input block. To get the tail, do these steps: 1. Call `begin_drain()` one time. -2. Call `drain`, `drain_planar` or `drain_mono` until the call returns zero. +2. Call the drain method for your layout until the call returns zero. 3. From each drain call, use only the frames that the call returns. The drain fills the unused output with zeros. The drain has a finite budget, @@ -426,34 +435,86 @@ 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()` | -| Control activity | `controlActivity()` | -| 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?)` | +| Fixed `Float32` buffer offsets | `inputF32Ptr`, `leftF32Ptr`, `rightF32Ptr` | +| Cached `Float32` memory views | `new TuneletAudioViews(memory, processor)` | +| Zero-copy `Float32` stereo | `processF32InPlace(frames, events?)` | +| Zero-copy `Float32` mono | `processMonoF32InPlace(frames, events?)` | +| Configuration | `config()`, `setConfig(config)`, `defaultConfig()` | +| Control activity | `controlActivity()` | +| 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)` | +| Zero-copy `Float32` tail | `beginDrain()`, `drainF32InPlace(frames)`, `drainMonoF32InPlace(frames)` | +| Configured tail budget | `tailFrames()` | +| Reset or release memory | `reset()`, `free()`, `views.dispose()` | ### Audio buffers -All audio buffers are `Int16Array` buffers, and they must fit in the prepared -frame limit. These rules apply: +The package offers copied `Int16Array` and `Float32Array` calls and zero-copy +in-place `Float32` calls. All blocks must fit in `maxBlockFrames`. This +package does not install an AudioWorklet or an integration with an audio +device. + +For `process`, `processMono`, `drain`, `drainMono`, `processF32`, +`processMonoF32`, `drainF32` and `drainMonoF32`, pass `Int16Array` or +`Float32Array` buffers. These rules apply: - Stereo output arrays must not overlap. - The input can overlap an output, because the binding copies the input first. - Buffers must stay attached during each call. -Web Audio uses Float32 samples, which you must convert to and from 16-bit -PCM. This package does not install an AudioWorklet or an integration with an -audio device. +For `Float32` input, `NaN` becomes `0`, and other values clamp to `-1..=1`, +multiply by `32767` in `f64` and round to `-32767..=32767`. Each `Float32` +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`. + +For zero-copy blocks in an AudioWorklet, bind `TuneletAudioViews` to +`InitOutput["memory"]` and a `Tunelet` instance: + +```ts +const wasm = await loadTunelet(); +const processor = new Tunelet(48000, 128); +const views = new TuneletAudioViews(wasm.memory, processor); + +views.input.set(monoChunk); // monoChunk.length <= 128 +processor.processF32InPlace(monoChunk.length); +const left = views.left; +const right = views.right; + +views.dispose(); +processor.free(); +``` + +`inputF32Ptr`, `leftF32Ptr` and `rightF32Ptr` stay at fixed byte offsets until +`processor.free()`. Copied `Float32Array` calls and in-place `Float32` calls +share those three `f32` buffers. Mono in-place calls read and write +`views.input`. Stereo in-place calls read `views.input` and write `views.left` +and `views.right`. + +These lifetime rules apply to `Float32` views: + +- A new `Tunelet`, `setConfig`, `events`, `controlActivity`, feedback, + telemetry or `formantEnvelope` can grow Wasm memory and detach + `memory.buffer`. +- Read `views.input` before each input write so `TuneletAudioViews` checks + `memory.buffer` and refreshes detached views. +- If an in-place call supplies `events`, read `views.left` and `views.right` + (or `views.input` for mono) again after that call. +- When you finish with the views, call `views.dispose()`. +- Do not read or write the views or pointers of an instance after + `processor.free()`, because `free()` returns those buffers to the allocator. ### Configuration objects @@ -518,23 +579,28 @@ call with more points than before reserve memory. ### Memory allocation -The constructor allocates reusable PCM buffers. The processor also keeps an -event buffer and uses its capacity again across calls. A successful call that -processes audio without events does not allocate new Rust PCM storage. -However, the call copies the audio across the boundary between JavaScript and -Wasm. These items can allocate: +The constructor allocates reusable `i16` and `f32` buffers of length +`maxBlockFrames`. The processor also keeps an event buffer and uses its +capacity again across calls. `processF32InPlace`, `processMonoF32InPlace`, +`drainF32InPlace` and `drainMonoF32InPlace` without `events` do not allocate +Rust storage, make JavaScript views or call JavaScript imports. If Wasm memory +does not grow, `TuneletAudioViews` also allocates no new `Float32Array` views +after construction. + +`Int16Array` and `Float32Array` buffer calls copy samples across the boundary +and make temporary views in the generated glue. These operations can also +allocate and grow Wasm memory: -- Object conversion. +- A new `Tunelet` instance. +- Configuration conversion. - Supplied events when a call gives more events than before, or when an event converts a stage configuration. - Errors. - Control activity, feedback and telemetry. - The formant envelopes. -The generated glue can also make temporary views. This binding is for general -use, and it does not guarantee hard real-time behavior for allocation or -scheduling. Drain completion and reset keep the same state as the equivalent -Rust functions. +Drain completion and reset keep the same state as the equivalent Rust +functions. ## Build from source diff --git a/scripts/verify-pack.mjs b/scripts/verify-pack.mjs index 684a904..391b528 100644 --- a/scripts/verify-pack.mjs +++ b/scripts/verify-pack.mjs @@ -246,7 +246,7 @@ function installArchive( ); } -/** Import the installed package in Node.js and check Wasm paths and configs. */ +/** Import the installed package in Node.js and check Wasm, PCM and Float32 paths. */ function verifyRuntimeImport(consumerDir, packageName) { const checkDefaultPath = path.join(consumerDir, "check-default.mjs"); fs.writeFileSync( @@ -277,18 +277,21 @@ function verifyRuntimeImport(consumerDir, packageName) { "assert.equal(rootModule.default, rootModule.loadTunelet);", 'assert.equal(typeof rootModule.initSync, "function");', 'assert.equal(typeof rootModule.Tunelet, "function");', + 'assert.equal(typeof rootModule.TuneletAudioViews, "function");', 'assert.equal(typeof rootModule.defaultConfig, "function");', 'assert.equal(typeof wasmModule.default, "function");', 'assert.equal(typeof wasmModule.initSync, "function");', "", "const wasmExports = await rootModule.loadTunelet();", "assert.ok(wasmExports);", + "assert.ok(wasmExports.memory instanceof WebAssembly.Memory);", "", "const initialConfig = rootModule.defaultConfig();", "initialConfig.resynthesis.harmony.voices = undefined;", "const processor = new rootModule.Tunelet(48000, 128, initialConfig);", "try {", " assert.equal(processor.config().resynthesis.harmony.voices, 4);", + " assert.equal(typeof processor.controlActivity().choirVoices, \"boolean\");", "", " const twoVoiceConfig = processor.config();", " twoVoiceConfig.resynthesis.harmony.voices = 2;", @@ -321,8 +324,179 @@ function verifyRuntimeImport(consumerDir, packageName) { " processor.free();", "}", "", + "const config = rootModule.defaultConfig();", + "config.resynthesis.formant.enabled = true;", + "config.reverb.enabled = true;", + "const pcmProcessor = new rootModule.Tunelet(48000, 128, config);", + "const copiedF32Processor = new rootModule.Tunelet(48000, 128, config);", + "const f32Processor = new rootModule.Tunelet(48000, 128, config);", + "const views = new rootModule.TuneletAudioViews(wasmExports.memory, f32Processor);", + "try {", + " assert.equal(views.maxBlockFrames, 128);", + " assert.equal(views.disposed, false);", + " const initPtrs = [", + " f32Processor.inputF32Ptr,", + " f32Processor.leftF32Ptr,", + " f32Processor.rightF32Ptr,", + " ];", + " assert.equal(initPtrs[0] % 4, 0);", + " assert.equal(initPtrs[1] % 4, 0);", + " assert.equal(initPtrs[2] % 4, 0);", + " assert.equal(views.input.length, 128);", + " assert.equal(views.left.length, 128);", + " assert.equal(views.right.length, 128);", + " assert.equal(views.input, views.input);", + "", + " const pcmInput = new Int16Array(128);", + " const pcmLeft = new Int16Array(128);", + " const pcmRight = new Int16Array(128);", + " const inputF32 = new Float32Array(128);", + " const leftF32 = new Float32Array(128);", + " const rightF32 = new Float32Array(128);", + " for (let block = 0; block < 20; block++) {", + " const f32In = views.input;", + " for (let i = 0; i < 128; i++) {", + " const sample = Math.fround(0.6 * Math.sin(((block * 128 + i) * 2 * Math.PI * 220) / 48000));", + " f32In[i] = sample;", + " inputF32[i] = sample;", + " pcmInput[i] = Math.round(Math.max(-1, Math.min(1, sample)) * 32767);", + " }", + " pcmProcessor.process(pcmInput, pcmLeft, pcmRight);", + " copiedF32Processor.processF32(inputF32, leftF32, rightF32);", + " f32Processor.processF32InPlace(128);", + " const f32Left = views.left;", + " const f32Right = views.right;", + " for (let i = 0; i < 128; i++) {", + " const expectedL = Math.fround(pcmLeft[i] / 32768);", + " const expectedR = Math.fround(pcmRight[i] / 32768);", + " assert.equal(leftF32[i], expectedL);", + " assert.equal(rightF32[i], expectedR);", + " assert.equal(f32Left[i], expectedL);", + " assert.equal(f32Right[i], expectedR);", + " }", + " }", + "", + " const beforeBuffer = wasmExports.memory.buffer;", + " const standby = new rootModule.Tunelet(48000, 2048, config);", + " try {", + " const envIn = new Float32Array(262144);", + " const envOut = new Float32Array(262144);", + " f32Processor.formantEnvelope(12000, envIn, envOut);", + " } finally {", + " standby.free();", + " }", + " assert.notEqual(wasmExports.memory.buffer, beforeBuffer);", + "", + " const reboundInput = views.input;", + " reboundInput.fill(0.25, 0, 64);", + " inputF32.fill(0.25, 0, 64);", + " const gainEvents = [{ offset: 0, event: { type: \"outputGain\", value: 0.75 } }];", + " f32Processor.processF32InPlace(64, gainEvents);", + " copiedF32Processor.processF32(", + " inputF32.subarray(0, 64),", + " leftF32.subarray(0, 64),", + " rightF32.subarray(0, 64),", + " gainEvents,", + " );", + " pcmInput.fill(Math.round(Math.fround(0.25) * 32767), 0, 64);", + " pcmProcessor.process(", + " pcmInput.subarray(0, 64),", + " pcmLeft.subarray(0, 64),", + " pcmRight.subarray(0, 64),", + " gainEvents,", + " );", + " for (let i = 0; i < 64; i++) {", + " assert.equal(views.left[i], Math.fround(pcmLeft[i] / 32768));", + " assert.equal(views.right[i], Math.fround(pcmRight[i] / 32768));", + " assert.equal(leftF32[i], views.left[i]);", + " assert.equal(rightF32[i], views.right[i]);", + " }", + " assert.deepEqual(", + " [f32Processor.inputF32Ptr, f32Processor.leftF32Ptr, f32Processor.rightF32Ptr],", + " initPtrs,", + " );", + "", + " const framesBeforeError = f32Processor.feedback().processedFrames;", + " const savedLeft0 = views.left[0];", + " assert.throws(() => f32Processor.processF32InPlace(129));", + " assert.throws(() => f32Processor.processF32InPlace(-1));", + " assert.throws(() => f32Processor.processF32InPlace(1.5));", + " assert.throws(() =>", + " f32Processor.processF32InPlace(64, [{ offset: 64, event: { type: \"reset\" } }]),", + " );", + " assert.equal(f32Processor.feedback().processedFrames, framesBeforeError);", + " assert.equal(views.left[0], savedLeft0);", + "", + " pcmProcessor.beginDrain();", + " copiedF32Processor.beginDrain();", + " f32Processor.beginDrain();", + " const pcmCount = pcmProcessor.drain(pcmLeft, pcmRight);", + " const copiedCount = copiedF32Processor.drainF32(leftF32, rightF32);", + " const f32Count = f32Processor.drainF32InPlace(128);", + " assert.equal(copiedCount, pcmCount);", + " assert.equal(f32Count, pcmCount);", + " for (let i = 0; i < 128; i++) {", + " assert.equal(views.left[i], Math.fround(pcmLeft[i] / 32768));", + " assert.equal(views.right[i], Math.fround(pcmRight[i] / 32768));", + " assert.equal(leftF32[i], views.left[i]);", + " assert.equal(rightF32[i], views.right[i]);", + " }", + "", + " const monoPcm = new rootModule.Tunelet(48000, 64, config);", + " const monoCopiedF32 = new rootModule.Tunelet(48000, 64, config);", + " const monoF32 = new rootModule.Tunelet(48000, 64, config);", + " const monoViews = new rootModule.TuneletAudioViews(wasmExports.memory, monoF32);", + " try {", + " const monoBuf = new Int16Array(64);", + " const monoCopiedBuf = new Float32Array(64);", + " for (let i = 0; i < 64; i++) {", + " monoViews.input[i] = 0.5;", + " monoCopiedBuf[i] = 0.5;", + " monoBuf[i] = Math.round(0.5 * 32767);", + " }", + " monoPcm.processMono(monoBuf);", + " monoCopiedF32.processMonoF32(monoCopiedBuf);", + " monoF32.processMonoF32InPlace(64);", + " for (let i = 0; i < 64; i++) {", + " const expected = Math.fround(monoBuf[i] / 32768);", + " assert.equal(monoCopiedBuf[i], expected);", + " assert.equal(monoViews.input[i], expected);", + " }", + " monoPcm.beginDrain();", + " monoCopiedF32.beginDrain();", + " monoF32.beginDrain();", + " const expectedDrain = monoPcm.drainMono(monoBuf);", + " assert.equal(monoCopiedF32.drainMonoF32(monoCopiedBuf), expectedDrain);", + " assert.equal(monoF32.drainMonoF32InPlace(64), expectedDrain);", + " for (let i = 0; i < 64; i++) {", + " const expected = Math.fround(monoBuf[i] / 32768);", + " assert.equal(monoCopiedBuf[i], expected);", + " assert.equal(monoViews.input[i], expected);", + " }", + " } finally {", + " monoViews.dispose();", + " monoPcm.free();", + " monoCopiedF32.free();", + " monoF32.free();", + " }", + "} finally {", + " views.dispose();", + " assert.equal(views.disposed, true);", + " assert.throws(() => views.input);", + " assert.throws(() => views.left);", + " assert.throws(() => views.right);", + " assert.throws(() => views.refresh());", + " pcmProcessor.free();", + " copiedF32Processor.free();", + " f32Processor.free();", + "}", + "", 'assert.equal(typeof Symbol.dispose, "symbol");', "const disposableProcessor = new rootModule.Tunelet(48000, 128);", + "const disposableViews = new rootModule.TuneletAudioViews(wasmExports.memory, disposableProcessor);", + 'assert.equal(typeof disposableViews[Symbol.dispose], "function");', + "disposableViews[Symbol.dispose]();", + "assert.equal(disposableViews.disposed, true);", 'assert.equal(typeof disposableProcessor[Symbol.dispose], "function");', "disposableProcessor[Symbol.dispose]();", "", @@ -500,6 +674,8 @@ function verifyTypeDeclarations(consumerDir, packageName) { " initSync as rootInitSync,", " loadTunelet as namedLoadTunelet,", " Tunelet,", + " TuneletAudioViews,", + " type ControlActivity,", " type ProcessorConfig,", " type ResynthesisConfig,", " type SyncInitInput as RootSyncInitInput,", @@ -545,10 +721,30 @@ function verifyTypeDeclarations(consumerDir, packageName) { " 128,", " configWithUndefined,", " );", + " using disposableViews = new TuneletAudioViews(", + " exportsFromRoot.memory,", + " disposableProcessor,", + " );", + " disposableViews.input.fill(0);", " disposableProcessor.reset();", " }", " const processor = new Tunelet(48000, 128, configWithUndefined);", " processor.setConfig(configWithUndefined);", + " const activity: ControlActivity = processor.controlActivity();", + " const views = new TuneletAudioViews(exportsFromRoot.memory, processor);", + " const ptrs: [number, number, number] = [", + " processor.inputF32Ptr,", + " processor.leftF32Ptr,", + " processor.rightF32Ptr,", + " ];", + " views.input.fill(0);", + " processor.processF32InPlace(128);", + " const stereoOut: [Float32Array, Float32Array] = [views.left, views.right];", + " processor.processMonoF32InPlace(128);", + " processor.beginDrain();", + " const stereoTail: number = processor.drainF32InPlace(128);", + " const monoTail: number = processor.drainMonoF32InPlace(128);", + " views.refresh();", " const resynthesisUpdate: ResynthesisConfig = {", " ...configWithUndefined.resynthesis,", " harmony: {", @@ -563,7 +759,31 @@ function verifyTypeDeclarations(consumerDir, packageName) { ' { offset: 0, event: { type: "resynthesis", value: resynthesisUpdate } },', " ]);", " processor.process(input, left, right);", + " 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);", + " views.dispose();", " processor.free();", + " void activity;", + " void ptrs;", + " void stereoOut;", + " void stereoTail;", + " void monoTail;", + " void drained;", + " void drainedMono;", + " void drainedF32;", + " void drainedMonoF32;", " void exportsFromNamed;", " void exportsFromWasm;", " void syncExportsFromRoot;", @@ -660,6 +880,7 @@ function verifyTypeDeclarations(consumerDir, packageName) { " url: URL,", " bufferSource: BufferSource,", " wasmModule: WebAssembly.Module,", + " wasmMemory: WebAssembly.Memory,", " voices?: number,", "): Promise {", " await loadTunelet(reqInfo);", @@ -669,6 +890,10 @@ function verifyTypeDeclarations(consumerDir, packageName) { " await loadTunelet(url);", " await loadTunelet(bufferSource);", " const out = await verifySharedApi(wasmModule, wasmModule, voices);", + " const domProc = new Tunelet(48000, 128);", + " const domViews = new TuneletAudioViews(wasmMemory, domProc);", + " domViews.dispose();", + " domProc.free();", " const table: WebAssembly.Table = out.__wbindgen_externrefs;", " void table;", " void window;", @@ -698,6 +923,7 @@ function verifyTypeDeclarations(consumerDir, packageName) { " url: URL,", " bufferSource: BufferSource,", " wasmModule: WebAssembly.Module,", + " wasmMemory: WebAssembly.Memory,", " voices?: number,", "): Promise {", " await loadTunelet(reqInfo);", @@ -706,6 +932,10 @@ function verifyTypeDeclarations(consumerDir, packageName) { " await loadTunelet(url);", " await loadTunelet(bufferSource);", " const out = await verifySharedApi(wasmModule, wasmModule, voices);", + " const workerProc = new Tunelet(48000, 128);", + " const workerViews = new TuneletAudioViews(wasmMemory, workerProc);", + " workerViews.dispose();", + " workerProc.free();", " const table: WebAssembly.Table = out.__wbindgen_externrefs;", " void table;", " void self;", diff --git a/src/index.ts b/src/index.ts index 8ad1dd3..4f6e6e1 100644 --- a/src/index.ts +++ b/src/index.ts @@ -3,16 +3,132 @@ * * 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, control-activity, event and feedback - * types. + * same Wasm binary. This module exports `TuneletAudioViews` and re-exports all + * named exports of the module that wasm-bindgen generates. Those exports + * include `Tunelet`, `defaultConfig`, `initSync` and the configuration, + * control-activity, event and feedback types. */ import init from "../pkg/tunelet.js"; -import type { InitInput, InitOutput } from "../pkg/tunelet.js"; +import type { InitInput, InitOutput, Tunelet } from "../pkg/tunelet.js"; export * from "../pkg/tunelet.js"; +/** + * Cached `Float32Array` views over the in-place `Tunelet` buffers in Wasm + * linear memory. + * + * Each access to `input`, `left` or `right` checks `memory.buffer`. If Wasm + * memory grew and detached the previous `ArrayBuffer`, the helper binds the + * three fixed pointers of `processor` to the new buffer. If `memory.buffer` did + * not change, the helper returns the cached views with no allocation. + * + * Read `input` before you write input samples. If an in-place call passes + * `events`, read `left` and `right` (or `input` for mono) after that call. + * When you call `processor.free()`, also call `dispose()`. Do not use the views + * after `processor.free()`. + */ +export class TuneletAudioViews { + private readonly memory: InitOutput["memory"]; + private processor: Tunelet | null; + /** The fixed frame capacity of `input`, `left` and `right`. */ + readonly maxBlockFrames: number; + private cachedBuffer: ArrayBuffer | null = null; + private inputView: Float32Array | null = null; + private leftView: Float32Array | null = null; + private rightView: Float32Array | null = null; + + /** + * Binds `Float32Array` views for `processor` over `memory`. + * + * @param memory The Wasm memory from `InitOutput["memory"]`. + * @param processor The live `Tunelet` instance that owns the buffers. + */ + constructor(memory: InitOutput["memory"], processor: Tunelet) { + this.memory = memory; + this.processor = processor; + this.maxBlockFrames = processor.maxBlockFrames; + this.refresh(); + } + + /** Returns `true` after `dispose()` clears the cached views. */ + get disposed(): boolean { + return this.processor === null; + } + + /** + * Returns the `Float32Array` view for mono input and in-place mono output. + * + * If `memory.buffer` changed, this getter refreshes all three views first. + */ + get input(): Float32Array { + this.refresh(); + return this.inputView!; + } + + /** + * Returns the `Float32Array` view for the left stereo output channel. + * + * If `memory.buffer` changed, this getter refreshes all three views first. + */ + get left(): Float32Array { + this.refresh(); + return this.leftView!; + } + + /** + * Returns the `Float32Array` view for the right stereo output channel. + * + * If `memory.buffer` changed, this getter refreshes all three views first. + */ + get right(): Float32Array { + this.refresh(); + return this.rightView!; + } + + /** + * If Wasm memory grew, this method refreshes the three `Float32Array` views + * from `memory.buffer`. + */ + refresh(): void { + const processor = this.processor; + if (processor === null) { + throw new Error("TuneletAudioViews is disposed"); + } + const buffer = this.memory.buffer; + if (this.cachedBuffer !== buffer) { + const frames = this.maxBlockFrames; + const inputPtr = processor.inputF32Ptr; + const leftPtr = processor.leftF32Ptr; + const rightPtr = processor.rightF32Ptr; + const input = new Float32Array(buffer, inputPtr, frames); + const left = new Float32Array(buffer, leftPtr, frames); + const right = new Float32Array(buffer, rightPtr, frames); + this.inputView = input; + this.leftView = left; + this.rightView = right; + this.cachedBuffer = buffer; + } + } + + /** Clears the cached `ArrayBuffer`, `Float32Array` views and processor link. */ + dispose(): void { + this.processor = null; + this.cachedBuffer = null; + this.inputView = null; + this.leftView = null; + this.rightView = null; + } +} + +export interface TuneletAudioViews { + [Symbol.dispose](): void; +} + +if (Symbol.dispose) { + TuneletAudioViews.prototype[Symbol.dispose] = + TuneletAudioViews.prototype.dispose; +} + /** The shared initialization promise, which a failure clears. */ let initialization: Promise | undefined; diff --git a/src/lib.rs b/src/lib.rs index 34a4ba9..171bca7 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 @@ -95,9 +105,9 @@ //! //! To export JavaScript bindings and generated TypeScript definitions, enable //! the optional `wasm` feature for `wasm32-unknown-unknown`. The binding owns -//! PCM buffers that it uses again. Configuration conversion, event conversion, -//! feedback objects and errors cause more allocation at the JavaScript -//! boundary. +//! reusable `i16` and `f32` buffers, and exposes fixed `f32` pointers for +//! in-place audio. Configuration conversion, event conversion, feedback objects +//! and errors cause more allocation at the JavaScript boundary. //! Refer to the README for how to build the shared package for browsers and //! Node.js. diff --git a/src/processor.rs b/src/processor.rs index 942826b..c728916 100644 --- a/src/processor.rs +++ b/src/processor.rs @@ -230,6 +230,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. /// @@ -312,6 +399,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 @@ -770,6 +924,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 4b7abee..a9b1ab3 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -9,10 +9,12 @@ //! wasm-pack can do the two steps in one command. The npm entry point uses //! `loadTunelet()` to initialize these bindings in browsers and in Node.js. //! -//! The exported `Tunelet` class owns a native [`Processor`] and three reusable -//! PCM buffers. JavaScript gives the `Int16Array` input and output buffers. The -//! PCM API does not give buffer pointers or long-lived memory views to -//! JavaScript. The class copies the input before it writes the output. +//! The exported `Tunelet` class owns a native [`Processor`], three reusable +//! `i16` PCM buffers and three fixed-capacity `f32` buffers. JavaScript can +//! pass `Int16Array` or `Float32Array` buffers, which the class copies in and +//! out on each call. JavaScript can also read `inputF32Ptr`, `leftF32Ptr` and +//! `rightF32Ptr` to process `Float32Array` views over Wasm linear memory in +//! place. //! //! Configuration objects obey these rules: //! @@ -38,10 +40,12 @@ //! - The buffers of the formant envelopes. //! - Errors. //! -//! The JavaScript glue can also make temporary views when it copies data. This -//! generic binding does not guarantee an AudioWorklet callback that is free of -//! allocation. If you do not need a processor any more, call the generated -//! `free()` method. +//! When the JavaScript glue copies `Int16Array` or `Float32Array` arguments, +//! it makes temporary views. By contrast, in-place `Float32` calls without +//! events do not allocate or call JavaScript imports. If Wasm memory grows, +//! previous `ArrayBuffer` views detach, so recheck `memory.buffer` before you +//! read or write views. If you do not need a processor any more, call `free()` +//! and do not touch its views again. use crate::events::ValidatedEvents; use crate::processor::EnvelopeKey; @@ -81,20 +85,30 @@ 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, the output +/// scale, the latency and the configuration behavior match [`Processor`]. +/// Buffer lengths and frame arguments count frames, not bytes. /// -/// These rules apply to the buffers: +/// These rules apply to `Int16Array` and `Float32Array` buffer arguments: /// /// - Separate stereo output arrays must not overlap. /// - The input can overlap an output, because the class copies the input /// first. /// - All buffers must stay attached until each call is complete. /// +/// These rules apply to in-place `Float32` calls: +/// +/// - `inputF32Ptr`, `leftF32Ptr` and `rightF32Ptr` are fixed byte offsets for +/// `maxBlockFrames` `f32` samples until `free()`. +/// - `Float32Array` buffer calls and in-place `Float32` calls share those +/// three `f32` buffers. +/// - Check `memory.buffer` before input writes and after calls that pass +/// `events`, because Wasm memory growth detaches old views. +/// - Do not read or write the views of an instance after `free()`. +/// /// If a call that processes audio fails, it throws a JavaScript `Error` before /// the audio state or the output changes. The class rejects malformed /// configuration objects and malformed event objects. It also rejects values @@ -114,6 +128,12 @@ pub struct WasmProcessor { /// The reusable PCM buffer for the right channel, which the class copies to /// the caller only after a successful call. right: Vec, + /// The fixed-capacity `f32` buffer for mono input and in-place mono output. + input_f32: Vec, + /// The fixed-capacity `f32` buffer for the left stereo output channel. + left_f32: Vec, + /// The fixed-capacity `f32` buffer for the right stereo output channel. + right_f32: Vec, /// The reusable buffers for the two formant envelopes. They become longer /// when a call needs more points, and they do not become shorter. envelope_input: Vec, @@ -181,6 +201,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(), envelope_cache: None, @@ -188,6 +211,34 @@ impl WasmProcessor { }) } + /// The byte offset in Wasm memory of the `maxBlockFrames` `f32` input + /// buffer. + /// + /// Mono in-place calls also write their output to this buffer. This offset + /// stays constant until `free()`. + #[wasm_bindgen(getter, js_name = inputF32Ptr)] + pub fn input_f32_ptr(&self) -> usize { + self.input_f32.as_ptr() as usize + } + + /// The byte offset in Wasm memory of the `maxBlockFrames` left `f32` + /// output buffer. + /// + /// This offset stays constant until `free()`. + #[wasm_bindgen(getter, js_name = leftF32Ptr)] + pub fn left_f32_ptr(&self) -> usize { + self.left_f32.as_ptr() as usize + } + + /// The byte offset in Wasm memory of the `maxBlockFrames` right `f32` + /// output buffer. + /// + /// This offset stays constant until `free()`. + #[wasm_bindgen(getter, js_name = rightF32Ptr)] + pub fn right_f32_ptr(&self) -> usize { + self.right_f32.as_ptr() as usize + } + /// The sample rate of the input and the output in hertz. /// /// The constructor sets this value, and the value does not change. @@ -314,6 +365,141 @@ 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(()) + } + + /// Processes `frames` samples from `inputF32Ptr` into `leftF32Ptr` and + /// `rightF32Ptr`. + /// + /// `frames` must be an integer in `0..=maxBlockFrames`. Input quantization, + /// the output scale, timed events and drain cancellation match + /// [`Processor::process_planar_f32`]. If you pass `events`, recheck + /// `memory.buffer` before you read the output views. + /// + /// # Errors + /// + /// If `frames` is not an integer in `0..=maxBlockFrames`, or if an event is + /// not valid, this method throws. All checks finish before the buffers or + /// the DSP state change. + #[wasm_bindgen(js_name = processF32InPlace)] + pub fn process_f32_in_place( + &mut self, + frames: f64, + events: Option>, + ) -> Result<(), JsError> { + let frames = self.check_frames(frames)?; + let events = match events { + Some(events) => decode_events(&mut self.events, events, frames)?, + None => &[], + }; + self.processor.process_planar_f32( + &self.input_f32[..frames], + &mut self.left_f32[..frames], + &mut self.right_f32[..frames], + events, + )?; + Ok(()) + } + + /// Replaces `frames` samples at `inputF32Ptr` with the mono `f32` downmix. + /// + /// `frames` must be an integer in `0..=maxBlockFrames`. Input quantization, + /// the output scale, peak measurements, events and drain cancellation match + /// [`Processor::process_mono_in_place_f32`]. If you pass `events`, recheck + /// `memory.buffer` before you read the output view. + /// + /// # Errors + /// + /// If `frames` is not an integer in `0..=maxBlockFrames`, or if an event is + /// not valid, this method throws. All checks finish before the buffer or + /// the DSP state changes. + #[wasm_bindgen(js_name = processMonoF32InPlace)] + pub fn process_mono_f32_in_place( + &mut self, + frames: f64, + events: Option>, + ) -> Result<(), JsError> { + let frames = self.check_frames(frames)?; + let events = match events { + Some(events) => decode_events(&mut self.events, events, frames)?, + None => &[], + }; + self.processor + .process_mono_in_place_f32(&mut self.input_f32[..frames], events)?; + 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 @@ -375,6 +561,94 @@ 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) + } + + /// Renders up to `frames` stereo tail frames into `leftF32Ptr` and + /// `rightF32Ptr`. + /// + /// `frames` must be an integer in `0..=maxBlockFrames`. The method returns + /// the rendered frame count and fills unused frames up to `frames` with + /// `0.0`. Empty blocks and drain completion match `drain`. + /// + /// # Errors + /// + /// If `frames` is not an integer in `0..=maxBlockFrames`, this method + /// throws. On error, the output buffers and the drain state do not change. + #[wasm_bindgen(js_name = drainF32InPlace)] + pub fn drain_f32_in_place(&mut self, frames: f64) -> Result { + let frames = self.check_frames(frames)?; + Ok(self + .processor + .drain_planar_f32(&mut self.left_f32[..frames], &mut self.right_f32[..frames])?) + } + + /// Renders up to `frames` mono tail frames into `inputF32Ptr` and returns + /// their count. + /// + /// `frames` must be an integer in `0..=maxBlockFrames`. The method fills + /// unused samples up to `frames` with `0.0`. The downmix, the output scale, + /// empty blocks and drain completion match `drainMono`. + /// + /// # Errors + /// + /// If `frames` is not an integer in `0..=maxBlockFrames`, this method + /// throws. On error, the output buffer and the drain state do not change. + #[wasm_bindgen(js_name = drainMonoF32InPlace)] + pub fn drain_mono_f32_in_place(&mut self, frames: f64) -> Result { + let frames = self.check_frames(frames)?; + Ok(self + .processor + .drain_mono_f32(&mut self.input_f32[..frames])?) + } + /// Returns a new feedback object and does not clear the peak window. /// /// `processedFrames` is a `bigint`, so its 64-bit count stays exact. @@ -520,6 +794,17 @@ impl WasmProcessor { pub fn reset(&mut self) { self.processor.reset(); } + + /// Validates a JavaScript frame count before buffer slices or DSP state + /// change. + fn check_frames(&self, frames: f64) -> Result { + if !(0.0..=f64::from(u32::MAX)).contains(&frames) || frames.fract() != 0.0 { + return Err(JsError::new("frames must be an integer in 0..=4294967295")); + } + let frames = frames as usize; + self.processor.check_block(frames)?; + Ok(frames) + } } /// The cached property keys and variant names for JavaScript events. @@ -749,6 +1034,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`,