1// Runs a composition's score in the background. It fast-forwards silently to the start point,
2// then simulates ahead of the player's playhead (no further than the buffer the player asks for),
3// sending drawing data to the page, timed commands to the synth workers, and its own audio (if
4// any) to the player.
5//
6// Synth commands are held back LAG seconds of piece time before they're released (with a horizon:
7// "every command before this time has been sent"), so a score can still lengthen a note it has
8// already played (the final-note hold) when it finds, a little later, that the piece has ended.
10import { SCORES } from "../compositions/scores.ts";
11import { SAMPLE_RATE, type Clock, type ScoreInit, type ScoreOut, type ScoreToSynth, type SynthCmd, type ToPlayer, type VisEvent } from "./protocol.ts";
12import type { NoteRef, PieceScore, ScoreSink } from "./score.ts";
14const LAG = 2.5; // s of piece time synth commands are held back
15const STEP = 0.05; // s of piece time simulated between checks for messages
16const FLUSH = 0.1; // s of piece time between posts to the page
17const EXTRA = 0.5; // s simulated beyond what the player needs (covers LAG and the synths' blocks)
19let score: PieceScore;
20let init: ScoreInit;
21let emitting = false;
22let playhead = 0; // piece frame
23let ahead = 4 * SAMPLE_RATE;
24let endT = Infinity;
25let finished = false;
26let scheduled = false;
28// held-back synth commands per stem, and what has been released
29let pending: SynthCmd[][] = [];
30let released = -Infinity; // horizon sent so far
31// drawing data waiting to be posted
32const tracks = new Map<number, { stride: number; rows: number[] }>();
33let events: VisEvent[] = [];
34let lastInfo: { t: number; info: Record<string, string> } | null = null;
35let lastFlushT = -Infinity;
36// score-rendered audio, per stem: next frame
37const audioFrame = new Map<number, number>();
39const toPage = (m: ScoreOut, transfer: Transferable[] = []) => (self as unknown as Worker).postMessage(m, transfer);
40const toPlayer = (m: ToPlayer, transfer: Transferable[] = []) => init.playerPort.postMessage(m, transfer);
42const sink: ScoreSink = {
43 get emitting() {
44 return emitting;
45 },
46 frame(track, t, values) {
47 if (!emitting) return;
48 let tr = tracks.get(track);
49 if (!tr) tracks.set(track, (tr = { stride: values.length + 1, rows: [] }));
50 tr.rows.push(t);
51 for (let i = 0; i < values.length; i++) tr.rows.push(values[i]);
52 },
53 event(e) {
54 if (emitting) events.push(e);
55 },
56 info(t, info) {
57 if (emitting) lastInfo = { t, info };
58 },
59 note(stem, t, midi, vel, dur) {
60 if (!emitting || !pending[stem] || vel <= 0) return null;
61 const on: SynthCmd = { t, type: "noteOn", note: midi, vel: Math.max(0.01, Math.min(1, vel)) };
62 const off: SynthCmd = { t: t + dur, type: "noteOff", note: midi, on: t };
63 pending[stem].push(on, off);
64 return { stem, t, off };
65 },
66 hold(ref: NoteRef, at, hold, fade) {
67 if (!emitting || !pending[ref.stem]) return;
68 const from = Math.max(at, released);
69 const end = from + hold + fade;
70 // the note's release, if not yet sent, moves to the end of the fade
71 if (pending[ref.stem].includes(ref.off) && ref.off.t < end) ref.off.t = end;
72 pending[ref.stem].push({ t: from, type: "hold", hold, fade });
73 },
74 cmd(stem, c) {
75 if (emitting && pending[stem]) pending[stem].push(c);
76 },
77 audio(stem, L, R) {
78 if (!emitting) return;
79 const frame = audioFrame.get(stem) ?? Math.round(init.from * SAMPLE_RATE);
80 audioFrame.set(stem, frame + L.length);
81 const send = Math.round(init.start * SAMPLE_RATE);
82 if (frame + L.length <= send) return;
83 const off = Math.max(0, send - frame);
84 const l = off ? L.slice(off) : L, r = off ? R.slice(off) : R;
85 toPlayer({ type: "chunk", stem, frame: frame + off, L: l, R: r }, [l.buffer, r.buffer]);
86 },
87 end(t) {
88 if (endT !== Infinity) return;
89 endT = t;
90 toPage({ type: "end", t });
91 toPlayer({ type: "end", frame: Math.round(t * SAMPLE_RATE) });
92 },
93};
95/** Release synth commands before `horizon` (in time order) and post drawing data. */
96function flush(horizon: number, force = false) {
97 if (horizon > released) {
98 init.synthPorts.forEach((port, s) => {
99 if (!port) return;
100 const q = pending[s];
101 q.sort((a, b) => a.t - b.t);
102 let n = 0;
103 while (n < q.length && q[n].t < horizon) n++;
104 const m: ScoreToSynth = { type: "cmds", cmds: q.splice(0, n), horizon };
105 port.postMessage(m);
106 });
107 released = horizon;
108 }
109 if (!force && score.time - lastFlushT < FLUSH) return;
110 lastFlushT = score.time;
111 for (const [track, tr] of tracks) {
112 if (!tr.rows.length) continue;
113 const data = Float64Array.from(tr.rows);
114 tr.rows = [];
115 toPage({ type: "frames", track, stride: tr.stride, data }, [data.buffer]);
116 }
117 if (events.length) {
118 toPage({ type: "events", events });
119 events = [];
120 }
121 if (lastInfo) {
122 toPage({ type: "info", t: lastInfo.t, info: lastInfo.info });
123 lastInfo = null;
124 }
125}
127function pump() {
128 if (scheduled || finished) return;
129 scheduled = true;
130 setTimeout(loop, 0);
131}
133function loop() {
134 scheduled = false;
135 try {
136 if (score.time >= endT) {
137 // everything is known: release the rest and tell the synths where to stop
138 flush(endT + 1, true);
139 init.synthPorts.forEach((port) => port?.postMessage({ type: "end", t: endT } satisfies ScoreToSynth));
140 finished = true;
141 return;
142 }
143 const need = Math.min(endT, (playhead + ahead) / SAMPLE_RATE + LAG + EXTRA);
144 if (score.time >= need) return; // far enough ahead: wait for the clock
145 score.advance(Math.min(score.time + STEP, need, endT));
146 flush(score.time - LAG);
147 } catch (err) {
148 finished = true;
149 toPage({ type: "error", message: String((err as Error)?.stack ?? err) });
150 return;
151 }
152 pump();
153}
155self.onmessage = (e: MessageEvent<ScoreInit>) => {
156 const m = e.data;
157 if (m.type !== "init") return;
158 init = m;
159 pending = m.synthPorts.map(() => []);
160 playhead = Math.round(m.start * SAMPLE_RATE);
161 m.playerPort.onmessage = (ev: MessageEvent<Clock>) => {
162 playhead = ev.data.playhead;
163 ahead = ev.data.ahead;
164 pump();
165 };
166 try {
167 const make = SCORES[m.comp];
168 if (!make) throw new Error(`no score for ${m.comp}`);
169 score = make(m.P, m.seed, sink);
170 // silently up to where sound starts (start minus a pre-roll), then for real
171 if (m.from > 0) score.advance(m.from);
172 emitting = true;
173 released = m.from;
174 } catch (err) {
175 finished = true;
176 toPage({ type: "error", message: String((err as Error)?.stack ?? err) });
177 return;
178 }
179 pump();
180};