# Deployment: where the sound runs

## Contents
1. Choosing a mode
2. Baked assets
3. Kernels (AudioWorklet and offline)
4. Native Web Audio graph: tract, spatial, mixer
5. Rendering Web Audio on a server
6. Web Audio practices and traps
7. Handing sounds to game engines

## 1. Choosing a mode

| Question | If yes |
|---|---|
| Linear media, or an engine with its own audio pipeline? | **Bake** WAVs (plus variations) |
| Must the sound follow a continuously changing value (speed, force, intensity, RPM)? | **Kernel** |
| Must it never repeat over long sessions with tiny download size? | **Kernel** |
| Is it a heavy designed one-shot (cinematic hit, speech line, shatter)? | **Bake**, then place it with the graph |
| Does it need 3D position, HRTF, rooms, user-controlled mix in a page? | **Graph** around baked/kernel sources |
| Must CI or a build step produce/verify the audio without a browser? | offline render (kernel path, or the graph on the server emulation) |

Costs: baked = download size and repetition; kernel = CPU on the audio thread (budget ~10–20 % of one core in
total; one kernel is typically < 2 %) and a worklet module to load; graph = native and cheap except convolvers
and HRTF panners (a few dozen of each at most).

Hybrid is the norm: bake what is expensive and fixed, keep one or two responsive layers live, do placement and
space in the graph. Example — a vehicle: baked ignition and door one-shots, `Engine` kernel with `rpm`/`load`
from the simulation, `SpatialSource` for position and Doppler, zone reverb from the `AmbienceMixer`.

## 2. Baked assets

```js
import * as sd from '<skill>/lib/node.js';
const buf = sd.master(sd.impact({ character: 'metal', weight: 0.8, seed: 4 }), { target: -16 });
sd.save('out/hit_metal_01.wav', buf, { bitDepth: 16, lens: 'impact', meta: { gen: 'impact', seed: 4 } });
```
- 48 kHz; 24-bit masters, 16-bit (dithered automatically) for shipped assets, 32-float between pipeline stages.
- Compressed delivery needs an external encoder: `ffmpeg -i in.wav -c:a libopus -b:a 96k out.opus` /
  `-c:a libvorbis -q:a 5 out.ogg` / `-c:a aac -b:a 128k out.m4a`. Leave −1 dBTP headroom: lossy codecs overshoot.
  MP3 adds padding that breaks gapless loops — use Ogg/Opus or WAV for loops.
- Variations: 3–8 files per event from different seeds *and* structure; verify with `compare.mjs --variety`.
- Embedding a baked sound in a scene offline: `spatialize(buf, { path, room })`; `renderScene` for whole beds.
- Any kernel bakes with `renderKernel(new K(sr, opts), seconds, { automation, events })`; `automation` is
  `(t, k) => k.set(...)` or `{ param: [[t, v], …] }`.

## 3. Kernels

A kernel is a class with `static params = { name: [default, min, max, description] }`, a constructor
`(sr, opts)`, `set(name, value)` and `process(L, R, n)`. The same instance code runs:

- **offline** — `renderKernel(...)` (bun/node, 25–400× realtime, no dependencies);
- **in the browser** — `const node = await kernelNode(ctx, 'grains', { surface: 'glass', rate: 800 })`, then
  `node.set({ rate: 5000 })`, `node.call('impact', {...})` for kernels with methods (`PhysicsSonifier`),
  `node.kill()`. The host processor is `sd-kernel` in `lib/webaudio/worklet-entry.js`, loaded as an ES-module
  worklet straight from `lib/` (no build). Where module worklets with imports are not possible (some bundlers,
  strict CSP, CDN) use the single-file bundle: `await ctx.audioWorklet.addModule('<url>/dist/sd-worklet.js')`
  before `kernelNode` (rebuild with `bun tools/build-worklet.mjs` after adding kernels).

