// Renders one modal-synth instrument off the real-time audio thread, ahead of playback. // // The synth is the same engine the AudioWorklet runs. Here it renders chunks of audio up to // `aheadFrames` beyond what the player has consumed, and posts them straight to the player's port. // Several of these workers run in parallel, one per instrument, on the device's other cores. // Notes arrive early (the page simulates ahead) with absolute audio-context times; the synth // applies them at the exact sample. import { DEFAULTS, type Params } from "@modal-synth/engine/params.ts"; import { Synth } from "@modal-synth/engine/synth.ts"; import type { Chunk, Consumed, FromWorker, ToWorker } from "./protocol.ts"; const BLOCK = 128; const CHUNK = 1024; // frames per posted chunk (~21 ms) let synth: Synth | null = null; let sr = 48000; let port: MessagePort | null = null; let rendered = 0; // next frame to render (absolute) let consumed = 0; // frames the player has played (absolute) let ahead = 48000; let horizon = 0; // frame up to which all notes are known (sent by the page) let running = false; let scheduled = false; let timed: { time: number; params: Params }[] = []; let underruns = 0; // load: render time / audio time, over the last ~second let busyMs = 0; let audioMs = 0; let lastLoadPost = 0; const post = (m: FromWorker) => (self as unknown as Worker).postMessage(m); self.onmessage = (ev: MessageEvent) => { const m = ev.data; switch (m.type) { case "init": { sr = m.sampleRate; synth = new Synth(sr); synth.message({ type: "params", params: { ...DEFAULTS, ...m.params } }); port = m.port; port.onmessage = (e: MessageEvent) => { consumed = Math.max(consumed, e.data.consumed); underruns = e.data.underruns; pump(); }; rendered = m.startFrame; consumed = m.startFrame; horizon = m.startFrame; ahead = m.aheadFrames; running = true; post({ type: "ready" }); pump(); break; } case "synth": synth?.message(m.msg); break; case "horizon": horizon = Math.max(horizon, Math.floor(m.time * sr)); pump(); break; case "timedParams": timed.push({ time: m.time, params: m.params }); timed.sort((a, b) => a.time - b.time); break; case "stop": running = false; port?.close(); break; case "bench": post({ type: "bench", load: bench(m) }); break; } }; function pump() { if (scheduled || !running) return; scheduled = true; setTimeout(loop, 0); } function loop() { scheduled = false; if (!running || !synth || !port) return; if (rendered < consumed) rendered = Math.ceil(consumed / BLOCK) * BLOCK; // never render the past // far enough ahead (wait for the player), or at the edge of what the page has scheduled // (wait for more notes: rendering past it would play them late) if (rendered >= consumed + ahead || rendered + CHUNK > horizon) return; const t0 = performance.now(); const L = new Float32Array(CHUNK), R = new Float32Array(CHUNK); const bl = new Float32Array(BLOCK), br = new Float32Array(BLOCK); for (let i = 0; i < CHUNK; i += BLOCK) { const now = (rendered + i) / sr; while (timed.length && timed[0].time <= now) synth.message({ type: "params", params: { ...DEFAULTS, ...timed.shift()!.params } }); bl.fill(0); br.fill(0); synth.process(bl, br, BLOCK, now); L.set(bl, i); R.set(br, i); } const chunk: Chunk = { frame: rendered, L, R }; port.postMessage(chunk, [L.buffer, R.buffer]); rendered += CHUNK; busyMs += performance.now() - t0; audioMs += (CHUNK / sr) * 1000; if (audioMs >= 1000 || performance.now() - lastLoadPost > 1000) { post({ type: "load", load: audioMs > 0 ? busyMs / audioMs : 0, underruns }); busyMs = audioMs = 0; lastLoadPost = performance.now(); } pump(); // yield between chunks so incoming notes are handled before later frames are rendered } /** Device check: render a note pattern as fast as possible; returns render time / audio time. */ function bench(m: Extract): number { const s = new Synth(m.sampleRate); s.message({ type: "params", params: { ...DEFAULTS, ...m.params } }); for (const n of m.notes) { s.message({ type: "noteOn", note: n.note, vel: n.vel, time: n.time }); s.message({ type: "noteOff", note: n.note, time: n.time + n.len }); } const bl = new Float32Array(BLOCK), br = new Float32Array(BLOCK); const total = Math.round(m.seconds * m.sampleRate); const warm = Math.round(m.warmup * m.sampleRate); let t0 = performance.now(); for (let f = 0; f < total; f += BLOCK) { if (f === Math.floor(warm / BLOCK) * BLOCK) t0 = performance.now(); // time only after warm-up (JIT, voices filling) bl.fill(0); br.fill(0); s.process(bl, br, BLOCK, f / m.sampleRate); } const audio = (total - Math.floor(warm / BLOCK) * BLOCK) / m.sampleRate; return (performance.now() - t0) / 1000 / audio; }