// One performance of a composition from a start time: the score worker, one synth worker per // instrument stem, the player worklet, and the effects. The page only draws: it reads the player's // playhead (so picture and sound share one clock) and the drawing data the score sends. import type { Params } from "../core/params.ts"; import { SharedReverb, routeEffects } from "../instruments/effects.ts"; import { FrameStore } from "./frames.ts"; import type { Layout } from "./layout.ts"; import playerUrl from "./player.ts?worker&url"; import { BLOCK, SAMPLE_RATE, type PlayerOptions, type PlayerStatus, type ScoreInit, type ScoreOut, type SynthInit } from "./protocol.ts"; /** Sound is computed from this long before the start point, so notes already ringing are heard. */ const PREROLL = 4; const loaded = new WeakMap>(); export type PerformanceState = "loading" | "buffering" | "playing" | "ended" | "error"; export class Performance { readonly store = new FrameStore(); readonly start: number; readonly seed: number; state: PerformanceState = "loading"; endT: number | null = null; error: string | null = null; fill = 0; rebuffers = 0; ahead = 0; readonly ready: Promise; private ctx: AudioContext; private layout: Layout; private workers: Worker[] = []; private node: AudioWorkletNode | null = null; private master: GainNode; private levels: GainNode[] = []; private pans: (StereoPannerNode | null)[] = []; private reverb: SharedReverb | null = null; private status: PlayerStatus | null = null; private disposed = false; private estimatedEnd: number; constructor(ctx: AudioContext, dest: AudioNode, comp: string, P: Params, seed: number, start: number, layout: Layout, estimatedEnd: number) { this.ctx = ctx; this.start = start; this.seed = seed; this.layout = layout; this.estimatedEnd = estimatedEnd; this.master = ctx.createGain(); this.master.connect(dest); this.ready = this.open(comp, P); } private async open(comp: string, P: Params) { const ctx = this.ctx; let p = loaded.get(ctx); if (!p) loaded.set(ctx, (p = ctx.audioWorklet.addModule(playerUrl))); await p; if (this.disposed) return; const { stems, outputs } = this.layout; // the player, and each output's level → pan → effects const opts: PlayerOptions = { stems: stems.length, outputs: outputs.length, route: stems.map((s) => s.output), startFrame: Math.round(this.start * SAMPLE_RATE), estimatedEnd: Math.round(this.estimatedEnd * SAMPLE_RATE) }; const node = new AudioWorkletNode(ctx, "stream-player", { numberOfInputs: 0, numberOfOutputs: outputs.length, outputChannelCount: outputs.map(() => 2), processorOptions: opts, }); this.node = node; if (outputs.some((o) => o.effects === "shared")) this.reverb = new SharedReverb(ctx, this.master, this.layout.reverbTime ?? 3); outputs.forEach((o, i) => { const level = ctx.createGain(); level.gain.value = Math.pow(10, o.level(P) / 20); node.connect(level, i); let tail: AudioNode = level; let pan: StereoPannerNode | null = null; if (o.pan) { pan = ctx.createStereoPanner(); pan.pan.value = o.pan(P); level.connect(pan); tail = pan; } routeEffects(ctx, tail, this.master, o.sound, o.effects === "shared" ? { send: this.reverb!.input } : o.effects); this.levels.push(level); this.pans.push(pan); }); node.port.onmessage = (e: MessageEvent) => this.onStatus(e.data); // workers: score, and a synth per synth stem; ports between them and to the player const from = Math.max(0, this.start - PREROLL); const playerPorts: MessagePort[] = []; const synthPorts: (MessagePort | null)[] = []; stems.forEach((s, i) => { if (s.kind !== "synth") { synthPorts.push(null); return; } const w = new Worker(new URL("./synthWorker.ts", import.meta.url), { type: "module" }); this.workers.push(w); const toScore = new MessageChannel(), toPlayer = new MessageChannel(); synthPorts.push(toScore.port1); playerPorts.push(toPlayer.port2); const init: SynthInit = { type: "init", sound: s.sound ?? {}, fromFrame: Math.floor((from * SAMPLE_RATE) / BLOCK) * BLOCK, sendFrame: Math.round(this.start * SAMPLE_RATE), stem: i, scorePort: toScore.port2, playerPort: toPlayer.port1, slow: Number(new URLSearchParams(location.search).get("slow")) || undefined, }; w.postMessage(init, [toScore.port2, toPlayer.port1]); w.onerror = (ev) => this.fail(`instrument: ${ev.message}`); }); const sw = new Worker(new URL("./scoreWorker.ts", import.meta.url), { type: "module" }); this.workers.push(sw); const scoreToPlayer = new MessageChannel(); playerPorts.push(scoreToPlayer.port2); sw.onmessage = (e: MessageEvent) => this.onScore(e.data); sw.onerror = (ev) => this.fail(`score: ${ev.message}`); const init: ScoreInit = { type: "init", comp, P, seed: this.seed, start: this.start, from, synthPorts, playerPort: scoreToPlayer.port1 }; sw.postMessage(init, [...synthPorts.filter((x): x is MessagePort => !!x), scoreToPlayer.port1]); node.port.postMessage({ type: "ports", ports: playerPorts }, playerPorts); this.state = "buffering"; } private onScore(m: ScoreOut) { if (m.type === "frames") this.store.add(m.track, m.stride, m.data); else if (m.type === "events") this.store.addEvents(m.events); else if (m.type === "info") this.store.addInfo(m.t, m.info); else if (m.type === "end") this.endT = m.t; else if (m.type === "error") this.fail(m.message); } private onStatus(s: PlayerStatus) { this.status = s; if (this.state === "error") return; this.state = s.state; this.fill = s.fill; this.rebuffers = s.rebuffers; this.ahead = s.ahead; } private fail(message: string) { this.state = "error"; this.error = message; console.error(message); } /** Time the listener is hearing now (piece seconds): the player's playhead, less output latency. */ time(): number { const s = this.status; if (!s) return this.start; let frames = s.playhead; if (s.state === "playing") frames += Math.min(4096, Math.max(0, this.ctx.currentTime * SAMPLE_RATE - s.at)); const latency = (this.ctx.outputLatency || 0) + (this.ctx.baseLatency || 0); return Math.max(this.start, frames / SAMPLE_RATE - latency); } /** Live settings: output levels and pans. */ update(P: Params) { const t = this.ctx.currentTime; this.layout.outputs.forEach((o, i) => { this.levels[i]?.gain.setTargetAtTime(Math.pow(10, o.level(P) / 20), t, 0.05); if (o.pan) this.pans[i]?.pan.setTargetAtTime(o.pan(P), t, 0.05); }); } dispose() { if (this.disposed) return; this.disposed = true; for (const w of this.workers) w.terminate(); const t = this.ctx.currentTime; const m = this.master, node = this.node, rev = this.reverb; m.gain.setTargetAtTime(0, t, 0.02); window.setTimeout(() => { node?.disconnect(); node?.port.close(); rev?.dispose(); m.disconnect(); }, 200); } }