/ music / double-pendulum
Sign in
music / double-pendulum
double-pendulum / src / stream / synthWorker.ts
169 lines · 5.9 KBBlameHistoryRaw
1// One instrument ("stem") of a performance, rendered in its own worker: the modal-synth engine,
2// driven by timed commands from the score, in 128-frame blocks from a fixed piece frame, so the
3// result depends only on the commands (the same on every device). It renders as fast as it can,
4// up to whichever comes first: what the score has sent (its horizon), or the player's playhead
5// plus the buffer it asks for. Audio goes straight to the player.
7import { DEFAULTS, type Params } from "@modal-synth/engine/params.ts";
8import { Synth } from "@modal-synth/engine/synth.ts";
9import { BLOCK, CHUNK, SAMPLE_RATE, type Clock, type ScoreToSynth, type SynthCmd, type SynthInit, type ToPlayer } from "./protocol.ts";
11let synth: Synth;
12let sound: Params;
13let cur: Params; // sound with the latest timed changes
14let stem = 0;
15let player: MessagePort;
16let rendered = 0; // next piece frame to render
17let sendFrame = 0;
18let horizon = 0; // frame: every command before it has arrived
19let endFrame = Infinity;
20let playhead = 0;
21let ahead = 4 * SAMPLE_RATE;
22let doneSent = false;
23const cmds: SynthCmd[] = [];
24const lastOn = new Map<number, number>(); // pitch → when it was last struck
25let scheduled = false;
26let slow = 1;
28// output gain, and the final-note fade
29let gain = 1, gainTarget = 1, gainTau = 0;
30let holding = false;
31let fadeFrom = Infinity, fadeLen = 1; // s
33self.onmessage = (e: MessageEvent<SynthInit>) => {
34 const m = e.data;
35 if (m.type !== "init") return;
36 sound = { ...DEFAULTS, ...m.sound };
37 cur = sound;
38 synth = new Synth(SAMPLE_RATE);
39 synth.message({ type: "params", params: sound });
40 stem = m.stem;
41 slow = Math.max(1, m.slow ?? 1);
42 rendered = m.fromFrame;
43 horizon = m.fromFrame;
44 sendFrame = m.sendFrame;
45 playhead = m.sendFrame;
46 player = m.playerPort;
47 player.onmessage = (ev: MessageEvent<Clock>) => {
48 playhead = ev.data.playhead;
49 ahead = ev.data.ahead;
50 pump();
51 };
52 m.scorePort.onmessage = (ev: MessageEvent<ScoreToSynth>) => {
53 const d = ev.data;
54 if (d.type === "cmds") {
55 for (const c of d.cmds) cmds.push(c);
56 horizon = Math.max(horizon, Math.floor(d.horizon * SAMPLE_RATE));
57 } else if (d.type === "end") {
58 endFrame = Math.round(d.t * SAMPLE_RATE);
59 horizon = Math.max(horizon, endFrame);
60 }
61 pump();
62 };
63};
65function pump() {
66 if (scheduled) return;
67 scheduled = true;
68 setTimeout(loop, 0);
71function apply(c: SynthCmd) {
72 switch (c.type) {
73 case "noteOn":
74 synth.message({ type: "noteOn", note: c.note, vel: c.vel });
75 lastOn.set(c.note, c.t);
76 break;
77 case "noteOff":
78 // notes are identified by pitch: a release from before a re-strike would cut the new note
79 if (c.on !== undefined && (lastOn.get(c.note) ?? -Infinity) > c.on) break;
80 synth.message({ type: "noteOff", note: c.note });
81 break;
82 case "params":
83 cur = { ...cur, ...c.params };
84 synth.message({ type: "params", params: cur });
85 break;
86 case "bend":
87 synth.message({ type: "bend", value: c.value });
88 break;
89 case "gain":
90 gainTarget = c.value;
91 gainTau = c.tau;
92 break;
93 case "hold": {
94 if (holding) break; // instrument-wide: the first hold sets it up
95 holding = true;
96 // a struck body decays by itself: slow its decay (base and high-frequency loss alike, so the
97 // tone color stays) so it rings through the hold and fade
98 const ring = c.hold + c.fade;
99 const t60 = Math.min(60, Math.max(sound.t60 as number, 6 * ring));
100 const slow = t60 / (sound.t60 as number);
101 cur = { ...cur, t60, hfDamp: (sound.hfDamp as number) / slow };
102 synth.message({ type: "params", params: cur });
103 fadeFrom = c.t + Math.max(c.hold, 0.005);
104 fadeLen = Math.max(0.01, c.fade);
105 break;
106 }
107 }
110const bl = new Float32Array(BLOCK), br = new Float32Array(BLOCK);
112function renderBlock(L: Float32Array, R: Float32Array, at: number) {
113 const now = rendered / SAMPLE_RATE;
114 const blockEnd = (rendered + BLOCK) / SAMPLE_RATE;
115 // commands due in this block apply at its start (block-accurate, like the synth's own timing)
116 while (cmds.length && cmds[0].t < blockEnd) apply(cmds.shift()!);
117 bl.fill(0);
118 br.fill(0);
119 synth.process(bl, br, BLOCK, now);
120 const target = gainTarget;
121 const g0 = gain;
122 gain = gainTau > 0 ? gain + (target - gain) * (1 - Math.exp(-BLOCK / SAMPLE_RATE / gainTau)) : target;
123 for (let i = 0; i < BLOCK; i++) {
124 let g = g0 + ((gain - g0) * (i + 1)) / BLOCK;
125 const t = (rendered + i) / SAMPLE_RATE;
126 if (t >= fadeFrom) {
127 const u = Math.min(1, (t - fadeFrom) / fadeLen);
128 const c = Math.cos((Math.PI / 2) * u);
129 g *= c * c;
130 }
131 L[at + i] = bl[i] * g;
132 R[at + i] = br[i] * g;
133 }
134 rendered += BLOCK;
137function loop() {
138 scheduled = false;
139 if (!synth) return;
140 if (rendered >= endFrame) {
141 if (!doneSent) {
142 doneSent = true;
143 post({ type: "done", stem, frame: endFrame });
144 }
145 return;
146 }
147 // render whole blocks, up to what the score has sent, the buffer the player wants, and the end
148 const cap = Math.min(horizon, playhead + ahead, endFrame + BLOCK - 1);
149 const n = Math.min(CHUNK, Math.floor((cap - rendered) / BLOCK) * BLOCK);
150 if (n <= 0) return;
151 const frame = rendered;
152 const L = new Float32Array(n), R = new Float32Array(n);
153 const t0 = performance.now();
154 for (let i = 0; i < n; i += BLOCK) renderBlock(L, R, i);
155 if (slow > 1) {
156 const until = performance.now() + (slow - 1) * (performance.now() - t0);
157 while (performance.now() < until); // testing only: pretend to be a slower device
158 }
159 if (frame + n > sendFrame) {
160 const off = Math.max(0, sendFrame - frame);
161 const l = off ? L.slice(off) : L, r = off ? R.slice(off) : R;
162 post({ type: "chunk", stem, frame: frame + off, L: l, R: r }, [l.buffer, r.buffer]);
163 }
164 pump(); // yield between chunks so new commands and the clock get through
167function post(m: ToPlayer, transfer: Transferable[] = []) {
168 player.postMessage(m, transfer);
↑↓ move↵openescclose