// One instrument ("stem") of a performance, rendered in its own worker: the modal-synth engine, // driven by timed commands from the score, in 128-frame blocks from a fixed piece frame, so the // result depends only on the commands (the same on every device). It renders as fast as it can, // up to whichever comes first: what the score has sent (its horizon), or the player's playhead // plus the buffer it asks for. Audio goes straight to the player. import { DEFAULTS, type Params } from "@modal-synth/engine/params.ts"; import { Synth } from "@modal-synth/engine/synth.ts"; import { BLOCK, CHUNK, SAMPLE_RATE, type Clock, type ScoreToSynth, type SynthCmd, type SynthInit, type ToPlayer } from "./protocol.ts"; const NORM_REF = 0.3; // normalized loudness: level 1 ≈ this RMS const NORM_TAU = 1.5; // s const NORM_RANGE = 20; // compensation limited to ×1/20 … ×20 let synth: Synth; let sound: Params; let cur: Params; // sound with the latest timed changes let stem = 0; let player: MessagePort; let rendered = 0; // next piece frame to render let sendFrame = 0; let horizon = 0; // frame: every command before it has arrived let endFrame = Infinity; let playhead = 0; let ahead = 4 * SAMPLE_RATE; let doneSent = false; const cmds: SynthCmd[] = []; const lastOn = new Map(); // pitch → when it was last struck let scheduled = false; let slow = 1; // output gain (hum levels), loudness normalization, and the final-note fade let gain = 1, gainTarget = 1, gainTau = 0, normalize = false; let msq = NORM_REF * NORM_REF; let holding = false; let fadeFrom = Infinity, fadeLen = 1; // s self.onmessage = (e: MessageEvent) => { const m = e.data; if (m.type !== "init") return; sound = { ...DEFAULTS, ...m.sound }; cur = sound; synth = new Synth(SAMPLE_RATE); synth.message({ type: "params", params: sound }); stem = m.stem; slow = Math.max(1, m.slow ?? 1); rendered = m.fromFrame; horizon = m.fromFrame; sendFrame = m.sendFrame; playhead = m.sendFrame; player = m.playerPort; player.onmessage = (ev: MessageEvent) => { playhead = ev.data.playhead; ahead = ev.data.ahead; pump(); }; m.scorePort.onmessage = (ev: MessageEvent) => { const d = ev.data; if (d.type === "cmds") { for (const c of d.cmds) cmds.push(c); horizon = Math.max(horizon, Math.floor(d.horizon * SAMPLE_RATE)); } else if (d.type === "end") { endFrame = Math.round(d.t * SAMPLE_RATE); horizon = Math.max(horizon, endFrame); } pump(); }; }; function pump() { if (scheduled) return; scheduled = true; setTimeout(loop, 0); } function apply(c: SynthCmd) { switch (c.type) { case "noteOn": synth.message({ type: "noteOn", note: c.note, vel: c.vel }); lastOn.set(c.note, c.t); break; case "noteOff": // notes are identified by pitch: a release from before a re-strike would cut the new note if (c.on !== undefined && (lastOn.get(c.note) ?? -Infinity) > c.on) break; synth.message({ type: "noteOff", note: c.note }); break; case "params": cur = { ...cur, ...c.params }; synth.message({ type: "params", params: cur }); break; case "bend": synth.message({ type: "bend", value: c.value }); break; case "gain": gainTarget = c.value; gainTau = c.tau; normalize = !!c.normalize; break; case "hold": { if (holding) break; // instrument-wide: the first hold sets it up holding = true; // a struck body decays by itself: slow its decay (base and high-frequency loss alike, so the // tone color stays) so it rings through the hold and fade const ring = c.hold + c.fade; const t60 = Math.min(60, Math.max(sound.t60 as number, 6 * ring)); const slow = t60 / (sound.t60 as number); cur = { ...cur, t60, hfDamp: (sound.hfDamp as number) / slow }; synth.message({ type: "params", params: cur }); fadeFrom = c.t + Math.max(c.hold, 0.005); fadeLen = Math.max(0.01, c.fade); break; } } } const bl = new Float32Array(BLOCK), br = new Float32Array(BLOCK); function renderBlock(L: Float32Array, R: Float32Array, at: number) { const now = rendered / SAMPLE_RATE; const blockEnd = (rendered + BLOCK) / SAMPLE_RATE; // commands due in this block apply at its start (block-accurate, like the synth's own timing) while (cmds.length && cmds[0].t < blockEnd) apply(cmds.shift()!); bl.fill(0); br.fill(0); synth.process(bl, br, BLOCK, now); if (normalize) { let s = 0; for (let i = 0; i < BLOCK; i++) s += bl[i] * bl[i] + br[i] * br[i]; s /= 2 * BLOCK; if (s > 1e-10) msq += (s - msq) * (1 - Math.exp(-BLOCK / SAMPLE_RATE / NORM_TAU)); } const comp = normalize ? Math.max(1 / NORM_RANGE, Math.min(NORM_RANGE, NORM_REF / Math.sqrt(msq))) : 1; const target = gainTarget * comp; const g0 = gain; gain = gainTau > 0 ? gain + (target - gain) * (1 - Math.exp(-BLOCK / SAMPLE_RATE / gainTau)) : target; for (let i = 0; i < BLOCK; i++) { let g = g0 + ((gain - g0) * (i + 1)) / BLOCK; const t = (rendered + i) / SAMPLE_RATE; if (t >= fadeFrom) { const u = Math.min(1, (t - fadeFrom) / fadeLen); const c = Math.cos((Math.PI / 2) * u); g *= c * c; } L[at + i] = bl[i] * g; R[at + i] = br[i] * g; } rendered += BLOCK; } function loop() { scheduled = false; if (!synth) return; if (rendered >= endFrame) { if (!doneSent) { doneSent = true; post({ type: "done", stem, frame: endFrame }); } return; } // render whole blocks, up to what the score has sent, the buffer the player wants, and the end const cap = Math.min(horizon, playhead + ahead, endFrame + BLOCK - 1); const n = Math.min(CHUNK, Math.floor((cap - rendered) / BLOCK) * BLOCK); if (n <= 0) return; const frame = rendered; const L = new Float32Array(n), R = new Float32Array(n); const t0 = performance.now(); for (let i = 0; i < n; i += BLOCK) renderBlock(L, R, i); if (slow > 1) { const until = performance.now() + (slow - 1) * (performance.now() - t0); while (performance.now() < until); // testing only: pretend to be a slower device } if (frame + n > sendFrame) { const off = Math.max(0, sendFrame - frame); const l = off ? L.slice(off) : L, r = off ? R.slice(off) : R; post({ type: "chunk", stem, frame: frame + off, L: l, R: r }, [l.buffer, r.buffer]); } pump(); // yield between chunks so new commands and the clock get through } function post(m: ToPlayer, transfer: Transferable[] = []) { player.postMessage(m, transfer); }