// AudioWorklet that plays audio rendered elsewhere (render workers), on the audio clock. // Chunks carry absolute frame numbers; the player outputs whatever covers the current frames // (silence if nothing has arrived: an underrun) and reports how far it has played, so the // renderer can stay a fixed distance ahead. import type { Chunk, Consumed } from "./protocol.ts"; declare const currentFrame: number; declare const sampleRate: number; declare class AudioWorkletProcessor { readonly port: MessagePort; constructor(); } declare function registerProcessor(name: string, ctor: new () => AudioWorkletProcessor): void; class PcmPlayer extends AudioWorkletProcessor { private queue: Chunk[] = []; private src: MessagePort | null = null; private underruns = 0; private started = false; private lastReport = 0; constructor() { super(); this.port.onmessage = (e: MessageEvent<{ type: "port"; port: MessagePort }>) => { if (e.data?.type !== "port") return; this.src = e.data.port; this.src.onmessage = (ev: MessageEvent) => this.queue.push(ev.data); }; } process(_in: Float32Array[][], outputs: Float32Array[][]): boolean { const out = outputs[0]; const L = out[0], R = out[1] ?? out[0]; const n = L.length; const F = currentFrame; const q = this.queue; while (q.length && q[0].frame + q[0].L.length <= F) q.shift(); let i = 0; while (i < n) { const f = F + i; const c = q.find((x) => x.frame <= f && f < x.frame + x.L.length); if (!c) { // nothing for this frame: silence (counts as an underrun once audio has started) const next = q.find((x) => x.frame > f); const end = next ? Math.min(n, next.frame - F) : n; if (this.started) this.underruns++; i = Math.max(end, i + 1); continue; } this.started = true; const off = f - c.frame; const len = Math.min(n - i, c.L.length - off); L.set(c.L.subarray(off, off + len), i); if (R !== L) R.set(c.R.subarray(off, off + len), i); i += len; } if (this.src && F + n - this.lastReport >= sampleRate / 50) { this.lastReport = F + n; const m: Consumed = { consumed: F + n, underruns: this.underruns }; this.src.postMessage(m); } return true; } } registerProcessor("pcm-player", PcmPlayer);