216afddorbits: render instruments ahead in Web WorkersJeremy Magland 1// Renders one modal-synth instrument off the real-time audio thread, ahead of playback.
2//
3// The synth is the same engine the AudioWorklet runs. Here it renders chunks of audio up to
4// `aheadFrames` beyond what the player has consumed, and posts them straight to the player's port.
5// Several of these workers run in parallel, one per instrument, on the device's other cores.
6// Notes arrive early (the page simulates ahead) with absolute audio-context times; the synth
7// applies them at the exact sample.
9import { DEFAULTS, type Params } from "@modal-synth/engine/params.ts";
10import { Synth } from "@modal-synth/engine/synth.ts";
11import type { Chunk, Consumed, FromWorker, ToWorker } from "./protocol.ts";
13const BLOCK = 128;
14const CHUNK = 1024; // frames per posted chunk (~21 ms)
16let synth: Synth | null = null;
17let sr = 48000;
18let port: MessagePort | null = null;
19let rendered = 0; // next frame to render (absolute)
20let consumed = 0; // frames the player has played (absolute)
21let ahead = 48000;
22let horizon = 0; // frame up to which all notes are known (sent by the page)
23let running = false;
24let scheduled = false;
25let timed: { time: number; params: Params }[] = [];
26let underruns = 0;
27// load: render time / audio time, over the last ~second
28let busyMs = 0;
29let audioMs = 0;
30let lastLoadPost = 0;
32const post = (m: FromWorker) => (self as unknown as Worker).postMessage(m);
34self.onmessage = (ev: MessageEvent<ToWorker>) => {
35 const m = ev.data;
36 switch (m.type) {
37 case "init": {
38 sr = m.sampleRate;
39 synth = new Synth(sr);
40 synth.message({ type: "params", params: { ...DEFAULTS, ...m.params } });
41 port = m.port;
42 port.onmessage = (e: MessageEvent<Consumed>) => {
43 consumed = Math.max(consumed, e.data.consumed);
44 underruns = e.data.underruns;
45 pump();
46 };
47 rendered = m.startFrame;
48 consumed = m.startFrame;
49 horizon = m.startFrame;
50 ahead = m.aheadFrames;
51 running = true;
52 post({ type: "ready" });
53 pump();
54 break;
55 }
56 case "synth":
57 synth?.message(m.msg);
58 break;
59 case "horizon":
60 horizon = Math.max(horizon, Math.floor(m.time * sr));
61 pump();
62 break;
63 case "timedParams":
64 timed.push({ time: m.time, params: m.params });
65 timed.sort((a, b) => a.time - b.time);
66 break;
67 case "stop":
68 running = false;
69 port?.close();
70 break;
71 case "bench":
72 post({ type: "bench", load: bench(m) });
73 break;
74 }
75};
77function pump() {
78 if (scheduled || !running) return;
79 scheduled = true;
80 setTimeout(loop, 0);
81}
83function loop() {
84 scheduled = false;
85 if (!running || !synth || !port) return;
86 if (rendered < consumed) rendered = Math.ceil(consumed / BLOCK) * BLOCK; // never render the past
87 // far enough ahead (wait for the player), or at the edge of what the page has scheduled
88 // (wait for more notes: rendering past it would play them late)
89 if (rendered >= consumed + ahead || rendered + CHUNK > horizon) return;
90 const t0 = performance.now();
91 const L = new Float32Array(CHUNK), R = new Float32Array(CHUNK);
92 const bl = new Float32Array(BLOCK), br = new Float32Array(BLOCK);
93 for (let i = 0; i < CHUNK; i += BLOCK) {
94 const now = (rendered + i) / sr;
95 while (timed.length && timed[0].time <= now) synth.message({ type: "params", params: { ...DEFAULTS, ...timed.shift()!.params } });
96 bl.fill(0);
97 br.fill(0);
98 synth.process(bl, br, BLOCK, now);
99 L.set(bl, i);
100 R.set(br, i);
101 }
102 const chunk: Chunk = { frame: rendered, L, R };
103 port.postMessage(chunk, [L.buffer, R.buffer]);
104 rendered += CHUNK;
105 busyMs += performance.now() - t0;
106 audioMs += (CHUNK / sr) * 1000;
107 if (audioMs >= 1000 || performance.now() - lastLoadPost > 1000) {
108 post({ type: "load", load: audioMs > 0 ? busyMs / audioMs : 0, underruns });
109 busyMs = audioMs = 0;
110 lastLoadPost = performance.now();
111 }
112 pump(); // yield between chunks so incoming notes are handled before later frames are rendered
113}
115/** Device check: render a note pattern as fast as possible; returns render time / audio time. */
116function bench(m: Extract<ToWorker, { type: "bench" }>): number {
117 const s = new Synth(m.sampleRate);
118 s.message({ type: "params", params: { ...DEFAULTS, ...m.params } });
119 for (const n of m.notes) {
120 s.message({ type: "noteOn", note: n.note, vel: n.vel, time: n.time });
121 s.message({ type: "noteOff", note: n.note, time: n.time + n.len });
122 }
123 const bl = new Float32Array(BLOCK), br = new Float32Array(BLOCK);
124 const total = Math.round(m.seconds * m.sampleRate);
125 const warm = Math.round(m.warmup * m.sampleRate);
126 let t0 = performance.now();
127 for (let f = 0; f < total; f += BLOCK) {
128 if (f === Math.floor(warm / BLOCK) * BLOCK) t0 = performance.now(); // time only after warm-up (JIT, voices filling)
129 bl.fill(0);
130 br.fill(0);
131 s.process(bl, br, BLOCK, f / m.sampleRate);
132 }
133 const audio = (total - Math.floor(warm / BLOCK) * BLOCK) / m.sampleRate;
134 return (performance.now() - t0) / 1000 / audio;
135}