Writing one:
```js
import { Kernel, register } from '<skill>/lib/core/kernel.js';
export class Geiger extends Kernel {
  static params = { rate: [5, 0, 2000, 'clicks per second'], tone: [2500, 200, 8000, 'click pitch Hz'], gain: [1, 0, 4, ''] };
  constructor(sr, opts) { super(sr, opts); this.a = 0; this.ph = 0; }
  process(L, R, n) {
    this.smooth(n);                                   // glide params toward their targets
    const p = this.p, r = this.rng, k = Math.exp(-1 / (this.sr * 0.004));
    for (let i = 0; i < n; i++) {
      if (r.next() < p.rate / this.sr) this.a = r.range(0.5, 1);
      this.ph += 2 * Math.PI * p.tone / this.sr; const y = Math.sin(this.ph) * this.a * p.gain; this.a *= k;
      L[i] = y; R[i] = y;
    }
  }
}
register('geiger', Geiger);
```
Rules of the audio thread: no allocation in `process` (create arrays in the constructor), no `Math.random`
(use `this.rng` — reproducible), no I/O, guard recursive filters against NaN, smooth every parameter that a
user can move (`this.smooth`), keep per-sample work proportional to voices you control.
A page UI can be generated from `Class.params` (see `templates/browser/index.html`): that table is the contract
between sound designer and integrator.

## 4. Native Web Audio graph

`lib/webaudio/index.js` (works with any `BaseAudioContext`):

- `tract(ctx, spec)` → `{ input, output, nodes }` — effects chain from data:
  `[['hp', 80], ['peak', 3000, 4, 1.2], ['drive', 9, 'tanh'], ['echo', { time: .25, feedback: .4, mix: .3 }], ['chorus', {}], ['reverb', { space: 'hall', wetDb: -10 }], ['comp', { threshold: -18, ratio: 4 }], ['limiter', -1], ['pan', -.3]]`.
  Nodes are exposed for automation (`nodes[1].frequency.setTargetAtTime(...)`). The pure-JS twins for offline use
  are in `lib/core/fx.js` and `reverb.js` (`eq`, `drive`, `echo`, `chorus`, `reverb`, `compress`, `limit`).
- `SpatialSource(ctx, { panningModel: 'HRTF', refDistance, rolloff, doppler, air })` — `input` → delay
  (propagation; moving it *is* the Doppler shift) → air low-pass → `PannerNode`. `moveTo([x, y, z], when)` from
  a game loop, or `follow(path, t0, t1)` to schedule a trajectory.
- `AmbienceMixer` — zones, layers, emitters (see `ambience.md` §6).
- `toAudioBuffer(ctx, buf)` / `fromAudioBuffer(ab)` bridge to the library's `{ sr, ch }` buffers;
  `renderOffline(seconds, build)` renders any graph to a buffer (browser or server).
- Reverb IRs come from `synthIR` (no IR files to ship); any recorded IR can be used instead.

## 5. Rendering Web Audio on a server

| Option | Notes |
|---|---|
| **Kernel path** (`renderKernel`, `spatialize`, `renderScene`, `lib/core/fx`) | no Web Audio at all; fastest; deterministic. Default for producing assets |
| **`web-audio-api`** (npm, pure JS, WPT-tested) | `bun add web-audio-api` in the skill folder (already an optional dependency). `renderOffline()` picks it up automatically. Full node set incl. `AudioWorklet`, HRTF panner, convolver. Speed: simple graphs ≫ realtime, convolver/HRTF-heavy graphs ≈ 0.5–2× realtime. Use it to render and *test the exact graph a page will run* |
| **`node-web-audio-api`** (npm, Rust bindings) | faster DSP; needs system audio libraries on Linux (e.g. `libpipewire-0.3`), works out of the box on macOS/Windows; Node only. `webAudio()` falls back to it if installed |
| **Headless Chromium** (Playwright/Puppeteer: run `OfflineAudioContext` in the page, return the samples) | bit-exact browser behaviour; heavy to install. Only when the browser's own implementation is what is under test |

