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";
11const NORM_REF = 0.3; // normalized loudness: level 1 ≈ this RMS
12const NORM_TAU = 1.5; // s
13const NORM_RANGE = 20; // compensation limited to ×1/20 … ×20
15let synth: Synth;
16let sound: Params;
17let cur: Params; // sound with the latest timed changes
18let stem = 0;
19let player: MessagePort;
20let rendered = 0; // next piece frame to render
21let sendFrame = 0;
22let horizon = 0; // frame: every command before it has arrived
23let endFrame = Infinity;
24let playhead = 0;
25let ahead = 4 * SAMPLE_RATE;
26let doneSent = false;
27const cmds: SynthCmd[] = [];
28const lastOn = new Map<number, number>(); // pitch → when it was last struck
29let scheduled = false;
30let slow = 1;
32// output gain (hum levels), loudness normalization, and the final-note fade
33let gain = 1, gainTarget = 1, gainTau = 0, normalize = false;
34let msq = NORM_REF * NORM_REF;
35let holding = false;
36let fadeFrom = Infinity, fadeLen = 1; // s
38self.onmessage = (e: MessageEvent<SynthInit>) => {
39 const m = e.data;
40 if (m.type !== "init") return;
41 sound = { ...DEFAULTS, ...m.sound };
42 cur = sound;
43 synth = new Synth(SAMPLE_RATE);
44 synth.message({ type: "params", params: sound });
45 stem = m.stem;
46 slow = Math.max(1, m.slow ?? 1);
47 rendered = m.fromFrame;
48 horizon = m.fromFrame;
49 sendFrame = m.sendFrame;
50 playhead = m.sendFrame;
51 player = m.playerPort;
52 player.onmessage = (ev: MessageEvent<Clock>) => {
53 playhead = ev.data.playhead;
54 ahead = ev.data.ahead;
55 pump();
56 };
57 m.scorePort.onmessage = (ev: MessageEvent<ScoreToSynth>) => {
58 const d = ev.data;
59 if (d.type === "cmds") {
60 for (const c of d.cmds) cmds.push(c);
61 horizon = Math.max(horizon, Math.floor(d.horizon * SAMPLE_RATE));
62 } else if (d.type === "end") {
63 endFrame = Math.round(d.t * SAMPLE_RATE);
64 horizon = Math.max(horizon, endFrame);
65 }
66 pump();
67 };
68};
70function pump() {
71 if (scheduled) return;
72 scheduled = true;
73 setTimeout(loop, 0);
74}
76function apply(c: SynthCmd) {
77 switch (c.type) {
78 case "noteOn":
79 synth.message({ type: "noteOn", note: c.note, vel: c.vel });
80 lastOn.set(c.note, c.t);
81 break;
82 case "noteOff":
83 // notes are identified by pitch: a release from before a re-strike would cut the new note
84 if (c.on !== undefined && (lastOn.get(c.note) ?? -Infinity) > c.on) break;
85 synth.message({ type: "noteOff", note: c.note });
86 break;
87 case "params":
88 cur = { ...cur, ...c.params };
89 synth.message({ type: "params", params: cur });
90 break;
91 case "bend":
92 synth.message({ type: "bend", value: c.value });
93 break;
94 case "gain":
95 gainTarget = c.value;
96 gainTau = c.tau;
97 normalize = !!c.normalize;
98 break;
99 case "hold": {
100 if (holding) break; // instrument-wide: the first hold sets it up
101 holding = true;
102 // a struck body decays by itself: slow its decay (base and high-frequency loss alike, so the
103 // tone color stays) so it rings through the hold and fade
104 const ring = c.hold + c.fade;
105 const t60 = Math.min(60, Math.max(sound.t60 as number, 6 * ring));
106 const slow = t60 / (sound.t60 as number);
107 cur = { ...cur, t60, hfDamp: (sound.hfDamp as number) / slow };
108 synth.message({ type: "params", params: cur });
109 fadeFrom = c.t + Math.max(c.hold, 0.005);
110 fadeLen = Math.max(0.01, c.fade);
111 break;
112 }
113 }
114}
116const bl = new Float32Array(BLOCK), br = new Float32Array(BLOCK);
118function renderBlock(L: Float32Array, R: Float32Array, at: number) {
119 const now = rendered / SAMPLE_RATE;
120 const blockEnd = (rendered + BLOCK) / SAMPLE_RATE;
121 // commands due in this block apply at its start (block-accurate, like the synth's own timing)
122 while (cmds.length && cmds[0].t < blockEnd) apply(cmds.shift()!);
123 bl.fill(0);
124 br.fill(0);
125 synth.process(bl, br, BLOCK, now);
126 if (normalize) {
127 let s = 0;
128 for (let i = 0; i < BLOCK; i++) s += bl[i] * bl[i] + br[i] * br[i];
129 s /= 2 * BLOCK;
130 if (s > 1e-10) msq += (s - msq) * (1 - Math.exp(-BLOCK / SAMPLE_RATE / NORM_TAU));
131 }
132 const comp = normalize ? Math.max(1 / NORM_RANGE, Math.min(NORM_RANGE, NORM_REF / Math.sqrt(msq))) : 1;
133 const target = gainTarget * comp;
134 const g0 = gain;
135 gain = gainTau > 0 ? gain + (target - gain) * (1 - Math.exp(-BLOCK / SAMPLE_RATE / gainTau)) : target;
136 for (let i = 0; i < BLOCK; i++) {
137 let g = g0 + ((gain - g0) * (i + 1)) / BLOCK;
138 const t = (rendered + i) / SAMPLE_RATE;
139 if (t >= fadeFrom) {
140 const u = Math.min(1, (t - fadeFrom) / fadeLen);
141 const c = Math.cos((Math.PI / 2) * u);
142 g *= c * c;
143 }
144 L[at + i] = bl[i] * g;
145 R[at + i] = br[i] * g;
146 }
147 rendered += BLOCK;
148}
150function loop() {
151 scheduled = false;
152 if (!synth) return;
153 if (rendered >= endFrame) {
154 if (!doneSent) {
155 doneSent = true;
156 post({ type: "done", stem, frame: endFrame });
157 }
158 return;
159 }
160 // render whole blocks, up to what the score has sent, the buffer the player wants, and the end
161 const cap = Math.min(horizon, playhead + ahead, endFrame + BLOCK - 1);
162 const n = Math.min(CHUNK, Math.floor((cap - rendered) / BLOCK) * BLOCK);
163 if (n <= 0) return;
164 const frame = rendered;
165 const L = new Float32Array(n), R = new Float32Array(n);
166 const t0 = performance.now();
167 for (let i = 0; i < n; i += BLOCK) renderBlock(L, R, i);
168 if (slow > 1) {
169 const until = performance.now() + (slow - 1) * (performance.now() - t0);
170 while (performance.now() < until); // testing only: pretend to be a slower device
171 }
172 if (frame + n > sendFrame) {
173 const off = Math.max(0, sendFrame - frame);
174 const l = off ? L.slice(off) : L, r = off ? R.slice(off) : R;
175 post({ type: "chunk", stem, frame: frame + off, L: l, R: r }, [l.buffer, r.buffer]);
176 }
177 pump(); // yield between chunks so new commands and the clock get through
178}
180function post(m: ToPlayer, transfer: Transferable[] = []) {
181 player.postMessage(m, transfer);
182}