1// AudioWorklet that plays a performance: audio rendered ahead by workers ("stems"), mixed onto
2// outputs (each output feeds its own effects on the page). It owns the piece's clock: the playhead
3// advances only while every stem has audio for it. When any stem runs short, everything pauses
4// (sound fades, the page's picture freezes at the playhead) until all stems are buffered `resume`
5// seconds ahead. It measures how fast the stems are being rendered: on a device that renders
6// slower than real time, a pause waits long enough to play through to the end (like a video's
7// "can play through"); otherwise each pause doubles `resume`, so waits get fewer and longer.
9import { BLOCK, type Clock, type PlayerOptions, type PlayerStatus, type ToPlayer } from "./protocol.ts";
11declare const currentFrame: number;
12declare const sampleRate: number;
13declare class AudioWorkletProcessor {
14 readonly port: MessagePort;
15 constructor(options?: { processorOptions?: unknown });
16}
17declare function registerProcessor(name: string, ctor: new (options: { processorOptions?: unknown }) => AudioWorkletProcessor): void;
19const RESUME_START = 1.0; // s buffered before playing at first
20const RESUME_MAX = 32; // s
21const AHEAD_MIN = 4; // s producers keep rendered ahead, at least
22const FADE_IN = 512; // samples
23const TAIL = 0.985; // per-sample decay of the last sample when sound stops for buffering
24const REPORT_EVERY = 6; // blocks between status reports (~16 ms)
25const RATE_EVERY = 12; // blocks between render-rate samples
26const RATE_WINDOW = 2; // s of render-rate samples kept
27const RATE_MIN = 1; // s of uncapped samples needed before the rate counts
29interface Chunk {
30 frame: number;
31 L: Float32Array;
32 R: Float32Array;
33}
35class StreamPlayer extends AudioWorkletProcessor {
36 private o: PlayerOptions;
37 private queues: Chunk[][];
38 private avail: number[]; // per stem: frame up to which audio has arrived (contiguous)
39 private doneAt: number[]; // per stem: silent from this frame on
40 private ports: MessagePort[] = [];
41 private playhead: number;
42 private endFrame = Infinity;
43 private state: PlayerStatus["state"] = "buffering";
44 private resume = RESUME_START;
45 private rebuffers = 0;
46 private fadeIn = 0;
47 private tail: number[][]; // per output: [L, R] last samples, decaying while paused
48 private blocks = 0;
49 // render-rate samples: [audio-clock frame, least rendered frame of the stems], while not capped
50 private rateLog: [number, number][] = [];
52 constructor(options: { processorOptions?: unknown }) {
53 super(options);
54 this.o = options.processorOptions as PlayerOptions;
55 this.queues = Array.from({ length: this.o.stems }, () => []);
56 this.avail = Array(this.o.stems).fill(this.o.startFrame);
57 this.doneAt = Array(this.o.stems).fill(Infinity);
58 this.playhead = this.o.startFrame;
59 this.tail = Array.from({ length: this.o.outputs }, () => [0, 0]);
60 this.port.onmessage = (e: MessageEvent<{ type: "ports"; ports: MessagePort[] }>) => {
61 if (e.data?.type !== "ports") return;
62 for (const p of e.data.ports) {
63 this.ports.push(p);
64 p.onmessage = (ev: MessageEvent<ToPlayer>) => this.receive(ev.data);
65 }
66 this.clock();
67 };
68 }
70 private receive(m: ToPlayer) {
71 if (m.type === "chunk") {
72 const q = this.queues[m.stem];
73 if (!q) return;
74 q.push({ frame: m.frame, L: m.L, R: m.R });
75 this.avail[m.stem] = Math.max(this.avail[m.stem], m.frame + m.L.length);
76 } else if (m.type === "done") this.doneAt[m.stem] = Math.min(this.doneAt[m.stem], m.frame);
77 else if (m.type === "end") this.endFrame = m.frame;
78 }
80 /** Is every stem ready up to frame `to` (from the playhead)? */
81 private readyTo(to: number): boolean {
82 for (let s = 0; s < this.o.stems; s++) {
83 const need = Math.min(to, this.doneAt[s], this.endFrame);
84 if (this.avail[s] < need) return false;
85 }
86 return true;
87 }
89 /** Least rendered frame over the stems still sounding (Infinity if none). */
90 private least(): number {
91 let a = Infinity;
92 for (let s = 0; s < this.o.stems; s++) if (this.doneAt[s] > this.playhead) a = Math.min(a, this.avail[s]);
93 return a;
94 }
96 /** Render speed (s of audio per s), from recent samples; null until measured. */
97 private rate(): number | null {
98 const log = this.rateLog;
99 if (log.length < 2) return null;
100 const [f0, a0] = log[0], [f1, a1] = log[log.length - 1];
101 if (f1 - f0 < RATE_MIN * sampleRate) return null;
102 return (a1 - a0) / (f1 - f0);
103 }
105 /** Frames producers should keep rendered ahead: comfortably more than any buffering target. */
106 private aheadFrames(): number {
107 return Math.round(Math.max(AHEAD_MIN, 2 * this.resume, this.target() + 2) * sampleRate);
108 }
110 private measure() {
111 const least = this.least();
112 const ahead = this.aheadFrames();
113 // only while the producers are working flat out (not waiting at their buffer limit)
114 if (!Number.isFinite(least) || least - this.playhead > 0.8 * ahead) {
115 this.rateLog = [];
116 return;
117 }
118 this.rateLog.push([currentFrame, least]);
119 while (this.rateLog.length > 2 && currentFrame - this.rateLog[0][0] > RATE_WINDOW * sampleRate) this.rateLog.shift();
120 }
122 /** Seconds to buffer before resuming: `resume`, or enough to play through if rendering is slow. */
123 private target(): number {
124 const r = this.rate();
125 if (r === null || r >= 1) return this.resume;
126 const end = Number.isFinite(this.endFrame) ? this.endFrame : this.o.estimatedEnd;
127 const through = ((end - this.playhead) / sampleRate) * (1 - r) * 1.15 + 0.5;
128 return Math.min(RESUME_MAX, Math.max(this.resume, through));
129 }
131 private fill(): number {
132 const target = Math.min(this.playhead + this.target() * sampleRate, this.endFrame);
133 if (target <= this.playhead) return 1;
134 let f = 1;
135 for (let s = 0; s < this.o.stems; s++) {
136 const need = Math.min(target, this.doneAt[s]);
137 if (need <= this.playhead) continue;
138 f = Math.min(f, Math.max(0, (this.avail[s] - this.playhead) / (need - this.playhead)));
139 }
140 return f;
141 }
143 private ahead(): number {
144 let a = Infinity;
145 for (let s = 0; s < this.o.stems; s++) if (this.doneAt[s] > this.playhead) a = Math.min(a, this.avail[s] - this.playhead);
146 return a === Infinity ? 0 : a / sampleRate;
147 }
149 private clock() {
150 const ahead = this.aheadFrames();
151 const m: Clock = { type: "clock", playhead: this.playhead, ahead };
152 for (const p of this.ports) p.postMessage(m);
153 }
155 private report() {
156 const m: PlayerStatus = {
157 type: "status",
158 state: this.state,
159 playhead: this.playhead,
160 at: currentFrame,
161 fill: this.state === "buffering" ? this.fill() : 1,
162 rebuffers: this.rebuffers,
163 ahead: this.ahead(),
164 };
165 this.port.postMessage(m);
166 }
168 process(_in: Float32Array[][], outputs: Float32Array[][]): boolean {
169 const n = BLOCK;
170 if (this.state === "playing" && this.playhead >= this.endFrame) this.state = "ended";
171 if (this.blocks % RATE_EVERY === 0) this.measure();
172 if (this.state === "buffering") {
173 const target = Math.min(this.playhead + Math.round(this.target() * sampleRate), this.endFrame);
174 if (this.readyTo(target)) {
175 this.state = "playing";
176 this.fadeIn = 0;
177 }
178 }
179 if (this.state === "playing" && !this.readyTo(this.playhead + n)) {
180 // a stem ran short: pause everything until it's buffered further ahead
181 this.state = "buffering";
182 this.rebuffers++;
183 this.resume = Math.min(RESUME_MAX, this.resume * 2);
184 }
186 if (this.state !== "playing") {
187 for (let o = 0; o < outputs.length; o++) {
188 const L = outputs[o][0], R = outputs[o][1] ?? L, tl = this.tail[o];
189 for (let i = 0; i < n; i++) {
190 tl[0] *= TAIL;
191 tl[1] *= TAIL;
192 L[i] = tl[0];
193 if (R !== L) R[i] = tl[1];
194 }
195 }
196 } else {
197 const p = this.playhead;
198 for (let s = 0; s < this.o.stems; s++) {
199 const q = this.queues[s];
200 while (q.length && q[0].frame + q[0].L.length <= p) q.shift();
201 if (p >= this.doneAt[s]) continue;
202 const out = outputs[this.o.route[s]];
203 if (!out) continue;
204 const L = out[0], R = out[1] ?? L;
205 let i = 0;
206 for (const c of q) {
207 if (i >= n) break;
208 const f = p + i;
209 if (c.frame + c.L.length <= f) continue;
210 if (c.frame > f) break; // gap (can't happen: producers send in order)
211 const off = f - c.frame, len = Math.min(n - i, c.L.length - off);
212 for (let j = 0; j < len; j++) {
213 L[i + j] += c.L[off + j];
214 if (R !== L) R[i + j] += c.R[off + j];
215 }
216 i += len;
217 }
218 }
219 // fade in after a pause; remember the last samples in case the next block pauses
220 for (let o = 0; o < outputs.length; o++) {
221 const L = outputs[o][0], R = outputs[o][1] ?? L;
222 if (this.fadeIn < FADE_IN) {
223 for (let i = 0; i < n; i++) {
224 const g = Math.min(1, (this.fadeIn + i) / FADE_IN);
225 L[i] *= g;
226 if (R !== L) R[i] *= g;
227 }
228 }
229 this.tail[o][0] = L[n - 1];
230 this.tail[o][1] = R[n - 1];
231 }
232 this.fadeIn += n;
233 this.playhead += n;
234 }
235 if (++this.blocks % REPORT_EVERY === 0) {
236 this.report();
237 this.clock();
238 }
239 return true;
240 }
241}
243registerProcessor("stream-player", StreamPlayer);