Gotcha: on the server an `AudioWorkletNode`'s open `MessagePort` keeps the process alive; `renderOffline` closes
kernel ports for you — if you build contexts by hand, call `node.port.close()` or `process.exit()` when done.
Emulations differ slightly from browsers in compressor curves and HRTF data: assert on measurements with
tolerances (`compare.mjs`), not on sample equality.

## 6. Web Audio practices and traps

- **One `AudioContext`**, created or resumed inside a user gesture (`await ctx.resume()` in a click handler).
- **Schedule on the audio clock**: `param.setValueAtTime / linearRampToValueAtTime / setTargetAtTime(v, t, tau)`;
  never `param.value = x` in a loop for audible moves (zipper noise). `setTargetAtTime` is the safe default for
  live control; cancel with `cancelScheduledValues` + `setValueAtTime(param.value, now)` before re-ramping.
- `exponentialRampToValueAtTime` cannot reach or cross 0 — ramp to 0.0001 and then set 0.
- **Clicks** = discontinuities: fade in/out over ≥ 3 ms; start/stop sources at zero or under a gain ramp.
- `AudioBufferSourceNode` is one-shot: create a new one per play; share the `AudioBuffer`.
- **Doppler** was removed from `PannerNode`; implement it with a `DelayNode` (as `SpatialSource` does).
- `PannerNode` `'HRTF'` is costly — use it for a handful of important sources, `'equalpower'` for the rest;
  HRTF is for headphones, and mono sources (it down-mixes stereo input).
- `ConvolverNode.normalize = false` when IRs are already energy-normalized (`synthIR` output is).
- `DynamicsCompressorNode` is not a brick-wall limiter and adds ~6 ms look-ahead latency; leave headroom.
- `WaveShaperNode.oversample = '4x'` for audible distortion; naive `OscillatorNode`s are band-limited, hand-made
  wavetables via `createPeriodicWave`.
- **Worklet**: 128-frame blocks; no allocation or logging inside `process`; parameters via `AudioParam`s or
  `port` messages (this skill's kernels use the port: `{ set: {...} }`).
- Tab backgrounding throttles timers, not the audio clock: schedule ahead (100–200 ms look-ahead window).
- iOS/Safari: context sample rate may be 44.1 or 48 kHz — do not hard-code; unlock on first touch; silent switch
  mutes Web Audio.
- Free what you stop: `disconnect()` nodes and `kill()` kernels; a connected silent node still costs CPU.

## 7. Handing sounds to game engines

- **Unity / Unreal / Godot / FMOD / Wwise**: deliver baked WAVs + a table of variations and intended runtime
  randomization (pitch ± semitones, volume ± dB, no-repeat), loop points (whole-file loops verified by
  `loopcheck`), loudness per category, and 3D settings (min/max distance ≈ `refDistance`/audible range).
  Reverb zones and snapshots map directly onto this skill's zone objects (level + low-pass per bus + room).
- **Parameter-driven sounds in native engines**: either bake a parameter grid (e.g. engine at 8 RPM steps,
  crossfaded by the engine's blend container / RTPC), or port the kernel — kernels are plain arithmetic on
  arrays and translate line-for-line to C#/C++/GDScript DSP callbacks (`OnAudioFilterRead`, `AudioStreamGenerator`,
  Unreal SourceEffect/MetaSounds custom nodes, Wwise/FMOD plug-ins).
- **Web engines** (Three.js, Babylon, Phaser, PlayCanvas): they expose their `AudioContext` — connect this
  skill's nodes to it (`THREE.AudioListener.context`, `Phaser.Sound.WebAudioSoundManager.context`) and feed
  listener position/orientation to `ctx.listener`.
- Ship the *recipe* too: generator name, parameters, seed (`meta` JSON). Regenerating beats editing.
