// Runs a composition's score in the background. It fast-forwards silently to the start point, // then simulates ahead of the player's playhead (no further than the buffer the player asks for), // sending drawing data to the page, timed commands to the synth workers, and its own audio (if // any) to the player. // // Synth commands are held back LAG seconds of piece time before they're released (with a horizon: // "every command before this time has been sent"), so a score can still lengthen a note it has // already played (the final-note hold) when it finds, a little later, that the piece has ended. import { SCORES } from "../compositions/scores.ts"; import { SAMPLE_RATE, type Clock, type ScoreInit, type ScoreOut, type ScoreToSynth, type SynthCmd, type ToPlayer, type VisEvent } from "./protocol.ts"; import type { NoteRef, PieceScore, ScoreSink } from "./score.ts"; const LAG = 2.5; // s of piece time synth commands are held back const STEP = 0.05; // s of piece time simulated between checks for messages const FLUSH = 0.1; // s of piece time between posts to the page const EXTRA = 0.5; // s simulated beyond what the player needs (covers LAG and the synths' blocks) let score: PieceScore; let init: ScoreInit; let emitting = false; let playhead = 0; // piece frame let ahead = 4 * SAMPLE_RATE; let endT = Infinity; let finished = false; let scheduled = false; // held-back synth commands per stem, and what has been released let pending: SynthCmd[][] = []; let released = -Infinity; // horizon sent so far // drawing data waiting to be posted const tracks = new Map(); let events: VisEvent[] = []; let lastInfo: { t: number; info: Record } | null = null; let lastFlushT = -Infinity; // score-rendered audio, per stem: next frame const audioFrame = new Map(); const toPage = (m: ScoreOut, transfer: Transferable[] = []) => (self as unknown as Worker).postMessage(m, transfer); const toPlayer = (m: ToPlayer, transfer: Transferable[] = []) => init.playerPort.postMessage(m, transfer); const sink: ScoreSink = { get emitting() { return emitting; }, frame(track, t, values) { if (!emitting) return; let tr = tracks.get(track); if (!tr) tracks.set(track, (tr = { stride: values.length + 1, rows: [] })); tr.rows.push(t); for (let i = 0; i < values.length; i++) tr.rows.push(values[i]); }, event(e) { if (emitting) events.push(e); }, info(t, info) { if (emitting) lastInfo = { t, info }; }, note(stem, t, midi, vel, dur) { if (!emitting || !pending[stem] || vel <= 0) return null; const on: SynthCmd = { t, type: "noteOn", note: midi, vel: Math.max(0.01, Math.min(1, vel)) }; const off: SynthCmd = { t: t + dur, type: "noteOff", note: midi, on: t }; pending[stem].push(on, off); return { stem, t, off }; }, hold(ref: NoteRef, at, hold, fade) { if (!emitting || !pending[ref.stem]) return; const from = Math.max(at, released); const end = from + hold + fade; // the note's release, if not yet sent, moves to the end of the fade if (pending[ref.stem].includes(ref.off) && ref.off.t < end) ref.off.t = end; pending[ref.stem].push({ t: from, type: "hold", hold, fade }); }, cmd(stem, c) { if (emitting && pending[stem]) pending[stem].push(c); }, audio(stem, L, R) { if (!emitting) return; const frame = audioFrame.get(stem) ?? Math.round(init.from * SAMPLE_RATE); audioFrame.set(stem, frame + L.length); const send = Math.round(init.start * SAMPLE_RATE); if (frame + L.length <= send) return; const off = Math.max(0, send - frame); const l = off ? L.slice(off) : L, r = off ? R.slice(off) : R; toPlayer({ type: "chunk", stem, frame: frame + off, L: l, R: r }, [l.buffer, r.buffer]); }, end(t) { if (endT !== Infinity) return; endT = t; toPage({ type: "end", t }); toPlayer({ type: "end", frame: Math.round(t * SAMPLE_RATE) }); }, }; /** Release synth commands before `horizon` (in time order) and post drawing data. */ function flush(horizon: number, force = false) { if (horizon > released) { init.synthPorts.forEach((port, s) => { if (!port) return; const q = pending[s]; q.sort((a, b) => a.t - b.t); let n = 0; while (n < q.length && q[n].t < horizon) n++; const m: ScoreToSynth = { type: "cmds", cmds: q.splice(0, n), horizon }; port.postMessage(m); }); released = horizon; } if (!force && score.time - lastFlushT < FLUSH) return; lastFlushT = score.time; for (const [track, tr] of tracks) { if (!tr.rows.length) continue; const data = Float64Array.from(tr.rows); tr.rows = []; toPage({ type: "frames", track, stride: tr.stride, data }, [data.buffer]); } if (events.length) { toPage({ type: "events", events }); events = []; } if (lastInfo) { toPage({ type: "info", t: lastInfo.t, info: lastInfo.info }); lastInfo = null; } } function pump() { if (scheduled || finished) return; scheduled = true; setTimeout(loop, 0); } function loop() { scheduled = false; try { if (score.time >= endT) { // everything is known: release the rest and tell the synths where to stop flush(endT + 1, true); init.synthPorts.forEach((port) => port?.postMessage({ type: "end", t: endT } satisfies ScoreToSynth)); finished = true; return; } const need = Math.min(endT, (playhead + ahead) / SAMPLE_RATE + LAG + EXTRA); if (score.time >= need) return; // far enough ahead: wait for the clock score.advance(Math.min(score.time + STEP, need, endT)); flush(score.time - LAG); } catch (err) { finished = true; toPage({ type: "error", message: String((err as Error)?.stack ?? err) }); return; } pump(); } self.onmessage = (e: MessageEvent) => { const m = e.data; if (m.type !== "init") return; init = m; pending = m.synthPorts.map(() => []); playhead = Math.round(m.start * SAMPLE_RATE); m.playerPort.onmessage = (ev: MessageEvent) => { playhead = ev.data.playhead; ahead = ev.data.ahead; pump(); }; try { const make = SCORES[m.comp]; if (!make) throw new Error(`no score for ${m.comp}`); score = make(m.P, m.seed, sink); // silently up to where sound starts (start minus a pre-roll), then for real if (m.from > 0) score.advance(m.from); emitting = true; released = m.from; } catch (err) { finished = true; toPage({ type: "error", message: String((err as Error)?.stack ?? err) }); return; } pump(); };