// AudioWorklet that plays a performance: audio rendered ahead by workers ("stems"), mixed onto // outputs (each output feeds its own effects on the page). It owns the piece's clock: the playhead // advances only while every stem has audio for it. When any stem runs short, everything pauses // (sound fades, the page's picture freezes at the playhead) until all stems are buffered `resume` // seconds ahead. It measures how fast the stems are being rendered: on a device that renders // slower than real time, a pause waits long enough to play through to the end (like a video's // "can play through"); otherwise each pause doubles `resume`, so waits get fewer and longer. import { BLOCK, type Clock, type PlayerOptions, type PlayerStatus, type ToPlayer } from "./protocol.ts"; declare const currentFrame: number; declare const sampleRate: number; declare class AudioWorkletProcessor { readonly port: MessagePort; constructor(options?: { processorOptions?: unknown }); } declare function registerProcessor(name: string, ctor: new (options: { processorOptions?: unknown }) => AudioWorkletProcessor): void; const RESUME_START = 1.0; // s buffered before playing at first const RESUME_MAX = 32; // s const AHEAD_MIN = 12; // s producers keep rendered ahead, at least (a deep buffer absorbs dense passages) const FADE_IN = 512; // samples const TAIL = 0.985; // per-sample decay of the last sample when sound stops for buffering const REPORT_EVERY = 6; // blocks between status reports (~16 ms) const RATE_EVERY = 12; // blocks between render-rate samples const RATE_WINDOW = 2; // s of render-rate samples kept const RATE_MIN = 1; // s of uncapped samples needed before the rate counts interface Chunk { frame: number; L: Float32Array; R: Float32Array; } class StreamPlayer extends AudioWorkletProcessor { private o: PlayerOptions; private queues: Chunk[][]; private avail: number[]; // per stem: frame up to which audio has arrived (contiguous) private doneAt: number[]; // per stem: silent from this frame on private ports: MessagePort[] = []; private playhead: number; private endFrame = Infinity; private state: PlayerStatus["state"] = "buffering"; private resume = RESUME_START; private rebuffers = 0; private fadeIn = 0; private tail: number[][]; // per output: [L, R] last samples, decaying while paused private blocks = 0; // render-rate samples: [audio-clock frame, least rendered frame of the stems], while not capped private rateLog: [number, number][] = []; constructor(options: { processorOptions?: unknown }) { super(options); this.o = options.processorOptions as PlayerOptions; this.queues = Array.from({ length: this.o.stems }, () => []); this.avail = Array(this.o.stems).fill(this.o.startFrame); this.doneAt = Array(this.o.stems).fill(Infinity); this.playhead = this.o.startFrame; this.tail = Array.from({ length: this.o.outputs }, () => [0, 0]); this.port.onmessage = (e: MessageEvent<{ type: "ports"; ports: MessagePort[] }>) => { if (e.data?.type !== "ports") return; for (const p of e.data.ports) { this.ports.push(p); p.onmessage = (ev: MessageEvent) => this.receive(ev.data); } this.clock(); }; } private receive(m: ToPlayer) { if (m.type === "chunk") { const q = this.queues[m.stem]; if (!q) return; q.push({ frame: m.frame, L: m.L, R: m.R }); this.avail[m.stem] = Math.max(this.avail[m.stem], m.frame + m.L.length); } else if (m.type === "done") this.doneAt[m.stem] = Math.min(this.doneAt[m.stem], m.frame); else if (m.type === "end") this.endFrame = m.frame; } /** Is every stem ready up to frame `to` (from the playhead)? */ private readyTo(to: number): boolean { for (let s = 0; s < this.o.stems; s++) { const need = Math.min(to, this.doneAt[s], this.endFrame); if (this.avail[s] < need) return false; } return true; } /** Least rendered frame over the stems still sounding (Infinity if none). */ private least(): number { let a = Infinity; for (let s = 0; s < this.o.stems; s++) if (this.doneAt[s] > this.playhead) a = Math.min(a, this.avail[s]); return a; } /** Render speed (s of audio per s), from recent samples; null until measured. */ private rate(): number | null { const log = this.rateLog; if (log.length < 2) return null; const [f0, a0] = log[0], [f1, a1] = log[log.length - 1]; if (f1 - f0 < RATE_MIN * sampleRate) return null; return (a1 - a0) / (f1 - f0); } /** Frames producers should keep rendered ahead: comfortably more than any buffering target. */ private aheadFrames(): number { return Math.round(Math.max(AHEAD_MIN, 2 * this.resume, this.target() + 2) * sampleRate); } private measure() { const least = this.least(); const ahead = this.aheadFrames(); // only while the producers are working flat out (not waiting at their buffer limit) if (!Number.isFinite(least) || least - this.playhead > 0.8 * ahead) { this.rateLog = []; return; } this.rateLog.push([currentFrame, least]); while (this.rateLog.length > 2 && currentFrame - this.rateLog[0][0] > RATE_WINDOW * sampleRate) this.rateLog.shift(); } /** Seconds to buffer before resuming: `resume`, or enough to play through if rendering is slow. */ private target(): number { const r = this.rate(); if (r === null || r >= 1) return this.resume; const end = Number.isFinite(this.endFrame) ? this.endFrame : this.o.estimatedEnd; const through = ((end - this.playhead) / sampleRate) * (1 - r) * 1.15 + 0.5; return Math.min(RESUME_MAX, Math.max(this.resume, through)); } private fill(): number { const target = Math.min(this.playhead + this.target() * sampleRate, this.endFrame); if (target <= this.playhead) return 1; let f = 1; for (let s = 0; s < this.o.stems; s++) { const need = Math.min(target, this.doneAt[s]); if (need <= this.playhead) continue; f = Math.min(f, Math.max(0, (this.avail[s] - this.playhead) / (need - this.playhead))); } return f; } private ahead(): number { let a = Infinity; for (let s = 0; s < this.o.stems; s++) if (this.doneAt[s] > this.playhead) a = Math.min(a, this.avail[s] - this.playhead); return a === Infinity ? 0 : a / sampleRate; } private clock() { const ahead = this.aheadFrames(); const m: Clock = { type: "clock", playhead: this.playhead, ahead }; for (const p of this.ports) p.postMessage(m); } private report() { const m: PlayerStatus = { type: "status", state: this.state, playhead: this.playhead, at: currentFrame, fill: this.state === "buffering" ? this.fill() : 1, rebuffers: this.rebuffers, ahead: this.ahead(), }; this.port.postMessage(m); } process(_in: Float32Array[][], outputs: Float32Array[][]): boolean { const n = BLOCK; if (this.state === "playing" && this.playhead >= this.endFrame) this.state = "ended"; if (this.blocks % RATE_EVERY === 0) this.measure(); if (this.state === "buffering") { const target = Math.min(this.playhead + Math.round(this.target() * sampleRate), this.endFrame); if (this.readyTo(target)) { this.state = "playing"; this.fadeIn = 0; } } if (this.state === "playing" && !this.readyTo(this.playhead + n)) { // a stem ran short: pause everything until it's buffered further ahead this.state = "buffering"; this.rebuffers++; this.resume = Math.min(RESUME_MAX, this.resume * 2); } if (this.state !== "playing") { for (let o = 0; o < outputs.length; o++) { const L = outputs[o][0], R = outputs[o][1] ?? L, tl = this.tail[o]; for (let i = 0; i < n; i++) { tl[0] *= TAIL; tl[1] *= TAIL; L[i] = tl[0]; if (R !== L) R[i] = tl[1]; } } } else { const p = this.playhead; for (let s = 0; s < this.o.stems; s++) { const q = this.queues[s]; while (q.length && q[0].frame + q[0].L.length <= p) q.shift(); if (p >= this.doneAt[s]) continue; const out = outputs[this.o.route[s]]; if (!out) continue; const L = out[0], R = out[1] ?? L; let i = 0; for (const c of q) { if (i >= n) break; const f = p + i; if (c.frame + c.L.length <= f) continue; if (c.frame > f) break; // gap (can't happen: producers send in order) const off = f - c.frame, len = Math.min(n - i, c.L.length - off); for (let j = 0; j < len; j++) { L[i + j] += c.L[off + j]; if (R !== L) R[i + j] += c.R[off + j]; } i += len; } } // fade in after a pause; remember the last samples in case the next block pauses for (let o = 0; o < outputs.length; o++) { const L = outputs[o][0], R = outputs[o][1] ?? L; if (this.fadeIn < FADE_IN) { for (let i = 0; i < n; i++) { const g = Math.min(1, (this.fadeIn + i) / FADE_IN); L[i] *= g; if (R !== L) R[i] *= g; } } this.tail[o][0] = L[n - 1]; this.tail[o][1] = R[n - 1]; } this.fadeIn += n; this.playhead += n; } if (++this.blocks % REPORT_EVERY === 0) { this.report(); this.clock(); } return true; } } registerProcessor("stream-player", StreamPlayer);