216afddorbits: render instruments ahead in Web WorkersJeremy Magland 1// AudioWorklet that plays audio rendered elsewhere (render workers), on the audio clock.
2// Chunks carry absolute frame numbers; the player outputs whatever covers the current frames
3// (silence if nothing has arrived: an underrun) and reports how far it has played, so the
4// renderer can stay a fixed distance ahead.
6import type { Chunk, Consumed } from "./protocol.ts";
8declare const currentFrame: number;
9declare const sampleRate: number;
10declare class AudioWorkletProcessor {
11 readonly port: MessagePort;
12 constructor();
13}
14declare function registerProcessor(name: string, ctor: new () => AudioWorkletProcessor): void;
16class PcmPlayer extends AudioWorkletProcessor {
17 private queue: Chunk[] = [];
18 private src: MessagePort | null = null;
19 private underruns = 0;
20 private started = false;
21 private lastReport = 0;
23 constructor() {
24 super();
25 this.port.onmessage = (e: MessageEvent<{ type: "port"; port: MessagePort }>) => {
26 if (e.data?.type !== "port") return;
27 this.src = e.data.port;
28 this.src.onmessage = (ev: MessageEvent<Chunk>) => this.queue.push(ev.data);
29 };
30 }
32 process(_in: Float32Array[][], outputs: Float32Array[][]): boolean {
33 const out = outputs[0];
34 const L = out[0], R = out[1] ?? out[0];
35 const n = L.length;
36 const F = currentFrame;
37 const q = this.queue;
38 while (q.length && q[0].frame + q[0].L.length <= F) q.shift();
39 let i = 0;
40 while (i < n) {
41 const f = F + i;
42 const c = q.find((x) => x.frame <= f && f < x.frame + x.L.length);
43 if (!c) {
44 // nothing for this frame: silence (counts as an underrun once audio has started)
45 const next = q.find((x) => x.frame > f);
46 const end = next ? Math.min(n, next.frame - F) : n;
47 if (this.started) this.underruns++;
48 i = Math.max(end, i + 1);
49 continue;
50 }
51 this.started = true;
52 const off = f - c.frame;
53 const len = Math.min(n - i, c.L.length - off);
54 L.set(c.L.subarray(off, off + len), i);
55 if (R !== L) R.set(c.R.subarray(off, off + len), i);
56 i += len;
57 }
58 if (this.src && F + n - this.lastReport >= sampleRate / 50) {
59 this.lastReport = F + n;
60 const m: Consumed = { consumed: F + n, underruns: this.underruns };
61 this.src.postMessage(m);
62 }
63 return true;
64 }
65}
67registerProcessor("pcm-player", PcmPlayer);