/ music / double-pendulum
Sign in
music / double-pendulum
double-pendulum / src / stream / performance.ts
185 lines · 7.2 KBBlameHistoryRaw
1// One performance of a composition from a start time: the score worker, one synth worker per
2// instrument stem, the player worklet, and the effects. The page only draws: it reads the player's
3// playhead (so picture and sound share one clock) and the drawing data the score sends.
5import type { Params } from "../core/params.ts";
6import { SharedReverb, routeEffects } from "../instruments/effects.ts";
7import { FrameStore } from "./frames.ts";
8import type { Layout } from "./layout.ts";
9import playerUrl from "./player.ts?worker&url";
10import { BLOCK, SAMPLE_RATE, type PlayerOptions, type PlayerStatus, type ScoreInit, type ScoreOut, type SynthInit } from "./protocol.ts";
12/** Sound is computed from this long before the start point, so notes already ringing are heard. */
13const PREROLL = 4;
15const loaded = new WeakMap<BaseAudioContext, Promise<void>>();
17export type PerformanceState = "loading" | "buffering" | "playing" | "ended" | "error";
19export class Performance {
20 readonly store = new FrameStore();
21 readonly start: number;
22 readonly seed: number;
23 state: PerformanceState = "loading";
24 endT: number | null = null;
25 error: string | null = null;
26 fill = 0;
27 rebuffers = 0;
28 ahead = 0;
29 readonly ready: Promise<void>;
31 private ctx: AudioContext;
32 private layout: Layout;
33 private workers: Worker[] = [];
34 private node: AudioWorkletNode | null = null;
35 private master: GainNode;
36 private levels: GainNode[] = [];
37 private pans: (StereoPannerNode | null)[] = [];
38 private reverb: SharedReverb | null = null;
39 private status: PlayerStatus | null = null;
40 private disposed = false;
41 private estimatedEnd: number;
43 constructor(ctx: AudioContext, dest: AudioNode, comp: string, P: Params, seed: number, start: number, layout: Layout, estimatedEnd: number) {
44 this.ctx = ctx;
45 this.start = start;
46 this.seed = seed;
47 this.layout = layout;
48 this.estimatedEnd = estimatedEnd;
49 this.master = ctx.createGain();
50 this.master.connect(dest);
51 this.ready = this.open(comp, P);
52 }
54 private async open(comp: string, P: Params) {
55 const ctx = this.ctx;
56 let p = loaded.get(ctx);
57 if (!p) loaded.set(ctx, (p = ctx.audioWorklet.addModule(playerUrl)));
58 await p;
59 if (this.disposed) return;
60 const { stems, outputs } = this.layout;
62 // the player, and each output's level → pan → effects
63 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) };
64 const node = new AudioWorkletNode(ctx, "stream-player", {
65 numberOfInputs: 0,
66 numberOfOutputs: outputs.length,
67 outputChannelCount: outputs.map(() => 2),
68 processorOptions: opts,
69 });
70 this.node = node;
71 if (outputs.some((o) => o.effects === "shared")) this.reverb = new SharedReverb(ctx, this.master, this.layout.reverbTime ?? 3);
72 outputs.forEach((o, i) => {
73 const level = ctx.createGain();
74 level.gain.value = Math.pow(10, o.level(P) / 20);
75 node.connect(level, i);
76 let tail: AudioNode = level;
77 let pan: StereoPannerNode | null = null;
78 if (o.pan) {
79 pan = ctx.createStereoPanner();
80 pan.pan.value = o.pan(P);
81 level.connect(pan);
82 tail = pan;
83 }
84 routeEffects(ctx, tail, this.master, o.sound, o.effects === "shared" ? { send: this.reverb!.input } : o.effects);
85 this.levels.push(level);
86 this.pans.push(pan);
87 });
88 node.port.onmessage = (e: MessageEvent<PlayerStatus>) => this.onStatus(e.data);
90 // workers: score, and a synth per synth stem; ports between them and to the player
91 const from = Math.max(0, this.start - PREROLL);
92 const playerPorts: MessagePort[] = [];
93 const synthPorts: (MessagePort | null)[] = [];
94 stems.forEach((s, i) => {
95 if (s.kind !== "synth") {
96 synthPorts.push(null);
97 return;
98 }
99 const w = new Worker(new URL("./synthWorker.ts", import.meta.url), { type: "module" });
100 this.workers.push(w);
101 const toScore = new MessageChannel(), toPlayer = new MessageChannel();
102 synthPorts.push(toScore.port1);
103 playerPorts.push(toPlayer.port2);
104 const init: SynthInit = {
105 type: "init",
106 sound: s.sound ?? {},
107 fromFrame: Math.floor((from * SAMPLE_RATE) / BLOCK) * BLOCK,
108 sendFrame: Math.round(this.start * SAMPLE_RATE),
109 stem: i,
110 scorePort: toScore.port2,
111 playerPort: toPlayer.port1,
112 slow: Number(new URLSearchParams(location.search).get("slow")) || undefined,
113 };
114 w.postMessage(init, [toScore.port2, toPlayer.port1]);
115 w.onerror = (ev) => this.fail(`instrument: ${ev.message}`);
116 });
117 const sw = new Worker(new URL("./scoreWorker.ts", import.meta.url), { type: "module" });
118 this.workers.push(sw);
119 const scoreToPlayer = new MessageChannel();
120 playerPorts.push(scoreToPlayer.port2);
121 sw.onmessage = (e: MessageEvent<ScoreOut>) => this.onScore(e.data);
122 sw.onerror = (ev) => this.fail(`score: ${ev.message}`);
123 const init: ScoreInit = { type: "init", comp, P, seed: this.seed, start: this.start, from, synthPorts, playerPort: scoreToPlayer.port1 };
124 sw.postMessage(init, [...synthPorts.filter((x): x is MessagePort => !!x), scoreToPlayer.port1]);
125 node.port.postMessage({ type: "ports", ports: playerPorts }, playerPorts);
126 this.state = "buffering";
127 }
129 private onScore(m: ScoreOut) {
130 if (m.type === "frames") this.store.add(m.track, m.stride, m.data);
131 else if (m.type === "events") this.store.addEvents(m.events);
132 else if (m.type === "info") this.store.addInfo(m.t, m.info);
133 else if (m.type === "end") this.endT = m.t;
134 else if (m.type === "error") this.fail(m.message);
135 }
137 private onStatus(s: PlayerStatus) {
138 this.status = s;
139 if (this.state === "error") return;
140 this.state = s.state;
141 this.fill = s.fill;
142 this.rebuffers = s.rebuffers;
143 this.ahead = s.ahead;
144 }
146 private fail(message: string) {
147 this.state = "error";
148 this.error = message;
149 console.error(message);
150 }
152 /** Time the listener is hearing now (piece seconds): the player's playhead, less output latency. */
153 time(): number {
154 const s = this.status;
155 if (!s) return this.start;
156 let frames = s.playhead;
157 if (s.state === "playing") frames += Math.min(4096, Math.max(0, this.ctx.currentTime * SAMPLE_RATE - s.at));
158 const latency = (this.ctx.outputLatency || 0) + (this.ctx.baseLatency || 0);
159 return Math.max(this.start, frames / SAMPLE_RATE - latency);
160 }
162 /** Live settings: output levels and pans. */
163 update(P: Params) {
164 const t = this.ctx.currentTime;
165 this.layout.outputs.forEach((o, i) => {
166 this.levels[i]?.gain.setTargetAtTime(Math.pow(10, o.level(P) / 20), t, 0.05);
167 if (o.pan) this.pans[i]?.pan.setTargetAtTime(o.pan(P), t, 0.05);
168 });
169 }
171 dispose() {
172 if (this.disposed) return;
173 this.disposed = true;
174 for (const w of this.workers) w.terminate();
175 const t = this.ctx.currentTime;
176 const m = this.master, node = this.node, rev = this.reverb;
177 m.gain.setTargetAtTime(0, t, 0.02);
178 window.setTimeout(() => {
179 node?.disconnect();
180 node?.port.close();
181 rev?.dispose();
182 m.disconnect();
183 }, 200);
184 }
↑↓ move↵openescclose