diff --git a/AGENTS.md b/AGENTS.md index 4bc6d47..900c3f7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -40,10 +40,13 @@ this file, rustdoc, code comments, TypeScript comments and commit messages. - Make the smallest possible change. Do not rename, move or format code that is not part of the task. -- The public API is all items that `src/lib.rs` exports, `src/wasm.rs` - and `src/index.ts`. Do not add, change or remove public items if the - task does not tell you to. Keep the Rust, Wasm and TypeScript APIs - equivalent. +- The public API is all items that `src/lib.rs`, `src/wasm.rs`, + `src/index.ts`, `src/worklet.ts` and `src/worklet-processor.ts` + export. Do not add, change or remove public items if the task does not + tell you to. Keep the Rust, Wasm and TypeScript APIs equivalent. As an + explicit exception, `TuneletFloat32`, `loadTuneletWasm` and the + `AudioWorklet` modules exist only in TypeScript, while native Rust + `Processor` uses `i16`. - Keep the crate lints in `src/lib.rs`: `#![forbid(unsafe_code)]`, `#![deny(missing_docs)]`, `#![deny(rustdoc::broken_intra_doc_links)]` and `#![warn(unreachable_pub)]`. Each public item must have rustdoc @@ -85,8 +88,9 @@ this file, rustdoc, code comments, TypeScript comments and commit messages. - `src/numeric.rs`, `src/numeric/`: the fixed-point functions, the random number generator and the lookup tables. - `src/wasm.rs`: the wasm-bindgen and tsify bindings (`wasm` feature). -- `src/index.ts`: the `loadTunelet` entry point. See also `package.json` - and `tsconfig.json`. +- `src/index.ts`, `src/worklet.ts`, `src/worklet-processor.ts`: + `loadTunelet`, `loadTuneletWasm`, `TuneletFloat32` and the Web Audio + worklet modules. See also `package.json` and `tsconfig.json`. ## Build and verify @@ -102,7 +106,7 @@ RUSTDOCFLAGS="-D warnings" cargo doc --locked --no-deps --target wasm32-unknown- If you change the Wasm or TypeScript code, also run these commands. `npm run check:wasm` runs Clippy and rustdoc for `wasm32-unknown-unknown`. -`npm run build` compiles `src/wasm.rs` and `src/index.ts`. +`npm run build` compiles `src/wasm.rs` and the TypeScript modules in `src/`. `npm run verify:pack` runs `npm run build` and checks the archives: ```sh diff --git a/README.md b/README.md index 83a8f47..a1a255a 100644 --- a/README.md +++ b/README.md @@ -359,21 +359,26 @@ 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 +The npm package is an ES module package for browsers and Node.js. It contains these items: - One Wasm binary. -- The generated bindings. -- A shared `loadTunelet` entry point. +- The generated bindings (`tunelet/wasm`). +- A shared root entry point (`tunelet`) with `loadTunelet`, `loadTuneletWasm`, + `Tunelet` and `TuneletFloat32`. +- Web Audio worklet modules (`tunelet/worklet` and + `tunelet/worklet-processor`). ### Load the module Both environments use the same imports and the same initialization call. An import of the package does not load the binary. Call `loadTunelet()` before -you use `Tunelet` or `defaultConfig()`. +you use `Tunelet`, `TuneletFloat32` or `defaultConfig()`. - Node.js reads the packaged binary from a file URL relative to the module. - Browsers fetch the served Wasm asset. +- In `AudioWorkletGlobalScope`, a default `loadTunelet()` call rejects with an + error because `fetch` is not available. Concurrent calls share one initialization promise. The package keeps the result of a successful initialization. If a load fails, the promise rejects, @@ -393,6 +398,12 @@ rules. The first concurrent call selects the source. Later arguments do not replace an initialized module. A custom binary must match the generated bindings. +To prepare Wasm for an `AudioWorklet`, call `loadTuneletWasm(source?)` on the +main thread. It resolves the binary into an `ArrayBuffer` or a +`WebAssembly.Module` without `fetch` inside the worklet. Then pass that module +or byte buffer to `initSync({ module })` in `AudioWorkletGlobalScope`, or call +`createTuneletWorkletNode` from `tunelet/worklet`. + 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 @@ -401,12 +412,13 @@ gives only ESM exports. CommonJS applications can use `await import("tunelet")`. ### Deployment -Browser bundlers must keep or emit the Wasm asset that +Browser bundlers must keep or emit the Wasm asset and the worklet module that `new URL(..., import.meta.url)` refers to. For a browser deployment without a bundler, do these steps: 1. Serve `dist/` and `pkg/`, and keep their relative layout. -2. Map the `tunelet` import to `dist/index.js`, or import that URL directly. +2. Map `tunelet` to `dist/index.js` and `tunelet/worklet` to `dist/worklet.js`, + or import those URLs directly. Serve the assets over HTTP(S). The package does not support a local `file:` page that opens the JavaScript. @@ -415,8 +427,10 @@ page that opens the JavaScript. | Operation | TypeScript API | | --------------------------------- | -------------------------------------------------------- | -| Shared initialization | `loadTunelet(source?)` | -| Mono PCM to planar stereo | `process(input, left, right, events?)` | +| Shared initialization | `loadTunelet(source?)`, `loadTuneletWasm(source?)` | +| Processor classes | `Tunelet` (`Int16Array`), `TuneletFloat32` (`Float32Array`) | +| Web Audio worklet | `createTuneletWorkletNode(context, options?)`, `TuneletWorkletNode` | +| Mono audio 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` | @@ -429,17 +443,66 @@ page that opens the JavaScript. ### Audio buffers -All audio buffers are `Int16Array` buffers, and they must fit in the prepared -frame limit. These rules apply: +`Tunelet` accepts `Int16Array` buffers, and `TuneletFloat32` accepts +`Float32Array` buffers. Every call must fit in the prepared `maxBlockFrames` +limit. These rules apply to both classes: - Stereo output arrays must not overlap. -- The input can overlap an output, because the binding copies the input +- The input can overlap an output, because the processor 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. +`TuneletFloat32` preallocates three `Int16Array` buffers (`input`, `left` and +`right`) at construction. It maps `NaN` to zero, clamps `Float32Array` inputs +to `-1.0..=1.0`, calls `Tunelet` and multiplies outputs by `1.0 / 32768.0`: + +```ts +import { loadTunelet, TuneletFloat32 } from "tunelet"; + +await loadTunelet(); +const processor = new TuneletFloat32(48000, 1024); +const input = new Float32Array(1024); +const left = new Float32Array(1024); +const right = new Float32Array(1024); +processor.process(input, left, right); +processor.free(); +``` + +Native Rust hosts, such as [`cpal`](https://docs.rs/cpal/latest/cpal/) streams +that supply `f32` slices, still use the `i16` methods on `Processor` and +convert samples in the host. `TuneletFloat32`, `loadTuneletWasm` and the +`AudioWorklet` modules exist only in TypeScript as an explicit exception to +the API equivalence rule in `AGENTS.md`. + +### Web Audio AudioWorklet + +Import `createTuneletWorkletNode` from `tunelet/worklet` on the main thread to +connect `tunelet` into a Web Audio graph: + +```ts +import { createTuneletWorkletNode } from "tunelet/worklet"; + +const context = new AudioContext({ sampleRate: 48000 }); +const node = await createTuneletWorkletNode(context); +sourceNode.connect(node).connect(context.destination); +``` + +`createTuneletWorkletNode` loads the Wasm bytes on the main thread, registers +`tunelet/worklet-processor` on `context.audioWorklet` and passes the binary in +`processorOptions` to `initSync`. The worklet does not call `fetch`. + +Sample rates outside 44.1 kHz and 48 kHz are out of scope. Both +`createTuneletWorkletNode` and `TuneletWorkletNode` reject unsupported +`AudioContext` sample rates before they create a node. + +`TuneletWorkletProcessor` preallocates `Float32Array` scratch arrays and +processes Web Audio blocks in chunks of at most `maxBlockFrames` (128 by +default). `TuneletWorkletNode` communicates with the processor over +`MessagePort` through `config()`, `setConfig(config)`, `sendMidi(event)`, +`sendCorrectionMidi(event)`, `sendControl(event)`, `sendEvents(events)`, +`reset()`, `beginDrain()`, `waitForDrain()`, `feedback()`, `takeFeedback()`, +`telemetry()`, `takeTelemetry()`, `formantEnvelope(maxFrequencyHz, points)` and +`free()`. ### Configuration objects @@ -502,21 +565,24 @@ 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 constructors of `Tunelet`, `TuneletFloat32` and `TuneletWorkletProcessor` +preallocate their reusable PCM conversion and scratch buffers. A successful +steady-state call that processes or drains audio without events does not +allocate new Rust PCM storage or new JavaScript conversion buffers. However, +the call copies the audio across the boundary between JavaScript and Wasm. +These items can allocate: - Object conversion. -- Supplied events. +- Supplied events and `MessagePort` messages. - Errors. - 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. +As `src/wasm.rs` notes, the generated `wasm-bindgen` glue can also make +temporary views on Wasm memory when it copies data. These bindings are for +general use, and they do not guarantee hard real-time behavior or an +`AudioWorklet` callback that is free of allocation. Drain completion and reset +keep the same state as the equivalent Rust functions. ## Build from source diff --git a/package.json b/package.json index 8c201f6..1b33b5a 100644 --- a/package.json +++ b/package.json @@ -15,6 +15,14 @@ "types": "./dist/index.d.ts", "import": "./dist/index.js" }, + "./worklet": { + "types": "./dist/worklet.d.ts", + "import": "./dist/worklet.js" + }, + "./worklet-processor": { + "types": "./dist/worklet-processor.d.ts", + "import": "./dist/worklet-processor.js" + }, "./wasm": { "types": "./pkg/tunelet.d.ts", "import": "./pkg/tunelet.js" @@ -26,7 +34,10 @@ "pkg/tunelet.d.ts", "pkg/tunelet_bg.wasm" ], - "sideEffects": false, + "sideEffects": [ + "./dist/text-codec-shim.js", + "./dist/worklet-processor.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..be4b873 100644 --- a/scripts/verify-pack.mjs +++ b/scripts/verify-pack.mjs @@ -1,6 +1,6 @@ /** - * This script packs the npm archive, checks its eight files, runs - * `loadTunelet()` and checks the TypeScript declarations. + * This script packs the npm archive, checks its files, runs `loadTunelet()` + * and checks the TypeScript declarations. */ import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; @@ -14,6 +14,14 @@ const EXPECTED_ARCHIVE_PATHS = [ "package/README.md", "package/dist/index.d.ts", "package/dist/index.js", + "package/dist/text-codec-shim.d.ts", + "package/dist/text-codec-shim.js", + "package/dist/worklet-processor.d.ts", + "package/dist/worklet-processor.js", + "package/dist/worklet-protocol.d.ts", + "package/dist/worklet-protocol.js", + "package/dist/worklet.d.ts", + "package/dist/worklet.js", "package/package.json", "package/pkg/tunelet.d.ts", "package/pkg/tunelet.js", @@ -86,7 +94,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 expected files. */ function verifyArchiveEntries(tempDir, relativeArchivePath) { const rawList = execFileSync("tar", ["-tzf", relativeArchivePath], { cwd: tempDir, @@ -155,16 +163,27 @@ function verifyRuntimeImport(consumerDir, packageName) { "", "const packageName = process.argv[2];", "const rootModule = await import(packageName);", + "const workletModule = await import(`${packageName}/worklet`);", + "const workletProcessorModule = await import(`${packageName}/worklet-processor`);", "const wasmModule = await import(`${packageName}/wasm`);", "", 'assert.equal(typeof rootModule.loadTunelet, "function");', + 'assert.equal(typeof rootModule.loadTuneletWasm, "function");', "assert.equal(rootModule.default, rootModule.loadTunelet);", 'assert.equal(typeof rootModule.initSync, "function");', 'assert.equal(typeof rootModule.Tunelet, "function");', + 'assert.equal(typeof rootModule.TuneletFloat32, "function");', 'assert.equal(typeof rootModule.defaultConfig, "function");', + 'assert.equal(typeof workletModule.createTuneletWorkletNode, "function");', + 'assert.equal(typeof workletModule.TuneletWorkletNode, "function");', + 'assert.equal(typeof workletProcessorModule.TuneletWorkletProcessor, "function");', 'assert.equal(typeof wasmModule.default, "function");', 'assert.equal(typeof wasmModule.initSync, "function");', "", + "const wasmBytes = await rootModule.loadTuneletWasm();", + "assert.ok(wasmBytes instanceof ArrayBuffer);", + "assert.ok(wasmBytes.byteLength > 0);", + "", "const wasmExports = await rootModule.loadTunelet();", "assert.ok(wasmExports);", "", @@ -179,6 +198,16 @@ function verifyRuntimeImport(consumerDir, packageName) { " processor.free();", "}", "", + "const floatProcessor = new rootModule.TuneletFloat32(48000, 128, config);", + "try {", + " const input = new Float32Array(128);", + " const left = new Float32Array(128);", + " const right = new Float32Array(128);", + " floatProcessor.process(input, left, right);", + "} finally {", + " floatProcessor.free();", + "}", + "", ].join("\n"), ); @@ -188,10 +217,14 @@ function verifyRuntimeImport(consumerDir, packageName) { }); } -/** Check TypeScript resolution for the root entry and the `./wasm` entry. */ +/** Check TypeScript resolution for all package entry points. */ function verifyTypeDeclarations(consumerDir, packageName) { const checkTsPath = path.join(consumerDir, "check.ts"); const pkgLiteral = JSON.stringify(packageName); + const workletLiteral = JSON.stringify(`${packageName}/worklet`); + const workletProcessorLiteral = JSON.stringify( + `${packageName}/worklet-processor`, + ); const wasmLiteral = JSON.stringify(`${packageName}/wasm`); fs.writeFileSync( checkTsPath, @@ -200,9 +233,18 @@ function verifyTypeDeclarations(consumerDir, packageName) { " defaultConfig,", " initSync as rootInitSync,", " loadTunelet as namedLoadTunelet,", + " loadTuneletWasm,", " Tunelet,", + " TuneletFloat32,", " type ProcessorConfig,", `} from ${pkgLiteral};`, + "import {", + " createTuneletWorkletNode,", + " TuneletWorkletNode,", + `} from ${workletLiteral};`, + "import {", + " TuneletWorkletProcessor,", + `} from ${workletProcessorLiteral};`, "import init, {", " initSync as wasmInitSync,", " type InitInput,", @@ -210,6 +252,7 @@ function verifyTypeDeclarations(consumerDir, packageName) { `} from ${wasmLiteral};`, "", "export async function verifyTypes(source?: InitInput): Promise {", + " const wasmBytes = await loadTuneletWasm(source);", " const exportsFromRoot: InitOutput = await loadTunelet(source);", " const exportsFromNamed: InitOutput = await namedLoadTunelet(source);", " const exportsFromWasm: InitOutput = await init(source);", @@ -220,6 +263,16 @@ function verifyTypeDeclarations(consumerDir, packageName) { " const right = new Int16Array(128);", " processor.process(input, left, right);", " processor.free();", + " const floatProcessor = new TuneletFloat32(48000, 128, config);", + " const floatInput = new Float32Array(128);", + " const floatLeft = new Float32Array(128);", + " const floatRight = new Float32Array(128);", + " floatProcessor.process(floatInput, floatLeft, floatRight);", + " floatProcessor.free();", + " void wasmBytes;", + " void createTuneletWorkletNode;", + " void TuneletWorkletNode;", + " void TuneletWorkletProcessor;", " void rootInitSync;", " void wasmInitSync;", " void exportsFromRoot;", diff --git a/src/index.ts b/src/index.ts index 8526d77..a89da4c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -2,26 +2,105 @@ * The shared ESM entry point for browsers and Node.js. * * Call `loadTunelet()` before you construct processors or read the default - * configuration. Both environments use the same generated bindings and the + * configuration. For an `AudioWorklet`, call `loadTuneletWasm()` on the main + * thread and pass the result to `initSync({ module })` or use + * `tunelet/worklet`. 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. */ -import init from "../pkg/tunelet.js"; -import type { InitInput, InitOutput } from "../pkg/tunelet.js"; +import "./text-codec-shim.js"; +import init, { Tunelet } from "../pkg/tunelet.js"; +import type { + BlockEvents, + Feedback, + InitInput, + InitOutput, + ProcessorConfig, + Telemetry, +} from "../pkg/tunelet.js"; export * from "../pkg/tunelet.js"; +/** Scale factor from signed 16-bit PCM to normalized Float32 audio. */ +const INV_PCM_SCALE = 1.0 / 32768.0; + +/** Shared empty buffers so zero-frame calls allocate no typed arrays. */ +const EMPTY_INPUT = new Int16Array(0); +const EMPTY_LEFT = new Int16Array(0); +const EMPTY_RIGHT = new Int16Array(0); + +/** Error text for fetch-based Wasm calls inside `AudioWorkletGlobalScope`. */ +const WORKLET_FETCH_ERROR = + "loadTunelet() cannot fetch Wasm in AudioWorkletGlobalScope. Load the binary on the main thread with loadTuneletWasm(), then call initSync({ module }) or use tunelet/worklet."; + /** The shared initialization promise, which a failure clears. */ let initialization: Promise | undefined; +/** The shared default Wasm binary promise, which a failure clears. */ +let defaultWasmBinary: Promise | undefined; + +/** Returns `true` if the current global object is an `AudioWorkletGlobalScope`. */ +function isAudioWorkletScope(): boolean { + const scope = globalThis as Record; + const workletCtor = scope.AudioWorkletGlobalScope; + if ( + typeof workletCtor === "function" && + globalThis instanceof (workletCtor as Function) + ) { + return true; + } + return ( + typeof scope.registerProcessor === "function" && + typeof scope.AudioWorkletProcessor === "function" + ); +} + +/** Copies an `ArrayBufferView` into an independent `ArrayBuffer`. */ +function copyViewToArrayBuffer(view: ArrayBufferView): ArrayBuffer { + const bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength); + const copy = new Uint8Array(bytes.byteLength); + copy.set(bytes); + return copy.buffer; +} + +/** Reads a Node.js `file:` URL into a byte view. */ +async function readFileUrlBuffer(url: URL): Promise { + // Keep the Node.js built-in module out of browser bundles. TypeScript + // removes the type-only import. The runtime import runs only for `file:` + // URLs. + const moduleName = "node:fs/promises"; + const fs: typeof import("node:fs/promises") = await import( + /* webpackIgnore: true */ /* @vite-ignore */ moduleName + ); + return fs.readFile(url); +} + +/** Reads a Node.js `file:` URL into an `ArrayBuffer`. */ +async function readFileUrlBytes(url: URL): Promise { + return copyViewToArrayBuffer(await readFileUrlBuffer(url)); +} + +/** Returns `true` if `input` requires `fetch` in non-file environments. */ +function isFetchSource(input: unknown): boolean { + if (typeof input === "string") { + return true; + } + if (input instanceof URL) { + return input.protocol !== "file:"; + } + return typeof Request === "function" && input instanceof Request; +} + /** * Initializes the Wasm module one time for this imported package instance. * * If you give no argument, the function finds the packaged binary relative to * this module. Node.js reads a `file:` URL, and browsers fetch the served - * asset. An import of the package does not load Wasm. In browsers, serve the - * assets over HTTP(S), or give the bytes or a compiled module as the source. + * asset. In `AudioWorkletGlobalScope`, a default call rejects with an error + * because `fetch` is not available. An import of the package does not load + * Wasm. In browsers, serve the assets over HTTP(S), or give the bytes or a + * compiled module as the source. * * For a custom deployment, you can give one of these sources: * @@ -44,12 +123,18 @@ let initialization: Promise | undefined; * * @param source The optional Wasm source. The default is the binary in this * package. - * @returns The initialized Wasm exports. Use the re-exported `Tunelet` class - * for processors. + * @returns The initialized Wasm exports. Use `Tunelet` or `TuneletFloat32` for + * processors. */ export function loadTunelet( source?: InitInput | Promise, ): Promise { + if ( + isAudioWorkletScope() && + (source === undefined || isFetchSource(source)) + ) { + return Promise.reject(new Error(WORKLET_FETCH_ERROR)); + } initialization ??= initialize(source).catch((error: unknown) => { initialization = undefined; throw error; @@ -67,18 +152,400 @@ async function initialize( : await source; if (input instanceof URL && input.protocol === "file:") { - // Keep the Node.js built-in module out of browser bundles. TypeScript - // removes the type-only import. The runtime import runs only for `file:` - // URLs. - const moduleName = "node:fs/promises"; - const fs: typeof import("node:fs/promises") = await import( - /* webpackIgnore: true */ /* @vite-ignore */ moduleName - ); - return init({ module_or_path: await fs.readFile(input) }); + return init({ module_or_path: await readFileUrlBuffer(input) }); + } + + if ( + isAudioWorkletScope() && + (typeof input === "string" || + input instanceof URL || + (typeof Request === "function" && input instanceof Request)) + ) { + throw new Error(WORKLET_FETCH_ERROR); } return init({ module_or_path: input }); } +/** Checks if a value is a Fetch API `Response` instance. */ +function isFetchResponse(value: unknown): value is Response { + return typeof Response === "function" && value instanceof Response; +} + +/** + * Resolves the Wasm binary into an `ArrayBuffer` or a `WebAssembly.Module`. + * + * Run this function on the main thread or in Node.js to load the Wasm asset + * without `fetch` inside an `AudioWorkletGlobalScope`. Then pass the result to + * `initSync({ module })` or to `TuneletWorkletNode`. + * + * If you omit `source`, the function loads the packaged `tunelet_bg.wasm` + * asset one time and caches that `ArrayBuffer`. If that load fails, the + * function clears the cached promise so a later call can try again. + * + * @param source The optional Wasm source. The default is the binary in this + * package. + * @returns An `ArrayBuffer` of Wasm bytes or a compiled `WebAssembly.Module`. + */ +export function loadTuneletWasm(): Promise; +export function loadTuneletWasm( + source: WebAssembly.Module | Promise, +): Promise; +export function loadTuneletWasm( + source?: InitInput | Promise, +): Promise; +export function loadTuneletWasm( + source?: InitInput | Promise, +): Promise { + if (source === undefined) { + if (isAudioWorkletScope()) { + return Promise.reject(new Error(WORKLET_FETCH_ERROR)); + } + defaultWasmBinary ??= resolveWasmSource(undefined).catch( + (error: unknown) => { + defaultWasmBinary = undefined; + throw error; + }, + ) as Promise; + return defaultWasmBinary; + } + return resolveWasmSource(source); +} + +/** Resolves one `InitInput` value into an `ArrayBuffer` or `WebAssembly.Module`. */ +async function resolveWasmSource( + source: InitInput | Promise | undefined, +): Promise { + const input = + source === undefined + ? new URL("../pkg/tunelet_bg.wasm", import.meta.url) + : await source; + + if (input instanceof WebAssembly.Module) { + return input; + } + if (input instanceof ArrayBuffer) { + return input; + } + if (ArrayBuffer.isView(input)) { + return copyViewToArrayBuffer(input); + } + if (isFetchResponse(input)) { + if (!input.ok) { + throw new Error( + `Failed to fetch Wasm: ${input.status} ${input.statusText}`, + ); + } + return input.arrayBuffer(); + } + if (input instanceof URL && input.protocol === "file:") { + return readFileUrlBytes(input); + } + if (isAudioWorkletScope() || typeof fetch !== "function") { + throw new Error(WORKLET_FETCH_ERROR); + } + + const response = await fetch(input); + if (!response.ok) { + throw new Error( + `Failed to fetch Wasm: ${response.status} ${response.statusText}`, + ); + } + return response.arrayBuffer(); +} + +/** Checks that two channel lengths are equal. */ +function checkBufferLength(expected: number, actual: number): void { + if (expected !== actual) { + throw new Error(`buffer length is ${actual}, expected ${expected}`); + } +} + +/** Checks that two output `Float32Array` views do not share memory ranges. */ +function checkDisjointOutputs(left: Float32Array, right: Float32Array): void { + if ( + left.byteLength > 0 && + left.buffer === right.buffer && + left.byteOffset < right.byteOffset + right.byteLength && + right.byteOffset < left.byteOffset + left.byteLength + ) { + throw new Error("left and right output buffers must not overlap"); + } +} + +/** Converts normalized `Float32Array` samples into signed 16-bit PCM. */ +function convertFloat32ToInt16( + source: Float32Array, + target: Int16Array, + frames: number, +): void { + for (let index = 0; index < frames; index += 1) { + const sample = source[index]; + if (sample !== sample) { + target[index] = 0; + } else { + const clamped = sample < -1.0 ? -1.0 : sample > 1.0 ? 1.0 : sample; + const scaled = Math.round(clamped * 32768.0); + target[index] = scaled > 32767 ? 32767 : scaled; + } + } +} + +/** Scales signed 16-bit PCM samples into `Float32Array` output. */ +function convertInt16ToFloat32( + source: Int16Array, + target: Float32Array, + frames: number, +): void { + for (let index = 0; index < frames; index += 1) { + target[index] = source[index] * INV_PCM_SCALE; + } +} + +/** + * A `Float32Array` adapter around `Tunelet` for Web Audio and Node.js. + * + * Call `loadTunelet()` or `initSync({ module })` before you construct this + * class. The constructor preallocates three `Int16Array` conversion buffers + * (`input`, `left` and `right`) of length `maxBlockFrames`. + * + * Audio methods map `NaN` to zero, clamp inputs to `-1.0..=1.0`, delegate to + * `Tunelet` and multiply outputs by `1.0 / 32768.0`. Separate stereo output + * arrays must not overlap. Input can overlap an output. If a call fails, it + * throws before the caller buffers or the DSP state change. + * + * This adapter allocates no new JavaScript typed arrays during steady-state + * audio calls. The generated wasm-bindgen glue can still make temporary views + * on Wasm memory during copies, and object, event, feedback, telemetry and + * error conversions can allocate memory. Call `free()` when you do not need + * the instance any more. + */ +export class TuneletFloat32 { + readonly #inner: Tunelet; + readonly #maxBlockFrames: number; + readonly #input: Int16Array; + readonly #left: Int16Array; + readonly #right: Int16Array; + #partialFrames = 0; + #partialInput: Int16Array = EMPTY_INPUT; + #partialLeft: Int16Array = EMPTY_LEFT; + #partialRight: Int16Array = EMPTY_RIGHT; + + /** + * Prepares a `Tunelet` processor and preallocates `Int16Array` conversion + * buffers. + * + * `sampleRate` must be 44100 or 48000. `maxBlockFrames` must be an integer + * in `1..=4294967295`. If you omit `config`, the processor uses the default + * configuration. + */ + constructor( + sampleRate: number, + maxBlockFrames: number, + config?: ProcessorConfig | null, + ) { + const inner = new Tunelet(sampleRate, maxBlockFrames, config); + try { + this.#input = new Int16Array(maxBlockFrames); + this.#left = new Int16Array(maxBlockFrames); + this.#right = new Int16Array(maxBlockFrames); + } catch (error) { + inner.free(); + throw error; + } + this.#inner = inner; + this.#maxBlockFrames = maxBlockFrames; + } + + /** The sample rate of the input and the output in hertz. */ + get sampleRate(): number { + return this.#inner.sampleRate; + } + + /** The maximum frame count for each process or drain call. */ + get maxBlockFrames(): number { + return this.#inner.maxBlockFrames; + } + + /** The nominal resynthesis delay in frames. */ + get latencyFrames(): number { + return this.#inner.latencyFrames; + } + + /** Returns a copy of the active configuration. */ + config(): ProcessorConfig { + return this.#inner.config(); + } + + /** Validates and replaces the complete configuration. */ + setConfig(config: ProcessorConfig): void { + this.#inner.setConfig(config); + } + + /** + * Processes mono `Float32Array` input into planar stereo `Float32Array` + * outputs of equal length. + */ + process( + input: Float32Array, + left: Float32Array, + right: Float32Array, + events?: BlockEvents | null, + ): void { + const frames = input.length; + checkBufferLength(frames, left.length); + checkBufferLength(frames, right.length); + this.#checkFrames(frames); + checkDisjointOutputs(left, right); + + const [pcmInput, pcmLeft, pcmRight] = this.#viewsForFrames(frames); + convertFloat32ToInt16(input, pcmInput, frames); + this.#inner.process(pcmInput, pcmLeft, pcmRight, events); + convertInt16ToFloat32(pcmLeft, left, frames); + convertInt16ToFloat32(pcmRight, right, frames); + } + + /** + * Replaces mono `Float32Array` audio in place with the stereo downmix. + */ + processMono(audio: Float32Array, events?: BlockEvents | null): void { + const frames = audio.length; + this.#checkFrames(frames); + + const pcmAudio = this.#monoViewForFrames(frames); + convertFloat32ToInt16(audio, pcmAudio, frames); + this.#inner.processMono(pcmAudio, events); + convertInt16ToFloat32(pcmAudio, audio, frames); + } + + /** Starts a finite tail budget and returns its frame count. */ + beginDrain(): number { + return this.#inner.beginDrain(); + } + + /** Returns the configured tail budget in frames. */ + tailFrames(): number { + return this.#inner.tailFrames(); + } + + /** + * Renders stereo tail frames into `Float32Array` buffers of equal length and + * returns the rendered frame count. + */ + drain(left: Float32Array, right: Float32Array): number { + const frames = left.length; + checkBufferLength(frames, right.length); + this.#checkFrames(frames); + checkDisjointOutputs(left, right); + + const [, pcmLeft, pcmRight] = this.#viewsForFrames(frames); + const rendered = this.#inner.drain(pcmLeft, pcmRight); + convertInt16ToFloat32(pcmLeft, left, frames); + convertInt16ToFloat32(pcmRight, right, frames); + return rendered; + } + + /** + * Renders mono tail frames into a `Float32Array` buffer and returns the + * rendered frame count. + */ + drainMono(audio: Float32Array): number { + const frames = audio.length; + this.#checkFrames(frames); + + const pcmAudio = this.#monoViewForFrames(frames); + const rendered = this.#inner.drainMono(pcmAudio); + convertInt16ToFloat32(pcmAudio, audio, frames); + return rendered; + } + + /** Returns a feedback snapshot and does not clear the peak window. */ + feedback(): Feedback { + return this.#inner.feedback(); + } + + /** Returns a feedback snapshot and clears the stereo peak window. */ + takeFeedback(): Feedback { + return this.#inner.takeFeedback(); + } + + /** Returns a telemetry snapshot and does not clear its peak windows. */ + telemetry(): Telemetry { + return this.#inner.telemetry(); + } + + /** Returns a telemetry snapshot and clears its three peak windows. */ + takeTelemetry(): Telemetry { + return this.#inner.takeTelemetry(); + } + + /** Writes the analysis and synthesis formant envelopes into two buffers. */ + formantEnvelope( + maxFrequencyHz: number, + input: Float32Array, + output: Float32Array, + ): boolean { + return this.#inner.formantEnvelope(maxFrequencyHz, input, output); + } + + /** Resets the audio histories and feedback, and cancels any active drain. */ + reset(): void { + this.#inner.reset(); + } + + /** Releases the owned Wasm processor memory. */ + free(): void { + this.#inner.free(); + } + + /** Releases the owned Wasm processor memory for `Symbol.dispose`. */ + [Symbol.dispose](): void { + this.free(); + } + + /** Rejects blocks that exceed `maxBlockFrames`. */ + #checkFrames(frames: number): void { + if (frames > this.#maxBlockFrames) { + throw new Error( + `block of ${frames} frames is larger than the prepared ${this.#maxBlockFrames}`, + ); + } + } + + /** Returns reusable `Int16Array` views of length `frames`. */ + #viewsForFrames(frames: number): [Int16Array, Int16Array, Int16Array] { + if (frames === this.#maxBlockFrames) { + return [this.#input, this.#left, this.#right]; + } + if (frames === 0) { + return [EMPTY_INPUT, EMPTY_LEFT, EMPTY_RIGHT]; + } + if (this.#partialFrames !== frames) { + this.#partialInput = this.#input.subarray(0, frames); + this.#partialLeft = this.#left.subarray(0, frames); + this.#partialRight = this.#right.subarray(0, frames); + this.#partialFrames = frames; + } + return [this.#partialInput, this.#partialLeft, this.#partialRight]; + } + + /** Returns a reusable mono `Int16Array` view of length `frames`. */ + #monoViewForFrames(frames: number): Int16Array { + if (frames === this.#maxBlockFrames) { + return this.#input; + } + if (frames === 0) { + return EMPTY_INPUT; + } + if (this.#partialFrames !== frames) { + this.#partialInput = this.#input.subarray(0, frames); + this.#partialLeft = this.#left.subarray(0, frames); + this.#partialRight = this.#right.subarray(0, frames); + this.#partialFrames = frames; + } + return this.#partialInput; + } +} + /** The default export is the same function as `loadTunelet`. */ export default loadTunelet; diff --git a/src/text-codec-shim.ts b/src/text-codec-shim.ts new file mode 100644 index 0000000..debfe87 --- /dev/null +++ b/src/text-codec-shim.ts @@ -0,0 +1,256 @@ +/** + * Minimal UTF-8 `TextDecoder` and `TextEncoder` shims for `AudioWorkletGlobalScope`. + * + * Some browser `AudioWorkletGlobalScope` runtimes omit `TextDecoder` and + * `TextEncoder`. The generated wasm-bindgen module constructs both classes at + * module load time. If the global scope already defines a class, this module + * keeps that native class. + */ + +interface MinimalTextDecoderOptions { + fatal?: boolean; + ignoreBOM?: boolean; +} + +interface MinimalTextDecodeOptions { + stream?: boolean; +} + +interface MinimalEncodeIntoResult { + read: number; + written: number; +} + +function toBytes(input?: AllowSharedBufferSource): Uint8Array { + if (input === undefined) { + return new Uint8Array(0); + } + if (input instanceof Uint8Array) { + return input; + } + if (ArrayBuffer.isView(input)) { + return new Uint8Array(input.buffer, input.byteOffset, input.byteLength); + } + return new Uint8Array(input); +} + +class FallbackTextDecoder { + readonly encoding = "utf-8"; + readonly fatal: boolean; + readonly ignoreBOM: boolean; + + constructor(label = "utf-8", options?: MinimalTextDecoderOptions) { + const normalized = String(label).trim().toLowerCase(); + if (normalized !== "utf-8" && normalized !== "utf8") { + throw new RangeError(`TextDecoder does not support label: ${label}`); + } + this.fatal = Boolean(options?.fatal); + this.ignoreBOM = Boolean(options?.ignoreBOM); + } + + decode( + input?: AllowSharedBufferSource, + options?: MinimalTextDecodeOptions, + ): string { + if (options?.stream) { + throw new TypeError("TextDecoder stream mode is not supported"); + } + const bytes = toBytes(input); + const length = bytes.length; + let index = 0; + if ( + !this.ignoreBOM && + length >= 3 && + bytes[0] === 0xef && + bytes[1] === 0xbb && + bytes[2] === 0xbf + ) { + index = 3; + } + + let result = ""; + while (index < length) { + const b0 = bytes[index]; + if (b0 < 0x80) { + result += String.fromCharCode(b0); + index += 1; + continue; + } + + if (b0 >= 0xc2 && b0 <= 0xdf) { + if (index + 1 < length) { + const b1 = bytes[index + 1]; + if ((b1 & 0xc0) === 0x80) { + result += String.fromCharCode(((b0 & 0x1f) << 6) | (b1 & 0x3f)); + index += 2; + continue; + } + } + } else if (b0 >= 0xe0 && b0 <= 0xef) { + if (index + 2 < length) { + const b1 = bytes[index + 1]; + const b2 = bytes[index + 2]; + const validSecond = + (b1 & 0xc0) === 0x80 && + (b0 !== 0xe0 || b1 >= 0xa0) && + (b0 !== 0xed || b1 <= 0x9f); + if (validSecond && (b2 & 0xc0) === 0x80) { + result += String.fromCharCode( + ((b0 & 0x0f) << 12) | ((b1 & 0x3f) << 6) | (b2 & 0x3f), + ); + index += 3; + continue; + } + } + } else if (b0 >= 0xf0 && b0 <= 0xf4) { + if (index + 3 < length) { + const b1 = bytes[index + 1]; + const b2 = bytes[index + 2]; + const b3 = bytes[index + 3]; + const validSecond = + (b1 & 0xc0) === 0x80 && + (b0 !== 0xf0 || b1 >= 0x90) && + (b0 !== 0xf4 || b1 <= 0x8f); + if ( + validSecond && + (b2 & 0xc0) === 0x80 && + (b3 & 0xc0) === 0x80 + ) { + const codePoint = + ((b0 & 0x07) << 18) | + ((b1 & 0x3f) << 12) | + ((b2 & 0x3f) << 6) | + (b3 & 0x3f); + const offset = codePoint - 0x10000; + result += String.fromCharCode( + 0xd800 + (offset >> 10), + 0xdc00 + (offset & 0x3ff), + ); + index += 4; + continue; + } + } + } + + if (this.fatal) { + throw new TypeError("Invalid UTF-8 byte sequence"); + } + result += "\ufffd"; + index += 1; + } + + return result; + } +} + +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 new Uint8Array(bytes); + } + + encodeInto( + source: string, + destination: Uint8Array, + ): MinimalEncodeIntoResult { + let read = 0; + let written = 0; + const limit = destination.length; + while (read < source.length) { + const code = source.charCodeAt(read); + if (code < 0x80) { + if (written + 1 > limit) { + break; + } + destination[written] = code; + written += 1; + read += 1; + } else if (code < 0x800) { + if (written + 2 > limit) { + 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 < source.length ? source.charCodeAt(read + 1) : 0; + if (next >= 0xdc00 && next <= 0xdfff) { + if (written + 4 > limit) { + 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 > limit) { + break; + } + destination[written] = 0xef; + destination[written + 1] = 0xbf; + destination[written + 2] = 0xbd; + written += 3; + read += 1; + } + } else { + if (written + 3 > limit) { + break; + } + const value = code >= 0xdc00 && code <= 0xdfff ? 0xfffd : code; + destination[written] = 0xe0 | (value >> 12); + destination[written + 1] = 0x80 | ((value >> 6) & 0x3f); + destination[written + 2] = 0x80 | (value & 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/worklet-processor.ts b/src/worklet-processor.ts new file mode 100644 index 0000000..eba79e8 --- /dev/null +++ b/src/worklet-processor.ts @@ -0,0 +1,916 @@ +/** + * The `AudioWorkletProcessor` entry point for `tunelet/worklet-processor`. + * + * This module initializes the Wasm binary synchronously with `initSync` from + * `processorOptions.wasm`. It does not call `fetch`. It preallocates + * `Float32Array` scratch arrays at construction and chunks Web Audio render + * blocks into `TuneletFloat32`. + */ +import "./text-codec-shim.js"; +import { initSync, TuneletFloat32 } from "./index.js"; +import type { + BlockEvents, + ControlEvent, + MidiEvent, + TimedEvent, +} from "./index.js"; +import { + DEFAULT_WORKLET_BLOCK_FRAMES, + TUNELET_PROCESSOR_NAME, +} from "./worklet-protocol.js"; +import type { + FormantEnvelopeResult, + TuneletProcessorOptions, + TuneletWorkletNotification, + TuneletWorkletOutboundMessage, + TuneletWorkletRequest, + TuneletWorkletResponse, +} from "./worklet-protocol.js"; + +export { + DEFAULT_WORKLET_BLOCK_FRAMES, + TUNELET_PROCESSOR_NAME, +} from "./worklet-protocol.js"; +export type { + FormantEnvelopeResult, + TuneletDrainOptions, + TuneletProcessorOptions, + TuneletWorkletCommand, + TuneletWorkletNotification, + TuneletWorkletOutboundMessage, + TuneletWorkletRequest, + TuneletWorkletResponse, +} from "./worklet-protocol.js"; + +/** Minimal `AudioWorkletProcessor` instance contract in `AudioWorkletGlobalScope`. */ +export interface AudioWorkletProcessorInstance { + readonly port: MessagePort; + process( + inputs: Float32Array[][], + outputs: Float32Array[][], + parameters: Record, + ): boolean; +} + +/** Constructor type for `AudioWorkletProcessor` in `AudioWorkletGlobalScope`. */ +export interface AudioWorkletProcessorConstructor { + new (options?: AudioWorkletNodeOptions): AudioWorkletProcessorInstance; + prototype: AudioWorkletProcessorInstance; +} + +type RegisterProcessorFn = ( + name: string, + processorCtor: AudioWorkletProcessorConstructor, +) => void; + +const EMPTY_FLOAT32 = new Float32Array(0); + +/** Resolves `AudioWorkletProcessor` in browsers and in test environments. */ +const WorkletProcessorBase: AudioWorkletProcessorConstructor = + typeof (globalThis as Record).AudioWorkletProcessor === + "function" + ? ((globalThis as Record) + .AudioWorkletProcessor as AudioWorkletProcessorConstructor) + : (class { + declare readonly port: MessagePort; + constructor(options?: AudioWorkletNodeOptions) { + const runtimeCtor = (globalThis as Record) + .AudioWorkletProcessor; + if (typeof runtimeCtor === "function") { + return Reflect.construct(runtimeCtor, [options], new.target); + } + throw new Error( + "AudioWorkletProcessor is not available in this environment", + ); + } + process(): boolean { + return false; + } + } as unknown as AudioWorkletProcessorConstructor); + +/** Formats a thrown value as an error message string. */ +function formatError(error: unknown): string { + if (error instanceof Error) { + return error.message; + } + return String(error); +} + +/** Checks that a number is an integer in `min..=max`. */ +function isIntegerInRange(value: unknown, min: number, max: number): boolean { + return ( + typeof value === "number" && + Number.isInteger(value) && + value >= min && + value <= max + ); +} + +/** Validates a `MidiEvent` before the processor queues it for the next block. */ +function validateMidiEvent(event: MidiEvent): void { + if (typeof event !== "object" || event === null) { + throw new Error("MIDI message is not valid"); + } + if (event.type === "noteOn") { + if ( + !isIntegerInRange(event.channel, 0, 15) || + !isIntegerInRange(event.note, 0, 127) || + !isIntegerInRange(event.velocity, 0, 127) + ) { + throw new Error("MIDI message is not valid"); + } + return; + } + if (event.type === "noteOff") { + if ( + !isIntegerInRange(event.channel, 0, 15) || + !isIntegerInRange(event.note, 0, 127) + ) { + throw new Error("MIDI message is not valid"); + } + return; + } + if (event.type === "allNotesOff") { + return; + } + throw new Error("MIDI message is not valid"); +} + +/** Validates one `ControlEvent` payload before it enters the event queue. */ +function validateControlEventShape( + event: ControlEvent, + processor: TuneletFloat32, +): void { + if (typeof event !== "object" || event === null || !("type" in event)) { + throw new Error("control event is not valid"); + } + switch (event.type) { + case "midi": + case "correctionMidi": + validateMidiEvent(event.value); + return; + case "reset": + return; + case "outputGain": + if (typeof event.value !== "number" || !Number.isFinite(event.value)) { + throw new Error("invalid config: output_gain must be finite"); + } + if (event.value < 0 || event.value > 64) { + throw new Error("invalid config: output_gain must be in 0..=64"); + } + return; + case "configure": + case "punch": + case "warm": + case "resynthesis": + case "alien": + case "reverb": { + if (typeof event.value !== "object" || event.value === null) { + throw new Error("control event configuration must be an object"); + } + // For timed offsets above zero, keep the processor state untouched here. + void processor; + return; + } + default: + throw new Error("control event is not valid"); + } +} + +/** + * Web Audio `AudioWorkletProcessor` that wraps `TuneletFloat32`. + * + * The constructor calls `initSync({ module })` with the Wasm binary from + * `options.processorOptions.wasm`. It preallocates `Float32Array` scratch + * buffers for `maxBlockFrames` and processes Web Audio blocks in chunks. + * + * Steady-state audio calls allocate no new JavaScript typed arrays. The + * generated wasm-bindgen glue can still create temporary views on Wasm memory, + * and `MessagePort` control, event, feedback, telemetry and envelope messages + * allocate JavaScript objects. + */ +export class TuneletWorkletProcessor extends WorkletProcessorBase { + #processor!: TuneletFloat32; + #maxBlockFrames = DEFAULT_WORKLET_BLOCK_FRAMES; + #scratchInput: Float32Array = EMPTY_FLOAT32; + #scratchLeft: Float32Array = EMPTY_FLOAT32; + #scratchRight: Float32Array = EMPTY_FLOAT32; + #partialFrames = 0; + #partialInput: Float32Array = EMPTY_FLOAT32; + #partialLeft: Float32Array = EMPTY_FLOAT32; + #partialRight: Float32Array = EMPTY_FLOAT32; + #pendingEvents: TimedEvent[] = []; + #draining = false; + #drainRemaining = 0; + #stopAfterDrain = false; + #disposed = false; + + constructor(options?: AudioWorkletNodeOptions) { + super(options); + try { + const processorOptions = (options?.processorOptions ?? + {}) as Partial; + if (processorOptions.wasm === undefined || processorOptions.wasm === null) { + throw new Error( + "processorOptions.wasm must provide a WebAssembly.Module or byte buffer for initSync", + ); + } + + const maxBlockFrames = + processorOptions.maxBlockFrames ?? DEFAULT_WORKLET_BLOCK_FRAMES; + const scopeSampleRate = (globalThis as Record) + .sampleRate; + if (typeof scopeSampleRate !== "number") { + throw new Error( + "AudioWorkletGlobalScope sampleRate is not available", + ); + } + + initSync({ module: processorOptions.wasm }); + const processor = new TuneletFloat32( + scopeSampleRate, + maxBlockFrames, + processorOptions.config, + ); + + try { + this.#scratchInput = new Float32Array(maxBlockFrames); + this.#scratchLeft = new Float32Array(maxBlockFrames); + this.#scratchRight = new Float32Array(maxBlockFrames); + } catch (error) { + processor.free(); + throw error; + } + + this.#processor = processor; + this.#maxBlockFrames = maxBlockFrames; + this.port.onmessage = (event: MessageEvent) => { + this.#handleMessage(event.data); + }; + + this.#postNotification({ + __tunelet: "ready", + sampleRate: processor.sampleRate, + maxBlockFrames: processor.maxBlockFrames, + latencyFrames: processor.latencyFrames, + }); + } catch (error) { + this.#disposed = true; + this.#postNotification({ + __tunelet: "initError", + error: formatError(error), + }); + throw error; + } + } + + /** Processes one Web Audio render quantum in chunks with scratch arrays. */ + override process( + inputs: Float32Array[][], + outputs: Float32Array[][], + _parameters: Record, + ): boolean { + if (this.#disposed) { + return false; + } + + const outputChannels = outputs[0]; + if (!outputChannels || outputChannels.length === 0) { + return true; + } + const firstOutput = outputChannels[0]; + if (!firstOutput || firstOutput.length === 0) { + return true; + } + + const blockFrames = firstOutput.length; + const inputChannels = inputs[0]; + const monoOutput = outputChannels.length === 1; + const rightOutput = monoOutput ? undefined : outputChannels[1]; + + // Zero any extra channels beyond stereo. + for (let ch = 2; ch < outputChannels.length; ch += 1) { + outputChannels[ch].fill(0); + } + + let drainFinishedInBlock = false; + let offset = 0; + + while (offset < blockFrames) { + const chunkFrames = Math.min( + this.#maxBlockFrames, + blockFrames - offset, + ); + + if (drainFinishedInBlock) { + firstOutput.fill(0, offset, offset + chunkFrames); + if (rightOutput) { + rightOutput.fill(0, offset, offset + chunkFrames); + } + offset += chunkFrames; + continue; + } + + const [chunkInput, chunkLeft, chunkRight] = + this.#scratchViews(chunkFrames); + + if (this.#draining) { + if (monoOutput) { + const rendered = this.#processor.drainMono(chunkLeft); + this.#copyToOutput(chunkLeft, firstOutput, offset, chunkFrames); + this.#drainRemaining -= rendered; + if (rendered < chunkFrames || this.#drainRemaining <= 0) { + this.#finishDrain(); + drainFinishedInBlock = true; + } + } else { + const rendered = this.#processor.drain(chunkLeft, chunkRight); + this.#copyToOutput(chunkLeft, firstOutput, offset, chunkFrames); + if (rightOutput) { + this.#copyToOutput(chunkRight, rightOutput, offset, chunkFrames); + } + this.#drainRemaining -= rendered; + if (rendered < chunkFrames || this.#drainRemaining <= 0) { + this.#finishDrain(); + drainFinishedInBlock = true; + } + } + offset += chunkFrames; + continue; + } + + this.#fillInputChunk(inputChannels, chunkInput, offset, chunkFrames); + const chunkEvents = this.#takeEventsForChunk(offset, chunkFrames); + + try { + if (monoOutput) { + this.#processor.processMono(chunkInput, chunkEvents); + this.#copyToOutput(chunkInput, firstOutput, offset, chunkFrames); + } else { + this.#processor.process( + chunkInput, + chunkLeft, + chunkRight, + chunkEvents, + ); + this.#copyToOutput(chunkLeft, firstOutput, offset, chunkFrames); + if (rightOutput) { + this.#copyToOutput(chunkRight, rightOutput, offset, chunkFrames); + } + } + } catch (error) { + this.#postNotification({ + __tunelet: "processError", + error: formatError(error), + }); + if (chunkEvents !== undefined) { + if (monoOutput) { + this.#fillInputChunk(inputChannels, chunkInput, offset, chunkFrames); + this.#processor.processMono(chunkInput); + this.#copyToOutput(chunkInput, firstOutput, offset, chunkFrames); + } else { + this.#processor.process(chunkInput, chunkLeft, chunkRight); + this.#copyToOutput(chunkLeft, firstOutput, offset, chunkFrames); + if (rightOutput) { + this.#copyToOutput(chunkRight, rightOutput, offset, chunkFrames); + } + } + } else { + firstOutput.fill(0, offset, offset + chunkFrames); + if (rightOutput) { + rightOutput.fill(0, offset, offset + chunkFrames); + } + } + } + + offset += chunkFrames; + } + + if (this.#pendingEvents.length > 0) { + for (let index = 0; index < this.#pendingEvents.length; index += 1) { + const current = this.#pendingEvents[index]; + current.offset = Math.max(0, current.offset - blockFrames); + } + } + + if (drainFinishedInBlock && this.#stopAfterDrain) { + this.#stopAfterDrain = false; + return false; + } + return !this.#disposed; + } + + /** Copies or downmixes `inputs[0]` into the mono `chunkInput` buffer. */ + #fillInputChunk( + inputChannels: Float32Array[] | undefined, + chunkInput: Float32Array, + offset: number, + chunkFrames: number, + ): void { + if (!inputChannels || inputChannels.length === 0) { + chunkInput.fill(0); + return; + } + const channelCount = inputChannels.length; + if (channelCount === 1) { + const channel = inputChannels[0]; + if (!channel || channel.length === 0) { + chunkInput.fill(0); + return; + } + if (channel.length === 1) { + chunkInput.fill(channel[0]); + return; + } + for (let i = 0; i < chunkFrames; i += 1) { + const srcIndex = offset + i; + chunkInput[i] = srcIndex < channel.length ? channel[srcIndex] : 0; + } + return; + } + + const invChannels = 1.0 / channelCount; + for (let i = 0; i < chunkFrames; i += 1) { + const srcIndex = offset + i; + let sum = 0; + for (let ch = 0; ch < channelCount; ch += 1) { + const channel = inputChannels[ch]; + if (channel && channel.length > 0) { + sum += + channel.length === 1 + ? channel[0] + : srcIndex < channel.length + ? channel[srcIndex] + : 0; + } + } + chunkInput[i] = sum * invChannels; + } + } + + /** Copies `chunkFrames` samples from a scratch buffer into an output slice. */ + #copyToOutput( + source: Float32Array, + destination: Float32Array, + destinationOffset: number, + chunkFrames: number, + ): void { + for (let i = 0; i < chunkFrames; i += 1) { + destination[destinationOffset + i] = source[i]; + } + } + + /** Returns reusable `Float32Array` scratch views of length `chunkFrames`. */ + #scratchViews( + chunkFrames: number, + ): [Float32Array, Float32Array, Float32Array] { + if (chunkFrames === this.#maxBlockFrames) { + return [this.#scratchInput, this.#scratchLeft, this.#scratchRight]; + } + if (this.#partialFrames !== chunkFrames) { + this.#partialInput = this.#scratchInput.subarray(0, chunkFrames); + this.#partialLeft = this.#scratchLeft.subarray(0, chunkFrames); + this.#partialRight = this.#scratchRight.subarray(0, chunkFrames); + this.#partialFrames = chunkFrames; + } + return [this.#partialInput, this.#partialLeft, this.#partialRight]; + } + + /** Extracts queued events that fall inside `[chunkStart, chunkStart + chunkFrames)`. */ + #takeEventsForChunk( + chunkStart: number, + chunkFrames: number, + ): BlockEvents | undefined { + if (this.#pendingEvents.length === 0) { + return undefined; + } + const chunkEnd = chunkStart + chunkFrames; + let count = 0; + while ( + count < this.#pendingEvents.length && + this.#pendingEvents[count].offset < chunkEnd + ) { + count += 1; + } + if (count === 0) { + return undefined; + } + const selected = this.#pendingEvents.splice(0, count); + for (let index = 0; index < selected.length; index += 1) { + const localOffset = selected[index].offset - chunkStart; + selected[index] = { + offset: localOffset < 0 ? 0 : localOffset, + event: selected[index].event, + }; + } + return selected; + } + + /** Inserts timed events and keeps offsets in frame order. */ + #enqueueTimedEvents(events: BlockEvents): void { + if (!Array.isArray(events)) { + throw new Error("events must be an array"); + } + let previous = 0; + for (let index = 0; index < events.length; index += 1) { + const entry = events[index]; + if ( + typeof entry !== "object" || + entry === null || + typeof entry.offset !== "number" || + !Number.isInteger(entry.offset) || + entry.offset < 0 + ) { + throw new Error(`event ${index}: offset is outside the block`); + } + if (entry.offset < previous) { + throw new Error( + `event ${index}: offset is below the previous event's offset`, + ); + } + validateControlEventShape(entry.event, this.#processor); + previous = entry.offset; + } + + this.#draining = false; + this.#drainRemaining = 0; + this.#stopAfterDrain = false; + + for (let index = 0; index < events.length; index += 1) { + const item: TimedEvent = { + offset: events[index].offset, + event: events[index].event, + }; + if ( + this.#pendingEvents.length === 0 || + this.#pendingEvents[this.#pendingEvents.length - 1].offset <= + item.offset + ) { + this.#pendingEvents.push(item); + } else { + const insertIndex = this.#pendingEvents.findIndex( + (existing) => existing.offset > item.offset, + ); + this.#pendingEvents.splice(insertIndex, 0, item); + } + } + } + + /** Completes an active drain and notifies the main thread. */ + #finishDrain(): void { + this.#draining = false; + this.#drainRemaining = 0; + this.#postNotification({ __tunelet: "drainComplete" }); + } + + /** Handles one command message from `TuneletWorkletNode` over `MessagePort`. */ + #handleMessage(request: TuneletWorkletRequest): void { + if ( + typeof request !== "object" || + request === null || + typeof request.type !== "string" + ) { + return; + } + + const requestId = request.id; + const requestType = request.type; + + if (this.#disposed && requestType !== "free") { + this.#postResponse({ + __tunelet: "response", + id: requestId, + requestType, + ok: false, + error: "TuneletWorkletProcessor is already disposed", + }); + return; + } + + try { + switch (request.type) { + case "config": { + const value = this.#processor.config(); + this.#postResponse({ + __tunelet: "response", + id: requestId, + requestType, + ok: true, + value, + }); + return; + } + case "setConfig": { + this.#processor.setConfig(request.config); + this.#draining = false; + this.#stopAfterDrain = false; + this.#postResponse({ + __tunelet: "response", + id: requestId, + requestType, + ok: true, + }); + return; + } + case "midi": { + validateMidiEvent(request.event); + this.#draining = false; + this.#stopAfterDrain = false; + this.#enqueueZeroOffsetEvent({ type: "midi", value: request.event }); + this.#postResponse({ + __tunelet: "response", + id: requestId, + requestType, + ok: true, + }); + return; + } + case "correctionMidi": { + validateMidiEvent(request.event); + this.#draining = false; + this.#stopAfterDrain = false; + this.#enqueueZeroOffsetEvent({ + type: "correctionMidi", + value: request.event, + }); + this.#postResponse({ + __tunelet: "response", + id: requestId, + requestType, + ok: true, + }); + return; + } + case "control": { + this.#applyOrQueueControl(request.event); + this.#postResponse({ + __tunelet: "response", + id: requestId, + requestType, + ok: true, + }); + return; + } + case "events": { + this.#enqueueTimedEvents(request.events); + this.#postResponse({ + __tunelet: "response", + id: requestId, + requestType, + ok: true, + }); + return; + } + case "reset": { + this.#pendingEvents.length = 0; + this.#draining = false; + this.#stopAfterDrain = false; + this.#processor.reset(); + this.#postResponse({ + __tunelet: "response", + id: requestId, + requestType, + ok: true, + }); + return; + } + case "beginDrain": { + this.#pendingEvents.length = 0; + const budget = this.#processor.beginDrain(); + this.#drainRemaining = budget; + this.#draining = budget > 0; + this.#stopAfterDrain = Boolean(request.stopAfterDrain); + this.#postResponse({ + __tunelet: "response", + id: requestId, + requestType, + ok: true, + value: budget, + }); + if (budget === 0) { + this.#postNotification({ __tunelet: "drainComplete" }); + } + return; + } + case "tailFrames": { + const value = this.#processor.tailFrames(); + this.#postResponse({ + __tunelet: "response", + id: requestId, + requestType, + ok: true, + value, + }); + return; + } + case "feedback": { + const value = this.#processor.feedback(); + this.#postResponse({ + __tunelet: "response", + id: requestId, + requestType, + ok: true, + value, + }); + return; + } + case "takeFeedback": { + const value = this.#processor.takeFeedback(); + this.#postResponse({ + __tunelet: "response", + id: requestId, + requestType, + ok: true, + value, + }); + return; + } + case "telemetry": { + const value = this.#processor.telemetry(); + this.#postResponse({ + __tunelet: "response", + id: requestId, + requestType, + ok: true, + value, + }); + return; + } + case "takeTelemetry": { + const value = this.#processor.takeTelemetry(); + this.#postResponse({ + __tunelet: "response", + id: requestId, + requestType, + ok: true, + value, + }); + return; + } + case "formantEnvelope": { + if ( + typeof request.points !== "number" || + !Number.isInteger(request.points) || + request.points < 0 + ) { + throw new Error("points must be a non-negative integer"); + } + const input = new Float32Array(request.points); + const output = new Float32Array(request.points); + const valid = this.#processor.formantEnvelope( + request.maxFrequencyHz, + input, + output, + ); + const value: FormantEnvelopeResult = { valid, input, output }; + this.#postResponse( + { + __tunelet: "response", + id: requestId, + requestType, + ok: true, + value, + }, + [input.buffer, output.buffer], + ); + return; + } + case "free": { + if (!this.#disposed) { + this.#pendingEvents.length = 0; + this.#draining = false; + this.#stopAfterDrain = false; + this.#disposed = true; + this.#processor.free(); + } + this.#postResponse({ + __tunelet: "response", + id: requestId, + requestType, + ok: true, + }); + return; + } + } + } catch (error) { + this.#postResponse({ + __tunelet: "response", + id: requestId, + requestType, + ok: false, + error: formatError(error), + }); + } + } + + /** Applies immediate stage controls with full Rust validation, or queues MIDI. */ + #applyOrQueueControl(event: ControlEvent): void { + validateControlEventShape(event, this.#processor); + switch (event.type) { + case "configure": + case "punch": + case "warm": + case "resynthesis": + case "alien": + case "reverb": + case "outputGain": { + if (this.#pendingEvents.length > 0) { + this.#draining = false; + this.#stopAfterDrain = false; + this.#enqueueZeroOffsetEvent(event); + return; + } + const nextConfig = + event.type === "configure" + ? event.value + : this.#processor.config(); + if (event.type === "punch") { + nextConfig.punch = event.value; + } else if (event.type === "warm") { + nextConfig.warm = event.value; + } else if (event.type === "resynthesis") { + nextConfig.resynthesis = event.value; + } else if (event.type === "alien") { + nextConfig.alien = event.value; + } else if (event.type === "reverb") { + nextConfig.reverb = event.value; + } else if (event.type === "outputGain") { + nextConfig.outputGain = event.value; + } + this.#processor.setConfig(nextConfig); + this.#draining = false; + this.#stopAfterDrain = false; + return; + } + case "reset": + this.#pendingEvents.length = 0; + this.#draining = false; + this.#stopAfterDrain = false; + this.#processor.reset(); + return; + case "midi": + case "correctionMidi": + this.#draining = false; + this.#stopAfterDrain = false; + this.#enqueueZeroOffsetEvent(event); + return; + } + } + + /** Inserts an event at frame offset 0 after earlier offset-0 events. */ + #enqueueZeroOffsetEvent(event: ControlEvent): void { + let insertIndex = 0; + while ( + insertIndex < this.#pendingEvents.length && + this.#pendingEvents[insertIndex].offset === 0 + ) { + insertIndex += 1; + } + this.#pendingEvents.splice(insertIndex, 0, { offset: 0, event }); + } + + /** Posts a command response over `MessagePort`. */ + #postResponse( + response: TuneletWorkletResponse, + transfer?: Transferable[], + ): void { + const message: TuneletWorkletOutboundMessage = response; + if (transfer && transfer.length > 0) { + this.port.postMessage(message, transfer); + } else { + this.port.postMessage(message); + } + } + + /** Posts a lifecycle notification over `MessagePort`. */ + #postNotification(notification: TuneletWorkletNotification): void { + const message: TuneletWorkletOutboundMessage = notification; + this.port.postMessage(message); + } +} + +/** + * Registers `TuneletWorkletProcessor` in `AudioWorkletGlobalScope`. + * + * When this module loads inside an `AudioWorkletGlobalScope`, it calls this + * function automatically with `TUNELET_PROCESSOR_NAME`. + */ +export function registerTuneletProcessor( + name = TUNELET_PROCESSOR_NAME, +): void { + const register = (globalThis as Record) + .registerProcessor as RegisterProcessorFn | undefined; + if (typeof register !== "function") { + throw new Error( + "registerProcessor is only available in AudioWorkletGlobalScope", + ); + } + register(name, TuneletWorkletProcessor); +} + +if ( + typeof (globalThis as Record).registerProcessor === + "function" +) { + registerTuneletProcessor(TUNELET_PROCESSOR_NAME); +} diff --git a/src/worklet-protocol.ts b/src/worklet-protocol.ts new file mode 100644 index 0000000..b2f0fac --- /dev/null +++ b/src/worklet-protocol.ts @@ -0,0 +1,120 @@ +/** + * Shared constants and `MessagePort` payloads for `tunelet/worklet` and + * `tunelet/worklet-processor`. + */ +import type { + BlockEvents, + ControlEvent, + Feedback, + MidiEvent, + ProcessorConfig, + SyncInitInput, + Telemetry, +} from "./index.js"; + +/** The default Web Audio processor registration name. */ +export const TUNELET_PROCESSOR_NAME = "tunelet-processor"; + +/** The default maximum block length in frames for Web Audio worklet chunks. */ +export const DEFAULT_WORKLET_BLOCK_FRAMES = 128; + +/** + * The initialization fields in `AudioWorkletNodeOptions.processorOptions`. + */ +export interface TuneletProcessorOptions { + /** The WebAssembly bytes or compiled module for `initSync`. */ + wasm: SyncInitInput; + /** The maximum frame count for one internal chunk. The default is 128. */ + maxBlockFrames?: number; + /** The optional initial processor configuration. */ + config?: ProcessorConfig | null; +} + +/** Options for `beginDrain` on a `TuneletWorkletNode`. */ +export interface TuneletDrainOptions { + /** + * If `true`, the worklet processor returns `false` from `process` after the + * tail budget completes. The default is `false`. + */ + stopAfterDrain?: boolean; +} + +/** The result of a formant-envelope request over `MessagePort`. */ +export interface FormantEnvelopeResult { + /** `true` if the formant stage produced valid envelopes. */ + valid: boolean; + /** The analysis vocal-tract envelope. */ + input: Float32Array; + /** The synthesis vocal-tract envelope after width and stretch controls. */ + output: Float32Array; +} + +/** Commands that the main thread sends to `TuneletWorkletProcessor`. */ +export type TuneletWorkletCommand = + | { type: "config" } + | { type: "setConfig"; config: ProcessorConfig } + | { type: "midi"; event: MidiEvent } + | { type: "correctionMidi"; event: MidiEvent } + | { type: "control"; event: ControlEvent } + | { type: "events"; events: BlockEvents } + | { type: "reset" } + | { type: "beginDrain"; stopAfterDrain?: boolean } + | { type: "tailFrames" } + | { type: "feedback" } + | { type: "takeFeedback" } + | { type: "telemetry" } + | { type: "takeTelemetry" } + | { type: "formantEnvelope"; maxFrequencyHz: number; points: number } + | { type: "free" }; + +/** A command message on `MessagePort`, with an optional request identifier. */ +export type TuneletWorkletRequest = TuneletWorkletCommand & { + id?: number; +}; + +/** A response to a `TuneletWorkletRequest` from `TuneletWorkletProcessor`. */ +export type TuneletWorkletResponse = + | { + __tunelet: "response"; + id?: number; + requestType: TuneletWorkletCommand["type"]; + ok: true; + value?: + | ProcessorConfig + | Feedback + | Telemetry + | FormantEnvelopeResult + | number; + } + | { + __tunelet: "response"; + id?: number; + requestType: TuneletWorkletCommand["type"]; + ok: false; + error: string; + }; + +/** Asynchronous lifecycle notifications from `TuneletWorkletProcessor`. */ +export type TuneletWorkletNotification = + | { + __tunelet: "ready"; + sampleRate: number; + maxBlockFrames: number; + latencyFrames: number; + } + | { + __tunelet: "initError"; + error: string; + } + | { + __tunelet: "drainComplete"; + } + | { + __tunelet: "processError"; + error: string; + }; + +/** All messages that `TuneletWorkletProcessor` posts on `MessagePort`. */ +export type TuneletWorkletOutboundMessage = + | TuneletWorkletResponse + | TuneletWorkletNotification; diff --git a/src/worklet.ts b/src/worklet.ts new file mode 100644 index 0000000..cea1358 --- /dev/null +++ b/src/worklet.ts @@ -0,0 +1,624 @@ +/** + * The main-thread Web Audio entry point for `tunelet/worklet`. + * + * Call `createTuneletWorkletNode(context, options)` on the main thread to + * validate the `AudioContext` sample rate, resolve the Wasm binary without + * `fetch` in the worklet, register the worklet script and construct a live + * `TuneletWorkletNode`. + */ +import { loadTuneletWasm } from "./index.js"; +import type { + BlockEvents, + ControlEvent, + Feedback, + InitInput, + MidiEvent, + ProcessorConfig, + SyncInitInput, + Telemetry, +} from "./index.js"; +import { + DEFAULT_WORKLET_BLOCK_FRAMES, + TUNELET_PROCESSOR_NAME, +} from "./worklet-protocol.js"; +import type { + FormantEnvelopeResult, + TuneletDrainOptions, + TuneletProcessorOptions, + TuneletWorkletCommand, + TuneletWorkletNotification, + TuneletWorkletOutboundMessage, + TuneletWorkletRequest, + TuneletWorkletResponse, +} from "./worklet-protocol.js"; + +export { + DEFAULT_WORKLET_BLOCK_FRAMES, + TUNELET_PROCESSOR_NAME, +} from "./worklet-protocol.js"; +export type { + FormantEnvelopeResult, + TuneletDrainOptions, + TuneletProcessorOptions, + TuneletWorkletCommand, + TuneletWorkletNotification, + TuneletWorkletOutboundMessage, + TuneletWorkletRequest, + TuneletWorkletResponse, +} from "./worklet-protocol.js"; + +/** The nominal resynthesis delay in frames at 44.1 kHz and 48 kHz. */ +const NOMINAL_LATENCY_FRAMES = 1593; + +/** Tracks `addModule` promises per `BaseAudioContext` and registration key. */ +const registeredContexts = new WeakMap< + BaseAudioContext, + Map> +>(); + +/** Resolves `AudioWorkletNode` in browsers and in test environments. */ +const AudioWorkletNodeBase: typeof AudioWorkletNode = + typeof globalThis.AudioWorkletNode === "function" + ? globalThis.AudioWorkletNode + : (class extends EventTarget { + constructor( + context: BaseAudioContext, + name: string, + options?: AudioWorkletNodeOptions, + ) { + super(); + if (typeof globalThis.AudioWorkletNode === "function") { + return Reflect.construct( + globalThis.AudioWorkletNode, + [context, name, options], + new.target, + ); + } + throw new Error( + "AudioWorkletNode is not available in this environment", + ); + } + disconnect(): void {} + } as unknown as typeof AudioWorkletNode); + +/** Checks that the `BaseAudioContext` runs at 44.1 kHz or 48 kHz. */ +function validateContextSampleRate(context: BaseAudioContext): void { + if ( + typeof context !== "object" || + context === null || + typeof context.sampleRate !== "number" + ) { + throw new TypeError("context must be a valid BaseAudioContext"); + } + const hz = context.sampleRate; + if (hz !== 44100 && hz !== 48000) { + throw new RangeError( + `unsupported sample rate: ${hz} Hz (expected 44100 or 48000)`, + ); + } +} + +/** Checks `maxBlockFrames` before worklet registration or node creation. */ +function validateMaxBlockFrames(maxBlockFrames: number): void { + if ( + typeof maxBlockFrames !== "number" || + !Number.isInteger(maxBlockFrames) || + maxBlockFrames < 1 || + maxBlockFrames > 0xffff_ffff + ) { + throw new RangeError( + "maxBlockFrames must be an integer in 1..=4294967295", + ); + } +} + +/** Checks `outputChannelCount` before node creation. */ +function validateOutputChannels( + outputChannelCount: readonly number[], +): [1] | [2] { + if ( + !Array.isArray(outputChannelCount) || + outputChannelCount.length !== 1 || + (outputChannelCount[0] !== 1 && outputChannelCount[0] !== 2) + ) { + throw new RangeError("outputChannelCount must be [1] or [2]"); + } + return [outputChannelCount[0]]; +} + +/** Options for `createTuneletWorkletNode`. */ +export interface TuneletWorkletOptions { + /** + * Optional Wasm source for `loadTuneletWasm`. The default is the binary in + * this package. + */ + wasm?: InitInput | Promise; + /** + * Optional URL for the worklet processor script. The default is + * `./worklet-processor.js` relative to this module. + */ + workletUrl?: string | URL; + /** + * Custom processor registration name. The default is + * `TUNELET_PROCESSOR_NAME`. + */ + processorName?: string; + /** + * Maximum frame count for each internal worklet chunk. The default is 128. + */ + maxBlockFrames?: number; + /** Optional initial `ProcessorConfig`. */ + config?: ProcessorConfig | null; + /** Output channel count for output zero: `[2]` (default) or `[1]`. */ + outputChannelCount?: [1] | [2]; + /** Input channel count on the Web Audio node. The default is 1. */ + channelCount?: number; + /** Input channel count mode. The default is `"explicit"`. */ + channelCountMode?: ChannelCountMode; + /** Input channel interpretation. The default is `"speakers"`. */ + channelInterpretation?: ChannelInterpretation; +} + +/** Options for synchronous `new TuneletWorkletNode(context, options)`. */ +export interface TuneletWorkletNodeOptions { + /** Preloaded Wasm bytes or compiled `WebAssembly.Module` for `initSync`. */ + wasm: SyncInitInput; + /** + * Custom processor registration name. The default is + * `TUNELET_PROCESSOR_NAME`. + */ + processorName?: string; + /** + * Maximum frame count for each internal worklet chunk. The default is 128. + */ + maxBlockFrames?: number; + /** Optional initial `ProcessorConfig`. */ + config?: ProcessorConfig | null; + /** Output channel count for output zero: `[2]` (default) or `[1]`. */ + outputChannelCount?: [1] | [2]; + /** Input channel count on the Web Audio node. The default is 1. */ + channelCount?: number; + /** Input channel count mode. The default is `"explicit"`. */ + channelCountMode?: ChannelCountMode; + /** Input channel interpretation. The default is `"speakers"`. */ + channelInterpretation?: ChannelInterpretation; +} + +interface PendingRequest { + resolve: (value: unknown) => void; + reject: (reason: unknown) => void; +} + +/** + * Main-thread `AudioWorkletNode` connected to `TuneletWorkletProcessor` over + * `MessagePort`. + * + * Prefer `createTuneletWorkletNode(context, options)` to load the Wasm binary, + * register the worklet module and await processor initialization. + */ +export class TuneletWorkletNode extends AudioWorkletNodeBase { + /** Resolves when the worklet processor finishes `initSync` and construction. */ + readonly ready: Promise; + + #sampleRate: number; + #maxBlockFrames: number; + #latencyFrames = NOMINAL_LATENCY_FRAMES; + #nextRequestId = 1; + #pending = new Map(); + #drainWaiters: Array<() => void> = []; + #draining = false; + #disposed = false; + + constructor(context: BaseAudioContext, options: TuneletWorkletNodeOptions) { + validateContextSampleRate(context); + if ( + typeof options !== "object" || + options === null || + options.wasm === undefined || + options.wasm === null + ) { + throw new TypeError( + "options.wasm must provide a WebAssembly.Module or byte buffer", + ); + } + + const maxBlockFrames = + options.maxBlockFrames ?? DEFAULT_WORKLET_BLOCK_FRAMES; + validateMaxBlockFrames(maxBlockFrames); + const outputChannelCount = validateOutputChannels( + options.outputChannelCount ?? [2], + ); + const processorName = options.processorName ?? TUNELET_PROCESSOR_NAME; + const processorOptions: TuneletProcessorOptions = { + wasm: options.wasm, + maxBlockFrames, + config: options.config, + }; + + super(context, processorName, { + numberOfInputs: 1, + numberOfOutputs: 1, + outputChannelCount, + channelCount: options.channelCount ?? 1, + channelCountMode: options.channelCountMode ?? "explicit", + channelInterpretation: options.channelInterpretation ?? "speakers", + processorOptions, + }); + + this.#sampleRate = context.sampleRate; + this.#maxBlockFrames = maxBlockFrames; + + let resolveReady!: () => void; + let rejectReady!: (reason: unknown) => void; + let settledReady = false; + this.ready = new Promise((resolve, reject) => { + resolveReady = () => { + if (!settledReady) { + settledReady = true; + resolve(); + } + }; + rejectReady = (reason: unknown) => { + if (!settledReady) { + settledReady = true; + reject(reason); + } + }; + }); + + this.port.onmessage = ( + event: MessageEvent, + ) => { + const message = event.data; + if ( + typeof message !== "object" || + message === null || + !("__tunelet" in message) + ) { + return; + } + + if (message.__tunelet === "ready") { + this.#sampleRate = message.sampleRate; + this.#maxBlockFrames = message.maxBlockFrames; + this.#latencyFrames = message.latencyFrames; + resolveReady(); + return; + } + + if (message.__tunelet === "initError") { + const error = new Error(message.error); + this.#disposed = true; + this.#rejectAllPending(error); + rejectReady(error); + return; + } + + if (message.__tunelet === "drainComplete") { + this.#draining = false; + this.#resolveDrainWaiters(); + if (typeof CustomEvent === "function") { + this.dispatchEvent(new CustomEvent("draincomplete")); + } + return; + } + + if (message.__tunelet === "processError") { + if (typeof CustomEvent === "function") { + this.dispatchEvent( + new CustomEvent("tuneleterror", { detail: new Error(message.error) }), + ); + } + return; + } + + if (message.__tunelet === "response" && message.id !== undefined) { + const entry = this.#pending.get(message.id); + if (!entry) { + return; + } + this.#pending.delete(message.id); + if (message.ok) { + entry.resolve(message.value); + } else { + entry.reject(new Error(message.error)); + } + } + }; + + if (typeof this.addEventListener === "function") { + this.addEventListener("processorerror", () => { + const error = new Error("TuneletWorkletProcessor encountered an error"); + this.#disposed = true; + this.#rejectAllPending(error); + rejectReady(error); + }); + } + } + + /** The sample rate of the processor in hertz. */ + get processorSampleRate(): number { + return this.#sampleRate; + } + + /** The maximum frame count for one internal processor chunk. */ + get maxBlockFrames(): number { + return this.#maxBlockFrames; + } + + /** The nominal resynthesis latency in frames. */ + get latencyFrames(): number { + return this.#latencyFrames; + } + + /** Reads a copy of the active `ProcessorConfig` over `MessagePort`. */ + config(): Promise { + return this.#request({ type: "config" }); + } + + /** Validates and replaces the full `ProcessorConfig` over `MessagePort`. */ + async setConfig(config: ProcessorConfig): Promise { + await this.#request({ type: "setConfig", config }); + this.#draining = false; + this.#resolveDrainWaiters(); + } + + /** Queues a harmony `MidiEvent` for the next audio block. */ + async sendMidi(event: MidiEvent): Promise { + await this.#request({ type: "midi", event }); + this.#draining = false; + this.#resolveDrainWaiters(); + } + + /** Queues a correction-keyboard `MidiEvent` for the next audio block. */ + async sendCorrectionMidi(event: MidiEvent): Promise { + await this.#request({ type: "correctionMidi", event }); + this.#draining = false; + this.#resolveDrainWaiters(); + } + + /** Applies or queues one `ControlEvent` over `MessagePort`. */ + async sendControl(event: ControlEvent): Promise { + await this.#request({ type: "control", event }); + this.#draining = false; + this.#resolveDrainWaiters(); + } + + /** Queues sample-offset `TimedEvent` entries for the next render quantum. */ + async sendEvents(events: BlockEvents): Promise { + await this.#request({ type: "events", events }); + this.#draining = false; + this.#resolveDrainWaiters(); + } + + /** Resets the audio histories and feedback, and cancels any active drain. */ + async reset(): Promise { + await this.#request({ type: "reset" }); + this.#draining = false; + this.#resolveDrainWaiters(); + } + + /** + * Starts a finite tail drain in the worklet and returns the configured tail + * budget in frames. + */ + async beginDrain(options?: TuneletDrainOptions): Promise { + this.#draining = true; + const budget = await this.#request({ + type: "beginDrain", + stopAfterDrain: options?.stopAfterDrain, + }); + if (budget === 0) { + this.#draining = false; + this.#resolveDrainWaiters(); + } + return budget; + } + + /** + * Resolves when the active drain finishes its tail budget or when another + * command cancels the drain. + */ + waitForDrain(): Promise { + if (!this.#draining || this.#disposed) { + return Promise.resolve(); + } + return new Promise((resolve) => { + this.#drainWaiters.push(resolve); + }); + } + + /** Returns the configured tail budget in frames. */ + tailFrames(): Promise { + return this.#request({ type: "tailFrames" }); + } + + /** Reads a `Feedback` snapshot and does not clear the stereo peak window. */ + feedback(): Promise { + return this.#request({ type: "feedback" }); + } + + /** Reads a `Feedback` snapshot and clears the stereo peak window. */ + takeFeedback(): Promise { + return this.#request({ type: "takeFeedback" }); + } + + /** Reads a `Telemetry` snapshot and does not clear its peak windows. */ + telemetry(): Promise { + return this.#request({ type: "telemetry" }); + } + + /** Reads a `Telemetry` snapshot and clears its three peak windows. */ + takeTelemetry(): Promise { + return this.#request({ type: "takeTelemetry" }); + } + + /** Reads the analysis and synthesis formant envelopes with `points` samples. */ + formantEnvelope( + maxFrequencyHz: number, + points: number, + ): Promise { + return this.#request({ + type: "formantEnvelope", + maxFrequencyHz, + points, + }); + } + + /** Releases the Wasm processor in the worklet and disconnects the node. */ + async free(): Promise { + if (this.#disposed) { + return; + } + this.#disposed = true; + this.#draining = false; + this.#resolveDrainWaiters(); + try { + await this.#requestAllowDisposed({ type: "free" }); + } finally { + this.disconnect(); + this.port.close(); + this.#rejectAllPending(new Error("TuneletWorkletNode was disposed")); + } + } + + /** Starts asynchronous cleanup for `Symbol.dispose`. */ + [Symbol.dispose](): void { + void this.free(); + } + + /** Sends one request with a correlation ID over `MessagePort`. */ + #request(command: TuneletWorkletCommand): Promise { + if (this.#disposed) { + return Promise.reject(new Error("TuneletWorkletNode is disposed")); + } + return this.#requestAllowDisposed(command); + } + + /** Sends one request also when `free()` shuts down the node. */ + #requestAllowDisposed(command: TuneletWorkletCommand): Promise { + const id = this.#nextRequestId; + this.#nextRequestId += 1; + const message: TuneletWorkletRequest = { ...command, id }; + return new Promise((resolve, reject) => { + this.#pending.set(id, { + resolve: resolve as (value: unknown) => void, + reject, + }); + this.port.postMessage(message); + }); + } + + /** Rejects all unresolved `MessagePort` requests. */ + #rejectAllPending(error: Error): void { + for (const pending of this.#pending.values()) { + pending.reject(error); + } + this.#pending.clear(); + this.#draining = false; + this.#resolveDrainWaiters(); + } + + /** Resolves all callers that await `waitForDrain()`. */ + #resolveDrainWaiters(): void { + if (this.#drainWaiters.length === 0) { + return; + } + const waiters = this.#drainWaiters.splice(0, this.#drainWaiters.length); + for (const resolve of waiters) { + resolve(); + } + } +} + +/** + * Registers the `tunelet` worklet processor module on `context.audioWorklet`. + * + * The function rejects unsupported `AudioContext` sample rates before it calls + * `addModule`. Concurrent or repeated calls for the same context and URL share + * one registration promise. If `addModule` fails, the cached entry clears so a + * later call can try again. + */ +export async function registerTuneletWorklet( + context: BaseAudioContext, + workletUrl?: string | URL, +): Promise { + validateContextSampleRate(context); + if (!context.audioWorklet || typeof context.audioWorklet.addModule !== "function") { + throw new Error( + "context.audioWorklet is not available (use a secure HTTPS or localhost origin)", + ); + } + + const resolvedHref = + workletUrl === undefined + ? new URL("./worklet-processor.js", import.meta.url).href + : workletUrl instanceof URL + ? workletUrl.href + : String(workletUrl); + + let perContext = registeredContexts.get(context); + if (!perContext) { + perContext = new Map>(); + registeredContexts.set(context, perContext); + } + + let registration = perContext.get(resolvedHref); + if (!registration) { + registration = context.audioWorklet + .addModule(resolvedHref) + .catch((error: unknown) => { + perContext?.delete(resolvedHref); + throw error; + }); + perContext.set(resolvedHref, registration); + } + await registration; +} + +/** + * Loads the Wasm binary on the main thread, registers the worklet processor + * and returns an initialized `TuneletWorkletNode`. + * + * Rejects unsupported `AudioContext` sample rates (rates other than 44100 Hz + * and 48000 Hz) before it registers the worklet, loads Wasm or creates a node. + */ +export async function createTuneletWorkletNode( + context: BaseAudioContext, + options?: TuneletWorkletOptions, +): Promise { + validateContextSampleRate(context); + const maxBlockFrames = + options?.maxBlockFrames ?? DEFAULT_WORKLET_BLOCK_FRAMES; + validateMaxBlockFrames(maxBlockFrames); + const outputChannelCount = validateOutputChannels( + options?.outputChannelCount ?? [2], + ); + + const [wasm] = await Promise.all([ + loadTuneletWasm(options?.wasm), + registerTuneletWorklet(context, options?.workletUrl), + ]); + + const node = new TuneletWorkletNode(context, { + wasm, + processorName: options?.processorName, + maxBlockFrames, + config: options?.config, + outputChannelCount, + channelCount: options?.channelCount, + channelCountMode: options?.channelCountMode, + channelInterpretation: options?.channelInterpretation, + }); + + try { + await node.ready; + } catch (error) { + node.disconnect(); + node.port.close(); + throw error; + } + return node; +} + +export default createTuneletWorkletNode; diff --git a/tsconfig.json b/tsconfig.json index 27aa560..2b20eec 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -11,5 +11,9 @@ "rootDir": "src", "outDir": "dist" }, - "include": ["src/index.ts"] + "include": [ + "src/index.ts", + "src/worklet.ts", + "src/worklet-processor.ts" + ] }