From 0ca1c0899171ca08a13a332890c2e8f96f9086dd Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Sat, 21 Nov 2026 01:56:27 +0000 Subject: [PATCH] feat(npm): add TypeScript AudioWorklet adapter - Export tunelet/worklet in package.json and tsconfig.json - Add a UTF-8 shim for TextDecoder and TextEncoder in worklets - Add TuneletWorkletProcessor with reusable Int16Array buffers - Resample non-native AudioContext rates to and from 48 kHz - Throttle feedback and telemetry reports to a UI interval - Export createTuneletNode with typed control methods - Document the AudioWorklet adapter in README.md --- README.md | 23 +- package.json | 9 +- src/index.ts | 425 +++++++++++++++++++- src/utf8-shim.ts | 230 +++++++++++ src/worklet-protocol.ts | 67 ++++ src/worklet.ts | 859 ++++++++++++++++++++++++++++++++++++++++ tsconfig.json | 2 +- 7 files changed, 1606 insertions(+), 9 deletions(-) create mode 100644 src/utf8-shim.ts create mode 100644 src/worklet-protocol.ts create mode 100644 src/worklet.ts diff --git a/README.md b/README.md index d2993dc..f5189a4 100644 --- a/README.md +++ b/README.md @@ -358,6 +358,7 @@ these items: - One Wasm binary. - The generated bindings. - A shared `loadTunelet` entry point. +- A browser `AudioWorklet` adapter (`createTuneletNode` and `tunelet/worklet`). ### Load the module @@ -409,6 +410,7 @@ page that opens the JavaScript. | Operation | TypeScript API | | --------------------------------- | -------------------------------------------------------- | | Shared initialization | `loadTunelet(source?)` | +| Browser AudioWorklet node | `createTuneletNode(context, options?)` | | Mono PCM to planar stereo | `process(input, left, right, events?)` | | In-place mono downmix | `processMono(audio, events?)` | | Configuration | `config()`, `setConfig(config)`, `defaultConfig()` | @@ -430,9 +432,24 @@ frame limit. These rules apply: 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. +Direct `Tunelet` calls use `Int16Array` samples. For Web Audio `Float32Array` +graphs in browsers, call `createTuneletNode(audioContext)` to register +`tunelet/worklet` and construct a `TuneletWorkletNode`: + +```ts +import { createTuneletNode } from "tunelet"; + +const context = new AudioContext(); +const mic = await navigator.mediaDevices.getUserMedia({ audio: true }); +const node = await createTuneletNode(context); +context.createMediaStreamSource(mic).connect(node).connect(context.destination); +``` + +`TuneletWorkletProcessor` installs an internal UTF-8 shim, reuses pre-allocated +`Int16Array` buffers and throttles `feedback` and `telemetry` reports to a UI +interval (50 ms by default). Contexts at 44.1 kHz or 48 kHz run at their native +rate. Contexts at other rates (such as 88.2 kHz or 96 kHz) resample each block +to and from an internal 48 kHz `Tunelet` instance. ### Configuration objects diff --git a/package.json b/package.json index 511ddfa..d1eede8 100644 --- a/package.json +++ b/package.json @@ -15,6 +15,10 @@ "types": "./dist/index.d.ts", "import": "./dist/index.js" }, + "./worklet": { + "types": "./dist/worklet.d.ts", + "import": "./dist/worklet.js" + }, "./wasm": { "types": "./pkg/tunelet.d.ts", "import": "./pkg/tunelet.js" @@ -26,7 +30,10 @@ "pkg/tunelet.d.ts", "pkg/tunelet_bg.wasm" ], - "sideEffects": false, + "sideEffects": [ + "./dist/worklet.js", + "./dist/utf8-shim.js" + ], "scripts": { "build": "npm run build:wasm && npm run build:ts", "build:wasm": "wasm-pack build --target web --out-dir pkg --release --no-opt --features wasm --locked", diff --git a/src/index.ts b/src/index.ts index da35a57..496dd0f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -2,19 +2,129 @@ * 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 - * same Wasm binary. This module re-exports all named exports of the module - * that wasm-bindgen generates, which include `Tunelet`, `defaultConfig`, + * configuration. For live Web Audio graphs in browsers, call + * `createTuneletNode(audioContext)` to register `tunelet/worklet` and construct + * a typed `AudioWorkletNode`. 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, { initSync } from "../pkg/tunelet.js"; -import type { InitInput, InitOutput } from "../pkg/tunelet.js"; +import type { + ControlEvent, + Feedback, + InitInput, + InitOutput, + ProcessorConfig, + Telemetry, + TimedEvent, +} from "../pkg/tunelet.js"; +import { TUNELET_WORKLET_PROCESSOR_NAME } from "./worklet-protocol.js"; +import type { + TuneletProcessorOptions, + TuneletReportingOptions, + TuneletWorkletCommand, + TuneletWorkletMessage, +} from "./worklet-protocol.js"; export * from "../pkg/tunelet.js"; +export { TUNELET_WORKLET_PROCESSOR_NAME } from "./worklet-protocol.js"; +export type { + TuneletProcessorOptions, + TuneletReportingOptions, + TuneletWorkletCommand, + TuneletWorkletMessage, +} from "./worklet-protocol.js"; + +/** Options for `createTuneletNode`. */ +export interface TuneletNodeOptions extends TuneletReportingOptions { + /** The initial configuration for the worklet processor. */ + config?: ProcessorConfig; + /** + * The optional Wasm binary source. The default is the packaged + * `tunelet_bg.wasm` asset. + */ + module?: InitInput | Promise; + /** + * The optional module URL for `audioWorklet.addModule`. The default is the + * packaged `worklet.js` entry. + */ + workletUrl?: string | URL; + /** The prepared host block limit in frames. The default is 128. */ + maxBlockFrames?: number; + /** The output channel count for each output. The default is `[2]`. */ + outputChannelCount?: number[]; + /** Additional fields for `AudioWorkletNodeOptions.processorOptions`. */ + processorOptions?: Record; + /** Receives each throttled `Feedback` snapshot from the audio thread. */ + onFeedback?: ((feedback: Feedback) => void) | null; + /** Receives each throttled `Telemetry` snapshot from the audio thread. */ + onTelemetry?: ((telemetry: Telemetry) => void) | null; + /** Receives validation errors from asynchronous control messages. */ + onError?: ((error: Error) => void) | null; +} + +/** + * An `AudioWorkletNode` with typed controls and throttled state snapshots for + * `TuneletWorkletProcessor`. + */ +export interface TuneletWorkletNode extends AudioWorkletNode { + /** The latest throttled `Feedback` snapshot, or `undefined` before reports. */ + readonly feedback: Feedback | undefined; + /** The latest throttled `Telemetry` snapshot, or `undefined` before reports. */ + readonly telemetry: Telemetry | undefined; + /** A callback that receives each throttled `Feedback` snapshot. */ + onFeedback: ((feedback: Feedback) => void) | null; + /** A callback that receives each throttled `Telemetry` snapshot. */ + onTelemetry: ((telemetry: Telemetry) => void) | null; + /** A callback that receives validation errors from control messages. */ + onError: ((error: Error) => void) | null; + /** Replaces the full `ProcessorConfig` on the audio thread. */ + setConfig(config: ProcessorConfig): void; + /** Queues one `ControlEvent` (at offset 0) or `TimedEvent` for the next block. */ + sendEvent(event: ControlEvent | TimedEvent): void; + /** Queues a slice of `TimedEvent` items for the next block. */ + sendEvents(events: readonly TimedEvent[]): void; + /** Resets the audio histories, resampler state and feedback. */ + reset(): void; + /** Starts a finite tail drain on the audio thread. */ + beginDrain(): void; + /** Updates the UI report interval and active report fields. */ + setReporting(options: TuneletReportingOptions): void; + /** Releases the Wasm processor memory and disconnects the node. */ + dispose(): void; + [Symbol.dispose](): void; +} /** The shared initialization promise, which a failure clears. */ let initialization: Promise | undefined; +/** The cached compiled Wasm module for the default packaged binary. */ +let compiledDefaultModule: Promise | undefined; + +/** Registered worklet module promises for each `BaseAudioContext`. */ +const registeredWorklets = new WeakMap< + BaseAudioContext, + Map> +>(); + +type AudioWorkletNodeConstructor = typeof AudioWorkletNode; +type BuiltNodeConstructor = new ( + context: BaseAudioContext, + nodeOptions: AudioWorkletNodeOptions, + callbacks: { + onFeedback?: ((feedback: Feedback) => void) | null; + onTelemetry?: ((telemetry: Telemetry) => void) | null; + onError?: ((error: Error) => void) | null; + }, +) => TuneletWorkletNode; + +/** Cached `TuneletWorkletNode` subclasses for each `AudioWorkletNode` class. */ +const nodeSubclasses = new WeakMap< + AudioWorkletNodeConstructor, + BuiltNodeConstructor +>(); + /** * Initializes the Wasm module one time for this imported package instance. * @@ -57,6 +167,60 @@ export function loadTunelet( return initialization; } +/** + * Compiles the Wasm binary, registers `tunelet/worklet` on `context` and + * returns a live `TuneletWorkletNode`. + * + * The node accepts mono or multi-channel `Float32` input and produces stereo + * output by default. Contexts at 44.1 kHz or 48 kHz run at their native rate. + * Contexts at other rates (such as 88.2 kHz or 96 kHz) resample to and from + * an internal 48 kHz `Tunelet` processor. + * + * @param context The target `AudioContext` or `OfflineAudioContext`. + * @param options Optional configuration, asset URLs and report settings. + * @returns A connected-ready `TuneletWorkletNode`. + */ +export async function createTuneletNode( + context: BaseAudioContext, + options?: TuneletNodeOptions, +): Promise { + if (!context || !context.audioWorklet) { + throw new Error("The AudioContext does not provide an audioWorklet."); + } + + const BaseNode = readAudioWorkletNodeConstructor(); + const [wasmModule] = await Promise.all([ + compileTuneletModule(options?.module), + registerWorkletModule(context, options?.workletUrl), + ]); + initSync({ module: wasmModule }); + + const processorOptions: TuneletProcessorOptions & Record = { + ...options?.processorOptions, + module: wasmModule, + config: options?.config, + sampleRate: context.sampleRate, + maxBlockFrames: options?.maxBlockFrames, + reportIntervalMs: options?.reportIntervalMs, + feedback: options?.feedback, + telemetry: options?.telemetry, + }; + + const nodeOptions: AudioWorkletNodeOptions = { + numberOfInputs: 1, + numberOfOutputs: 1, + outputChannelCount: options?.outputChannelCount ?? [2], + processorOptions, + }; + + const NodeClass = getOrCreateNodeSubclass(BaseNode); + return new NodeClass(context, nodeOptions, { + onFeedback: options?.onFeedback, + onTelemetry: options?.onTelemetry, + onError: options?.onError, + }); +} + /** Awaits the source one time, then initializes the Wasm module from it. */ async function initialize( source: InitInput | Promise | undefined, @@ -80,5 +244,258 @@ async function initialize( return init({ module_or_path: input }); } +/** Compiles a `WebAssembly.Module` and caches the default packaged binary. */ +function compileTuneletModule( + source?: InitInput | Promise, +): Promise { + if (source !== undefined) { + return compileFromSource(source); + } + compiledDefaultModule ??= compileFromSource(undefined).catch( + (error: unknown) => { + compiledDefaultModule = undefined; + throw error; + }, + ); + return compiledDefaultModule; +} + +/** Resolves any `InitInput` source into a compiled `WebAssembly.Module`. */ +async function compileFromSource( + 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 URL && input.protocol === "file:") { + const moduleName = "node:fs/promises"; + const fs: typeof import("node:fs/promises") = await import( + /* webpackIgnore: true */ /* @vite-ignore */ moduleName + ); + const bytes = await fs.readFile(input); + return WebAssembly.compile( + new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength), + ); + } + + if (ArrayBuffer.isView(input)) { + return WebAssembly.compile( + new Uint8Array(input.buffer, input.byteOffset, input.byteLength), + ); + } + + if (input instanceof ArrayBuffer) { + return WebAssembly.compile(input); + } + + if (typeof Response === "function" && input instanceof Response) { + return compileFromResponse(input); + } + + const response = await fetch(input as RequestInfo | URL); + return compileFromResponse(response); +} + +/** Compiles a `Response` via `WebAssembly.compileStreaming` when supported. */ +async function compileFromResponse( + response: Response, +): Promise { + if (!response.ok) { + throw new Error( + `failed to fetch Wasm: ${response.status} ${response.statusText} fetching '${response.url}'`, + ); + } + const contentType = response.headers?.get("Content-Type")?.toLowerCase() ?? ""; + if ( + typeof WebAssembly.compileStreaming === "function" && + contentType.includes("application/wasm") + ) { + return WebAssembly.compileStreaming(response); + } + return WebAssembly.compile(await response.arrayBuffer()); +} + +/** Registers the worklet module one time for each `(context, url)` pair. */ +function registerWorkletModule( + context: BaseAudioContext, + workletUrl?: string | URL, +): Promise { + const resolved = workletUrl ?? new URL("./worklet.js", import.meta.url); + const href = typeof resolved === "string" ? resolved : resolved.href; + + let byUrl = registeredWorklets.get(context); + if (!byUrl) { + byUrl = new Map>(); + registeredWorklets.set(context, byUrl); + } + + let pending = byUrl.get(href); + if (!pending) { + const mapRef = byUrl; + pending = context.audioWorklet.addModule(href).catch((error: unknown) => { + mapRef.delete(href); + throw error; + }); + byUrl.set(href, pending); + } + return pending; +} + +/** Returns `globalThis.AudioWorkletNode` or throws if Web Audio is absent. */ +function readAudioWorkletNodeConstructor(): AudioWorkletNodeConstructor { + const candidate = (globalThis as { AudioWorkletNode?: unknown }) + .AudioWorkletNode; + if (typeof candidate !== "function") { + throw new Error( + "AudioWorkletNode is not available in this JavaScript environment.", + ); + } + return candidate as AudioWorkletNodeConstructor; +} + +/** Builds a subclass of `BaseNode` lazily so Node.js imports stay safe. */ +function getOrCreateNodeSubclass( + BaseNode: AudioWorkletNodeConstructor, +): BuiltNodeConstructor { + const existing = nodeSubclasses.get(BaseNode); + if (existing) { + return existing; + } + + class TuneletWorkletNodeImpl extends BaseNode implements TuneletWorkletNode { + onFeedback: ((feedback: Feedback) => void) | null; + onTelemetry: ((telemetry: Telemetry) => void) | null; + onError: ((error: Error) => void) | null; + + #feedback: Feedback | undefined; + #telemetry: Telemetry | undefined; + #disposed = false; + readonly #listener: (event: MessageEvent) => void; + + constructor( + context: BaseAudioContext, + nodeOptions: AudioWorkletNodeOptions, + callbacks: { + onFeedback?: ((feedback: Feedback) => void) | null; + onTelemetry?: ((telemetry: Telemetry) => void) | null; + onError?: ((error: Error) => void) | null; + }, + ) { + super(context, TUNELET_WORKLET_PROCESSOR_NAME, nodeOptions); + this.onFeedback = callbacks.onFeedback ?? null; + this.onTelemetry = callbacks.onTelemetry ?? null; + this.onError = callbacks.onError ?? null; + + this.#listener = (event: MessageEvent) => { + this.#handleMessage(event.data); + }; + + if (typeof this.port.addEventListener === "function") { + this.port.addEventListener("message", this.#listener); + this.port.start?.(); + } else { + this.port.onmessage = this.#listener; + } + (this.port as { unref?: () => void }).unref?.(); + } + + get feedback(): Feedback | undefined { + return this.#feedback; + } + + get telemetry(): Telemetry | undefined { + return this.#telemetry; + } + + setConfig(config: ProcessorConfig): void { + this.#postCommand({ type: "setConfig", config }); + } + + sendEvent(event: ControlEvent | TimedEvent): void { + const timed: TimedEvent = + "offset" in event && "event" in event + ? { offset: event.offset, event: event.event } + : { offset: 0, event }; + this.#postCommand({ type: "events", events: [timed] }); + } + + sendEvents(events: readonly TimedEvent[]): void { + if (events.length === 0) { + return; + } + this.#postCommand({ type: "events", events: Array.from(events) }); + } + + reset(): void { + this.#postCommand({ type: "reset" }); + } + + beginDrain(): void { + this.#postCommand({ type: "beginDrain" }); + } + + setReporting(options: TuneletReportingOptions): void { + this.#postCommand({ type: "setReporting", ...options }); + } + + dispose(): void { + if (this.#disposed) { + return; + } + this.#disposed = true; + this.port.postMessage({ type: "dispose" } satisfies TuneletWorkletCommand); + if (typeof this.port.removeEventListener === "function") { + this.port.removeEventListener("message", this.#listener); + } else if (this.port.onmessage === this.#listener) { + this.port.onmessage = null; + } + this.port.close?.(); + try { + this.disconnect(); + } catch { + // Ignore disconnect errors if the node was never connected. + } + } + + [Symbol.dispose](): void { + this.dispose(); + } + + #postCommand(command: TuneletWorkletCommand): void { + if (this.#disposed) { + throw new Error("The TuneletWorkletNode is disposed."); + } + this.port.postMessage(command); + } + + #handleMessage(message: TuneletWorkletMessage | undefined): void { + if (!message || typeof message !== "object") { + return; + } + if (message.type === "report") { + if (message.feedback !== undefined) { + this.#feedback = message.feedback; + this.onFeedback?.(message.feedback); + } + if (message.telemetry !== undefined) { + this.#telemetry = message.telemetry; + this.onTelemetry?.(message.telemetry); + } + } else if (message.type === "error") { + this.onError?.(new Error(message.message)); + } + } + } + + nodeSubclasses.set(BaseNode, TuneletWorkletNodeImpl); + return TuneletWorkletNodeImpl; +} + /** The default export is the same function as `loadTunelet`. */ export default loadTunelet; diff --git a/src/utf8-shim.ts b/src/utf8-shim.ts new file mode 100644 index 0000000..9f01eb9 --- /dev/null +++ b/src/utf8-shim.ts @@ -0,0 +1,230 @@ +/** + * The internal UTF-8 shim for `AudioWorkletGlobalScope`. + * + * Browsers do not expose `TextDecoder` or `TextEncoder` on the audio thread. + * The generated Wasm glue constructs both classes when the module loads. Import + * this file before `../pkg/tunelet.js` so `globalThis` has both classes first. + */ + +interface ShimDecoderOptions { + fatal?: boolean; + ignoreBOM?: boolean; +} + +class Utf8TextDecoder { + readonly encoding = "utf-8"; + readonly fatal: boolean; + readonly ignoreBOM: boolean; + + constructor(label = "utf-8", options?: ShimDecoderOptions) { + const normalized = String(label).trim().toLowerCase(); + if ( + normalized !== "utf-8" && + normalized !== "utf8" && + normalized !== "unicode-1-1-utf-8" + ) { + throw new RangeError(`The encoding label "${label}" is not supported.`); + } + this.fatal = Boolean(options?.fatal); + this.ignoreBOM = Boolean(options?.ignoreBOM); + } + + decode(input?: AllowSharedBufferSource): string { + if (input === undefined) { + return ""; + } + const bytes = toUint8View(input); + const length = bytes.length; + if (length === 0) { + return ""; + } + + 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 = + b0 === 0xe0 + ? b1 >= 0xa0 && b1 <= 0xbf + : b0 === 0xed + ? b1 >= 0x80 && b1 <= 0x9f + : (b1 & 0xc0) === 0x80; + 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 = + b0 === 0xf0 + ? b1 >= 0x90 && b1 <= 0xbf + : b0 === 0xf4 + ? b1 >= 0x80 && b1 <= 0x8f + : (b1 & 0xc0) === 0x80; + if (validSecond && (b2 & 0xc0) === 0x80 && (b3 & 0xc0) === 0x80) { + const codePoint = + ((b0 & 0x07) << 18) | + ((b1 & 0x3f) << 12) | + ((b2 & 0x3f) << 6) | + (b3 & 0x3f); + result += String.fromCodePoint(codePoint); + index += 4; + continue; + } + } + } + + if (this.fatal) { + throw new TypeError("The byte sequence is not valid UTF-8."); + } + result += "\ufffd"; + index += 1; + } + + return result; + } +} + +class Utf8TextEncoder { + readonly encoding = "utf-8"; + + encode(input = ""): Uint8Array { + const text = String(input); + const buffer = new Uint8Array(text.length * 3); + const { written } = this.encodeInto(text, buffer); + return buffer.slice(0, written); + } + + encodeInto( + source: string, + destination: Uint8Array, + ): { read: number; written: number } { + const text = String(source); + const limit = destination.length; + let read = 0; + let written = 0; + + while (read < text.length) { + const first = text.charCodeAt(read); + if (first < 0x80) { + if (written + 1 > limit) { + break; + } + destination[written] = first; + read += 1; + written += 1; + } else if (first < 0x800) { + if (written + 2 > limit) { + break; + } + destination[written] = 0xc0 | (first >> 6); + destination[written + 1] = 0x80 | (first & 0x3f); + read += 1; + written += 2; + } else if (first >= 0xd800 && first <= 0xdbff) { + if (read + 1 < text.length) { + const second = text.charCodeAt(read + 1); + if (second >= 0xdc00 && second <= 0xdfff) { + if (written + 4 > limit) { + break; + } + const codePoint = + 0x10000 + ((first - 0xd800) << 10) + (second - 0xdc00); + destination[written] = 0xf0 | (codePoint >> 18); + destination[written + 1] = 0x80 | ((codePoint >> 12) & 0x3f); + destination[written + 2] = 0x80 | ((codePoint >> 6) & 0x3f); + destination[written + 3] = 0x80 | (codePoint & 0x3f); + read += 2; + written += 4; + continue; + } + } + if (written + 3 > limit) { + break; + } + destination[written] = 0xef; + destination[written + 1] = 0xbf; + destination[written + 2] = 0xbd; + read += 1; + written += 3; + } else if (first >= 0xdc00 && first <= 0xdfff) { + if (written + 3 > limit) { + break; + } + destination[written] = 0xef; + destination[written + 1] = 0xbf; + destination[written + 2] = 0xbd; + read += 1; + written += 3; + } else { + if (written + 3 > limit) { + break; + } + destination[written] = 0xe0 | (first >> 12); + destination[written + 1] = 0x80 | ((first >> 6) & 0x3f); + destination[written + 2] = 0x80 | (first & 0x3f); + read += 1; + written += 3; + } + } + + return { read, written }; + } +} + +/** Returns a `Uint8Array` view over any buffer source without a copy. */ +function toUint8View(input: AllowSharedBufferSource): Uint8Array { + if (input instanceof Uint8Array) { + return input; + } + if (ArrayBuffer.isView(input)) { + return new Uint8Array(input.buffer, input.byteOffset, input.byteLength); + } + return new Uint8Array(input); +} + +const scope = globalThis as { + TextDecoder?: unknown; + TextEncoder?: unknown; +}; + +scope.TextDecoder ??= Utf8TextDecoder; +scope.TextEncoder ??= Utf8TextEncoder; + +export {}; diff --git a/src/worklet-protocol.ts b/src/worklet-protocol.ts new file mode 100644 index 0000000..5534f2f --- /dev/null +++ b/src/worklet-protocol.ts @@ -0,0 +1,67 @@ +/** + * Shared constants and message types for `createTuneletNode` and + * `tunelet/worklet`. + */ +import type { + Feedback, + ProcessorConfig, + SyncInitInput, + Telemetry, + TimedEvent, +} from "../pkg/tunelet.js"; + +/** The registered `AudioWorkletProcessor` name for `tunelet/worklet`. */ +export const TUNELET_WORKLET_PROCESSOR_NAME = "tunelet"; + +/** The default Web Audio block limit in frames. */ +export const DEFAULT_MAX_BLOCK_FRAMES = 128; + +/** The default interval between UI reports in milliseconds. */ +export const DEFAULT_REPORT_INTERVAL_MS = 50; + +/** Controls periodic feedback and telemetry snapshots from the worklet. */ +export interface TuneletReportingOptions { + /** + * The minimum interval between UI reports in milliseconds. Set 0 to disable + * periodic reports. The default is 50. + */ + reportIntervalMs?: number; + /** Enables periodic `Feedback` reports. The default is `true`. */ + feedback?: boolean; + /** Enables periodic `Telemetry` reports. The default is `true`. */ + telemetry?: boolean; +} + +/** + * The `processorOptions` payload that `TuneletWorkletProcessor` reads at + * construction. + */ +export interface TuneletProcessorOptions extends TuneletReportingOptions { + /** The compiled Wasm module or bytes for synchronous initialization. */ + module?: SyncInitInput; + /** The initial configuration for the `Tunelet` processor. */ + config?: ProcessorConfig; + /** + * The host `AudioContext` sample rate in hertz. The default is the global + * `sampleRate` of `AudioWorkletGlobalScope`. + */ + sampleRate?: number; + /** The maximum host block size for one chunk in frames. The default is 128. */ + maxBlockFrames?: number; +} + +/** Commands that the main thread sends to `TuneletWorkletProcessor`. */ +export type TuneletWorkletCommand = + | { type: "setConfig"; config: ProcessorConfig } + | { type: "events"; events: TimedEvent[] } + | { type: "reset" } + | { type: "beginDrain" } + | ({ type: "setReporting" } & TuneletReportingOptions) + | { type: "dispose" }; + +/** Messages that `TuneletWorkletProcessor` sends to the main thread. */ +export type TuneletWorkletMessage = + | { type: "report"; feedback?: Feedback; telemetry?: Telemetry } + | { type: "drainStarted"; tailFrames: number } + | { type: "drainComplete" } + | { type: "error"; message: string }; diff --git a/src/worklet.ts b/src/worklet.ts new file mode 100644 index 0000000..297f371 --- /dev/null +++ b/src/worklet.ts @@ -0,0 +1,859 @@ +/** + * The `AudioWorklet` entry point for `tunelet/worklet`. + * + * This module installs the UTF-8 shim first, imports the generated Wasm + * bindings, defines `TuneletWorkletProcessor` and registers it in + * `AudioWorkletGlobalScope`. + */ +import "./utf8-shim.js"; +import { initSync, Tunelet } from "../pkg/tunelet.js"; +import type { + Feedback, + ProcessorConfig, + Telemetry, + TimedEvent, +} from "../pkg/tunelet.js"; +import { + DEFAULT_MAX_BLOCK_FRAMES, + DEFAULT_REPORT_INTERVAL_MS, + TUNELET_WORKLET_PROCESSOR_NAME, +} from "./worklet-protocol.js"; +import type { + TuneletProcessorOptions, + TuneletReportingOptions, + TuneletWorkletCommand, + TuneletWorkletMessage, +} from "./worklet-protocol.js"; + +export { TUNELET_WORKLET_PROCESSOR_NAME } from "./worklet-protocol.js"; +export type { + TuneletProcessorOptions, + TuneletReportingOptions, + TuneletWorkletCommand, + TuneletWorkletMessage, +} from "./worklet-protocol.js"; + +const INV_PCM_SCALE = 1 / 32768; +const INTERNAL_FALLBACK_RATE = 48000; +const RESAMPLE_CUSHION_FRAMES = 3; +const ANTI_ALIAS_CUTOFF_HZ = 20000; + +interface WorkletProcessorInstance { + readonly port: MessagePort; +} + +interface WorkletProcessorConstructor { + new (options?: AudioWorkletNodeOptions): WorkletProcessorInstance; +} + +const WorkletProcessorBase: WorkletProcessorConstructor = + typeof (globalThis as { AudioWorkletProcessor?: unknown }) + .AudioWorkletProcessor === "function" + ? ( + globalThis as unknown as { + AudioWorkletProcessor: WorkletProcessorConstructor; + } + ).AudioWorkletProcessor + : class FallbackWorkletProcessor implements WorkletProcessorInstance { + readonly port: MessagePort; + + constructor() { + const channel = new MessageChannel(); + (channel.port1 as { unref?: () => void }).unref?.(); + (channel.port2 as { unref?: () => void }).unref?.(); + this.port = channel.port1; + } + }; + +/** + * Wraps a Wasm `Tunelet` processor for Web Audio `Float32Array` blocks. + * + * The constructor allocates all `Int16Array` buffers, length views and rate + * conversion arrays one time. Contexts at 44.1 kHz or 48 kHz run at their + * native rate. Contexts at other rates use an internal 48 kHz `Tunelet` + * instance with a stateful block resampler. + */ +export class TuneletWorkletProcessor extends WorkletProcessorBase { + /** The sample rate of the host `AudioContext` in hertz. */ + readonly hostSampleRate: number; + /** The internal sample rate of the `Tunelet` instance (44100 or 48000). */ + readonly sampleRate: number; + /** The maximum host frame count for one internal chunk. */ + readonly maxBlockFrames: number; + + private readonly engine: Tunelet; + private readonly needsResample: boolean; + private readonly stepDown: number; + private readonly stepUp: number; + + private readonly pcmInput: Int16Array; + private readonly pcmLeft: Int16Array; + private readonly pcmRight: Int16Array; + private readonly pcmInputViews: readonly Int16Array[]; + private readonly pcmLeftViews: readonly Int16Array[]; + private readonly pcmRightViews: readonly Int16Array[]; + + private readonly monoScratch: Float32Array; + private readonly inputHistory: Float32Array; + private readonly outQueueL: Float32Array; + private readonly outQueueR: Float32Array; + + private readonly useAntiAlias: boolean; + private readonly aaB0: number; + private readonly aaB1: number; + private readonly aaB2: number; + private readonly aaA1: number; + private readonly aaA2: number; + private aaZ1 = 0; + private aaZ2 = 0; + + private inputCursor = 0; + private outputCursor = 0; + private queueLength = 0; + + private pendingEvents: TimedEvent[] = []; + private reportIntervalFrames = 0; + private framesSinceReport = 0; + private feedbackEnabled = true; + private telemetryEnabled = true; + private draining = false; + private disposed = false; + + constructor(options?: AudioWorkletNodeOptions) { + super(options); + + const processorOptions = (options?.processorOptions ?? + {}) as TuneletProcessorOptions; + + if (processorOptions.module !== undefined) { + initSync({ module: processorOptions.module }); + } + + const resolvedHostRate = + processorOptions.sampleRate ?? readGlobalSampleRate(); + if ( + typeof resolvedHostRate !== "number" || + !Number.isFinite(resolvedHostRate) || + resolvedHostRate <= 0 + ) { + throw new RangeError("sampleRate must be a positive finite number"); + } + + const maxHostFrames = + processorOptions.maxBlockFrames ?? DEFAULT_MAX_BLOCK_FRAMES; + if ( + typeof maxHostFrames !== "number" || + !Number.isInteger(maxHostFrames) || + maxHostFrames < 1 || + maxHostFrames > 0xffffffff + ) { + throw new RangeError( + "maxBlockFrames must be an integer in 1..=4294967295", + ); + } + + this.hostSampleRate = resolvedHostRate; + this.sampleRate = + resolvedHostRate === 44100 || resolvedHostRate === 48000 + ? resolvedHostRate + : INTERNAL_FALLBACK_RATE; + this.maxBlockFrames = maxHostFrames; + this.needsResample = this.hostSampleRate !== this.sampleRate; + this.stepDown = this.hostSampleRate / this.sampleRate; + this.stepUp = this.sampleRate / this.hostSampleRate; + + const maxResampledFrames = this.needsResample + ? Math.ceil((maxHostFrames * this.sampleRate) / this.hostSampleRate) + 2 + : maxHostFrames; + const enginePreparedFrames = Math.max(maxHostFrames, maxResampledFrames); + + this.engine = new Tunelet( + this.sampleRate, + enginePreparedFrames, + processorOptions.config, + ); + + this.pcmInput = new Int16Array(enginePreparedFrames); + this.pcmLeft = new Int16Array(enginePreparedFrames); + this.pcmRight = new Int16Array(enginePreparedFrames); + this.pcmInputViews = createLengthViews( + this.pcmInput, + enginePreparedFrames, + ); + this.pcmLeftViews = createLengthViews(this.pcmLeft, enginePreparedFrames); + this.pcmRightViews = createLengthViews( + this.pcmRight, + enginePreparedFrames, + ); + this.monoScratch = new Float32Array(maxHostFrames); + + if (this.needsResample) { + this.inputHistory = new Float32Array(maxHostFrames + 1); + const queueCapacity = enginePreparedFrames + 16; + this.outQueueL = new Float32Array(queueCapacity); + this.outQueueR = new Float32Array(queueCapacity); + this.queueLength = RESAMPLE_CUSHION_FRAMES; + } else { + this.inputHistory = new Float32Array(0); + this.outQueueL = new Float32Array(0); + this.outQueueR = new Float32Array(0); + } + + if (this.hostSampleRate > this.sampleRate) { + this.useAntiAlias = true; + const omega = (2 * Math.PI * ANTI_ALIAS_CUTOFF_HZ) / this.hostSampleRate; + const cosOmega = Math.cos(omega); + const sinOmega = Math.sin(omega); + const alpha = sinOmega / Math.SQRT2; + const a0 = 1 + alpha; + this.aaB0 = (1 - cosOmega) / (2 * a0); + this.aaB1 = (1 - cosOmega) / a0; + this.aaB2 = this.aaB0; + this.aaA1 = (-2 * cosOmega) / a0; + this.aaA2 = (1 - alpha) / a0; + } else { + this.useAntiAlias = false; + this.aaB0 = 1; + this.aaB1 = 0; + this.aaB2 = 0; + this.aaA1 = 0; + this.aaA2 = 0; + } + + this.applyReporting({ + reportIntervalMs: + processorOptions.reportIntervalMs ?? DEFAULT_REPORT_INTERVAL_MS, + feedback: processorOptions.feedback ?? true, + telemetry: processorOptions.telemetry ?? true, + }); + + this.port.onmessage = (event: MessageEvent) => { + this.handleCommand(event.data); + }; + (this.port as { unref?: () => void }).unref?.(); + } + + /** The nominal processor latency in host frames. */ + get latencyFrames(): number { + if (!this.needsResample) { + return this.engine.latencyFrames; + } + return Math.round( + (this.engine.latencyFrames + RESAMPLE_CUSHION_FRAMES) * this.stepDown, + ); + } + + /** Processes one Web Audio render quantum of `Float32Array` channels. */ + process( + inputs: readonly (readonly Float32Array[])[], + outputs: readonly (readonly Float32Array[])[], + ): boolean { + if (this.disposed) { + return false; + } + + const outputChannels = outputs[0]; + if (!outputChannels || outputChannels.length === 0) { + return true; + } + + const outL = outputChannels[0]; + const totalHostFrames = outL.length; + if (totalHostFrames === 0) { + return true; + } + + const outR = outputChannels.length > 1 ? outputChannels[1] : undefined; + for (let ch = 2; ch < outputChannels.length; ch++) { + outputChannels[ch].fill(0); + } + + const inputChannels = inputs[0]; + let offset = 0; + while (offset < totalHostFrames) { + const chunkFrames = Math.min( + this.maxBlockFrames, + totalHostFrames - offset, + ); + if (this.needsResample) { + this.processResampledChunk( + inputChannels, + outL, + outR, + offset, + chunkFrames, + ); + } else { + this.processDirectChunk( + inputChannels, + outL, + outR, + offset, + chunkFrames, + ); + } + offset += chunkFrames; + } + + this.maybePostReport(totalHostFrames); + return !this.disposed; + } + + /** Processes a chunk at 44.1 kHz or 48 kHz without rate conversion. */ + private processDirectChunk( + inputChannels: readonly Float32Array[] | undefined, + outL: Float32Array, + outR: Float32Array | undefined, + offset: number, + frames: number, + ): void { + const inView = this.pcmInputViews[frames]; + const leftView = this.pcmLeftViews[frames]; + const rightView = this.pcmRightViews[frames]; + + if (this.draining && this.pendingEvents.length === 0) { + const rendered = + outR !== undefined + ? this.engine.drain(leftView, rightView) + : this.engine.drainMono(inView); + if (outR !== undefined) { + writeStereoFloat32(this.pcmLeft, this.pcmRight, outL, outR, offset, frames); + } else { + writeMonoFloat32(this.pcmInput, outL, offset, frames); + } + if (rendered === 0) { + this.draining = false; + this.postMessage({ type: "drainComplete" }); + } + return; + } + + this.draining = false; + this.fillMonoPcm(inputChannels, offset, frames); + + const events = this.consumeEvents(frames, frames, false); + if (outR !== undefined) { + this.runStereoProcess(inView, leftView, rightView, events); + writeStereoFloat32(this.pcmLeft, this.pcmRight, outL, outR, offset, frames); + } else { + this.runMonoProcess(inView, events); + writeMonoFloat32(this.pcmInput, outL, offset, frames); + } + } + + /** Processes a chunk through the block resampler to and from 48 kHz. */ + private processResampledChunk( + inputChannels: readonly Float32Array[] | undefined, + outL: Float32Array, + outR: Float32Array | undefined, + offset: number, + hostFrames: number, + ): void { + if (this.draining && this.pendingEvents.length === 0) { + let engineFrames = 0; + while (this.inputCursor < hostFrames) { + engineFrames += 1; + this.inputCursor += this.stepDown; + } + this.inputCursor -= hostFrames; + + let rendered = 0; + if (engineFrames > 0) { + rendered = + outR !== undefined + ? this.engine.drain( + this.pcmLeftViews[engineFrames], + this.pcmRightViews[engineFrames], + ) + : this.engine.drainMono(this.pcmInputViews[engineFrames]); + this.appendEngineOutput(engineFrames, outR !== undefined); + } + this.upsampleOutput(outL, outR, offset, hostFrames); + + if (engineFrames > 0 && rendered === 0) { + this.draining = false; + this.postMessage({ type: "drainComplete" }); + } + return; + } + + this.draining = false; + this.fillInputHistory(inputChannels, offset, hostFrames); + + let engineFrames = 0; + while (this.inputCursor < hostFrames) { + const index = this.inputCursor | 0; + const frac = this.inputCursor - index; + const sample = + this.inputHistory[index] + + (this.inputHistory[index + 1] - this.inputHistory[index]) * frac; + this.pcmInput[engineFrames] = floatToInt16(sample); + engineFrames += 1; + this.inputCursor += this.stepDown; + } + this.inputHistory[0] = this.inputHistory[hostFrames]; + this.inputCursor -= hostFrames; + + if (engineFrames > 0) { + const events = this.consumeEvents(hostFrames, engineFrames, true); + const inView = this.pcmInputViews[engineFrames]; + if (outR !== undefined) { + this.runStereoProcess( + inView, + this.pcmLeftViews[engineFrames], + this.pcmRightViews[engineFrames], + events, + ); + } else { + this.runMonoProcess(inView, events); + } + this.appendEngineOutput(engineFrames, outR !== undefined); + } + + this.upsampleOutput(outL, outR, offset, hostFrames); + } + + /** Executes `Tunelet.process` and recovers if queued events are invalid. */ + private runStereoProcess( + inView: Int16Array, + leftView: Int16Array, + rightView: Int16Array, + events: TimedEvent[] | undefined, + ): void { + if (events === undefined) { + this.engine.process(inView, leftView, rightView); + return; + } + try { + this.engine.process(inView, leftView, rightView, events); + } catch (error: unknown) { + this.postError(error); + this.engine.process(inView, leftView, rightView); + } + } + + /** Executes `Tunelet.processMono` and recovers if queued events are invalid. */ + private runMonoProcess( + inView: Int16Array, + events: TimedEvent[] | undefined, + ): void { + if (events === undefined) { + this.engine.processMono(inView); + return; + } + try { + this.engine.processMono(inView, events); + } catch (error: unknown) { + this.postError(error); + this.engine.processMono(inView); + } + } + + /** Converts mono or multi-channel `Float32` input directly into `pcmInput`. */ + private fillMonoPcm( + inputChannels: readonly Float32Array[] | undefined, + offset: number, + frames: number, + ): void { + const channelCount = inputChannels?.length ?? 0; + if (channelCount === 0) { + this.pcmInputViews[frames].fill(0); + return; + } + if (channelCount === 1) { + const ch0 = inputChannels![0]; + const available = Math.max(0, Math.min(frames, ch0.length - offset)); + for (let i = 0; i < available; i++) { + this.pcmInput[i] = floatToInt16(ch0[offset + i]); + } + for (let i = available; i < frames; i++) { + this.pcmInput[i] = 0; + } + return; + } + + this.mixChannelsToScratch(inputChannels!, offset, frames); + for (let i = 0; i < frames; i++) { + this.pcmInput[i] = floatToInt16(this.monoScratch[i]); + } + } + + /** Writes filtered mono host samples into `inputHistory[1..hostFrames]`. */ + private fillInputHistory( + inputChannels: readonly Float32Array[] | undefined, + offset: number, + frames: number, + ): void { + const channelCount = inputChannels?.length ?? 0; + if (channelCount === 0) { + for (let i = 0; i < frames; i++) { + this.inputHistory[i + 1] = this.filterSample(0); + } + return; + } + if (channelCount === 1) { + const ch0 = inputChannels![0]; + const available = Math.max(0, Math.min(frames, ch0.length - offset)); + for (let i = 0; i < available; i++) { + this.inputHistory[i + 1] = this.filterSample(ch0[offset + i]); + } + for (let i = available; i < frames; i++) { + this.inputHistory[i + 1] = this.filterSample(0); + } + return; + } + + this.mixChannelsToScratch(inputChannels!, offset, frames); + for (let i = 0; i < frames; i++) { + this.inputHistory[i + 1] = this.filterSample(this.monoScratch[i]); + } + } + + /** Averages all connected input channels into `monoScratch[0..frames]`. */ + private mixChannelsToScratch( + channels: readonly Float32Array[], + offset: number, + frames: number, + ): void { + const count = channels.length; + const scale = 1 / count; + for (let i = 0; i < frames; i++) { + let sum = 0; + const sampleIndex = offset + i; + for (let ch = 0; ch < count; ch++) { + const channel = channels[ch]; + if (sampleIndex < channel.length) { + sum += channel[sampleIndex] || 0; + } + } + this.monoScratch[i] = sum * scale; + } + } + + /** Applies the anti-alias filter when the host rate is above 48 kHz. */ + private filterSample(raw: number): number { + const x = raw <= -1 ? -1 : raw >= 1 ? 1 : raw || 0; + if (!this.useAntiAlias) { + return x; + } + const y = this.aaB0 * x + this.aaZ1; + this.aaZ1 = this.aaB1 * x - this.aaA1 * y + this.aaZ2; + this.aaZ2 = this.aaB2 * x - this.aaA2 * y; + return y; + } + + /** Appends rendered 48 kHz `Int16` frames to the float output queue. */ + private appendEngineOutput(engineFrames: number, stereo: boolean): void { + let writeIndex = this.queueLength; + if (stereo) { + for (let i = 0; i < engineFrames; i++) { + this.outQueueL[writeIndex] = this.pcmLeft[i] * INV_PCM_SCALE; + this.outQueueR[writeIndex] = this.pcmRight[i] * INV_PCM_SCALE; + writeIndex += 1; + } + } else { + for (let i = 0; i < engineFrames; i++) { + this.outQueueL[writeIndex] = this.pcmInput[i] * INV_PCM_SCALE; + writeIndex += 1; + } + } + this.queueLength = writeIndex; + } + + /** Interpolates `hostFrames` output frames from the 48 kHz output queue. */ + private upsampleOutput( + outL: Float32Array, + outR: Float32Array | undefined, + offset: number, + hostFrames: number, + ): void { + const maxIndex = Math.max(0, this.queueLength - 2); + if (outR !== undefined) { + for (let i = 0; i < hostFrames; i++) { + const rawIndex = this.outputCursor | 0; + const index = rawIndex <= maxIndex ? rawIndex : maxIndex; + const frac = rawIndex <= maxIndex ? this.outputCursor - rawIndex : 1; + outL[offset + i] = + this.outQueueL[index] + + (this.outQueueL[index + 1] - this.outQueueL[index]) * frac; + outR[offset + i] = + this.outQueueR[index] + + (this.outQueueR[index + 1] - this.outQueueR[index]) * frac; + this.outputCursor += this.stepUp; + } + } else { + for (let i = 0; i < hostFrames; i++) { + const rawIndex = this.outputCursor | 0; + const index = rawIndex <= maxIndex ? rawIndex : maxIndex; + const frac = rawIndex <= maxIndex ? this.outputCursor - rawIndex : 1; + outL[offset + i] = + this.outQueueL[index] + + (this.outQueueL[index + 1] - this.outQueueL[index]) * frac; + this.outputCursor += this.stepUp; + } + } + + const maxConsume = Math.max(0, this.queueLength - 2); + const consumed = Math.min(this.outputCursor | 0, maxConsume); + if (consumed > 0) { + const kept = this.queueLength - consumed; + for (let i = 0; i < kept; i++) { + this.outQueueL[i] = this.outQueueL[consumed + i]; + } + if (outR !== undefined) { + for (let i = 0; i < kept; i++) { + this.outQueueR[i] = this.outQueueR[consumed + i]; + } + } + this.queueLength = kept; + this.outputCursor -= consumed; + } + } + + /** Consumes queued `TimedEvent` items for one processed engine block. */ + private consumeEvents( + hostFrames: number, + engineFrames: number, + scaleOffsets: boolean, + ): TimedEvent[] | undefined { + if (this.pendingEvents.length === 0) { + return undefined; + } + const batch = this.pendingEvents; + this.pendingEvents = []; + if (scaleOffsets) { + for (let i = 0; i < batch.length; i++) { + const current = batch[i]; + if (current.offset >= 0 && current.offset < hostFrames) { + current.offset = Math.min( + engineFrames - 1, + Math.floor((current.offset * engineFrames) / hostFrames), + ); + } else if (current.offset >= hostFrames) { + current.offset = engineFrames; + } + } + } + return batch; + } + + /** Posts throttled `Feedback` and `Telemetry` snapshots at the UI interval. */ + private maybePostReport(processedHostFrames: number): void { + if ( + this.reportIntervalFrames <= 0 || + (!this.feedbackEnabled && !this.telemetryEnabled) + ) { + return; + } + + this.framesSinceReport += processedHostFrames; + if (this.framesSinceReport < this.reportIntervalFrames) { + return; + } + this.framesSinceReport %= this.reportIntervalFrames; + + const feedback: Feedback | undefined = this.feedbackEnabled + ? this.engine.takeFeedback() + : undefined; + const telemetry: Telemetry | undefined = this.telemetryEnabled + ? this.engine.takeTelemetry() + : undefined; + this.postMessage({ type: "report", feedback, telemetry }); + } + + /** Handles control messages from `TuneletWorkletNode`. */ + private handleCommand(command: TuneletWorkletCommand | undefined): void { + if (!command || this.disposed) { + return; + } + + try { + switch (command.type) { + case "setConfig": + this.draining = false; + this.engine.setConfig(command.config); + break; + case "events": + this.enqueueEvents(command.events); + break; + case "reset": + this.resetProcessorState(); + break; + case "beginDrain": { + const tailFrames = this.engine.beginDrain(); + this.draining = tailFrames > 0; + this.postMessage({ type: "drainStarted", tailFrames }); + if (!this.draining) { + this.postMessage({ type: "drainComplete" }); + } + break; + } + case "setReporting": + this.applyReporting(command); + break; + case "dispose": + this.disposeProcessor(); + break; + } + } catch (error: unknown) { + this.postError(error); + } + } + + /** Appends new `TimedEvent` items in ascending offset order. */ + private enqueueEvents(events: readonly TimedEvent[]): void { + if (!Array.isArray(events) || events.length === 0) { + return; + } + let needsSort = false; + let lastOffset = + this.pendingEvents.length > 0 + ? this.pendingEvents[this.pendingEvents.length - 1].offset + : 0; + for (let i = 0; i < events.length; i++) { + const item = events[i]; + if (item.offset < lastOffset) { + needsSort = true; + } + lastOffset = item.offset; + this.pendingEvents.push({ offset: item.offset, event: item.event }); + } + if (needsSort) { + this.pendingEvents.sort((a, b) => a.offset - b.offset); + } + } + + /** Clears the resampler histories, event queue and native processor state. */ + private resetProcessorState(): void { + this.pendingEvents.length = 0; + this.draining = false; + this.aaZ1 = 0; + this.aaZ2 = 0; + this.inputCursor = 0; + this.outputCursor = 0; + if (this.needsResample) { + this.inputHistory.fill(0); + this.outQueueL.fill(0); + this.outQueueR.fill(0); + this.queueLength = RESAMPLE_CUSHION_FRAMES; + } + this.engine.reset(); + } + + /** Updates the throttled UI report cadence and active report fields. */ + private applyReporting(options: TuneletReportingOptions): void { + if (options.feedback !== undefined) { + this.feedbackEnabled = Boolean(options.feedback); + } + if (options.telemetry !== undefined) { + this.telemetryEnabled = Boolean(options.telemetry); + } + if (options.reportIntervalMs !== undefined) { + const intervalMs = options.reportIntervalMs; + if (!Number.isFinite(intervalMs) || intervalMs < 0) { + throw new RangeError( + "reportIntervalMs must be zero or a positive finite number", + ); + } + if (intervalMs === 0) { + this.reportIntervalFrames = 0; + this.framesSinceReport = 0; + } else { + this.reportIntervalFrames = Math.max( + 1, + Math.round((intervalMs / 1000) * this.hostSampleRate), + ); + if (this.framesSinceReport >= this.reportIntervalFrames) { + this.framesSinceReport = 0; + } + } + } + } + + /** Releases the Wasm `Tunelet` memory and marks the worklet as complete. */ + private disposeProcessor(): void { + if (this.disposed) { + return; + } + this.disposed = true; + this.pendingEvents.length = 0; + this.port.onmessage = null; + this.engine.free(); + } + + /** Sends a typed message to the main thread port. */ + private postMessage(message: TuneletWorkletMessage): void { + this.port.postMessage(message); + } + + /** Reports an error message on the port and keeps audio output active. */ + private postError(error: unknown): void { + const message = error instanceof Error ? error.message : String(error); + this.postMessage({ type: "error", message }); + } +} + +/** Pre-allocates `Int16Array` prefix views for lengths `0..=maxFrames`. */ +function createLengthViews( + buffer: Int16Array, + maxFrames: number, +): Int16Array[] { + const views = new Array(maxFrames + 1); + for (let length = 0; length <= maxFrames; length++) { + views[length] = buffer.subarray(0, length); + } + return views; +} + +/** Clamps one `Float32` sample to `-1..=1` and quantizes it to `i16`. */ +function floatToInt16(sample: number): number { + const clamped = sample <= -1 ? -1 : sample >= 1 ? 1 : sample || 0; + return clamped < 0 ? Math.round(clamped * 32768) : Math.round(clamped * 32767); +} + +/** Converts stereo `Int16` buffers to `Float32` output slices. */ +function writeStereoFloat32( + pcmL: Int16Array, + pcmR: Int16Array, + outL: Float32Array, + outR: Float32Array, + offset: number, + frames: number, +): void { + for (let i = 0; i < frames; i++) { + outL[offset + i] = pcmL[i] * INV_PCM_SCALE; + outR[offset + i] = pcmR[i] * INV_PCM_SCALE; + } +} + +/** Converts a mono `Int16` buffer to a `Float32` output slice. */ +function writeMonoFloat32( + pcm: Int16Array, + out: Float32Array, + offset: number, + frames: number, +): void { + for (let i = 0; i < frames; i++) { + out[offset + i] = pcm[i] * INV_PCM_SCALE; + } +} + +/** Reads the `sampleRate` global from `AudioWorkletGlobalScope` if present. */ +function readGlobalSampleRate(): number | undefined { + const candidate = (globalThis as { sampleRate?: unknown }).sampleRate; + return typeof candidate === "number" ? candidate : undefined; +} + +if ( + typeof (globalThis as { registerProcessor?: unknown }).registerProcessor === + "function" +) { + ( + globalThis as unknown as { + registerProcessor: ( + name: string, + processorCtor: typeof TuneletWorkletProcessor, + ) => void; + } + ).registerProcessor(TUNELET_WORKLET_PROCESSOR_NAME, TuneletWorkletProcessor); +} diff --git a/tsconfig.json b/tsconfig.json index 27aa560..162ac6b 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -11,5 +11,5 @@ "rootDir": "src", "outDir": "dist" }, - "include": ["src/index.ts"] + "include": ["src/index.ts", "src/worklet.ts"] }