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

Filter by extension

Filter by extension


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

Expand All @@ -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
Expand Down
112 changes: 89 additions & 23 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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
Expand All @@ -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.
Expand All @@ -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` |
Expand All @@ -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

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

Expand Down
13 changes: 12 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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 })\"",
Expand Down
61 changes: 57 additions & 4 deletions scripts/verify-pack.mjs
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -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",
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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);",
"",
Expand All @@ -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"),
);

Expand All @@ -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,
Expand All @@ -200,16 +233,26 @@ 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,",
" type InitOutput,",
`} from ${wasmLiteral};`,
"",
"export async function verifyTypes(source?: InitInput): Promise<void> {",
" const wasmBytes = await loadTuneletWasm(source);",
" const exportsFromRoot: InitOutput = await loadTunelet(source);",
" const exportsFromNamed: InitOutput = await namedLoadTunelet(source);",
" const exportsFromWasm: InitOutput = await init(source);",
Expand All @@ -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;",
Expand Down
Loading