// A modal-synth instrument rendered in a Web Worker, ahead of playback, and streamed to a player // worklet. Same sound and interface as the direct (AudioWorklet) modal instrument, but the // synthesis runs on another core with a buffer of AHEAD seconds, so the real-time audio thread // only copies samples. Notes must be played at least AHEAD + a little before their time. import { DEFAULTS, type Params } from "@modal-synth/engine/params.ts"; import type { Msg } from "@modal-synth/engine/synth.ts"; import { PRESETS } from "@modal-synth/presets.ts"; import playerUrl from "./player.ts?worker&url"; import { fadeCurve } from "../fade.ts"; import { parseModalPreset, routeEffects } from "../modal.ts"; import type { NoteHandle, NoteInstrument, NoteInstrumentFactory } from "../types.ts"; import type { FromWorker, ToWorker } from "./protocol.ts"; /** seconds of audio kept rendered ahead of playback */ export const AHEAD = 1.0; /** how early notes must be played (scheduled) relative to their time */ export const SCHEDULE_AHEAD = AHEAD + 0.5; const NOTE_OFF_LEAD = AHEAD + 0.3; // release messages are sent this far ahead of their time const FLUSH_MS = 50; const loaded = new WeakMap>(); function loadPlayer(ctx: AudioContext): Promise { let p = loaded.get(ctx); if (!p) { p = ctx.audioWorklet.addModule(playerUrl); loaded.set(ctx, p); } return p; } export function makeStreamedFactory(preset: Params | null): NoteInstrumentFactory { return (ctx, out, opts) => { const sound: Params = { ...DEFAULTS, ...(preset ?? parseModalPreset(opts.custom) ?? {}), ...(opts.overrides ?? {}) }; const fade = ctx.createGain(); routeEffects(ctx, fade, out, sound, opts); const worker = new Worker(new URL("./renderWorker.ts", import.meta.url), { type: "module" }); const send = (m: ToWorker, transfer: Transferable[] = []) => worker.postMessage(m, transfer); let load = 0; let underruns = 0; let node: AudioWorkletNode | null = null; const ready = (async () => { await loadPlayer(ctx); node = new AudioWorkletNode(ctx, "pcm-player", { numberOfInputs: 0, outputChannelCount: [2] }); node.connect(fade); const ch = new MessageChannel(); node.port.postMessage({ type: "port", port: ch.port2 }, [ch.port2]); const workerReady = new Promise((resolve) => { worker.onmessage = (e: MessageEvent) => { if (e.data.type === "ready") resolve(); else if (e.data.type === "load") { load = e.data.load; underruns = e.data.underruns; } }; }); send( { type: "init", sampleRate: ctx.sampleRate, params: sound, port: ch.port1, startFrame: Math.round((ctx.currentTime + 0.05) * ctx.sampleRate), aheadFrames: Math.round(AHEAD * ctx.sampleRate), }, [ch.port1], ); await workerReady; })(); const synthMsg = (msg: Msg) => send({ type: "synth", msg }); // releases wait here until shortly before they're due, so the final note can be extended; // a release is skipped if the same pitch was struck again after its note began interface Off { note: number; on: number; time: number } let offs: Off[] = []; const lastOn = new Map(); const flush = () => { const horizon = ctx.currentTime + NOTE_OFF_LEAD; const keep: Off[] = []; for (const o of offs) { if (o.time > horizon) keep.push(o); else if ((lastOn.get(o.note) ?? -Infinity) <= o.on) synthMsg({ type: "noteOff", note: o.note, time: o.time }); } offs = keep; }; const timer = window.setInterval(flush, FLUSH_MS); let holding = false; const inst: NoteInstrument = { ready, load: () => load, underruns: () => underruns, horizon: (time) => send({ type: "horizon", time }), play({ when, freq, velocity, duration }) { if (velocity <= 0) return null; const note = 69 + 12 * Math.log2(freq / 440); synthMsg({ type: "noteOn", note, vel: Math.max(0.01, Math.min(1, velocity)), time: when }); if (opts.immediateRelease) { synthMsg({ type: "noteOff", note, time: when + duration }); return null; } lastOn.set(note, when); const off: Off = { note, on: when, time: when + duration }; offs.push(off); const handle: NoteHandle = { hold(from, holdLen, fadeLen) { const t = Math.max(from, ctx.currentTime); off.time = t + holdLen + fadeLen; if (holding) return; // instrument-wide: the first hold schedules it holding = true; // lengthen the decay (base and high-frequency loss alike) from `t`, as the direct // instrument does; the renderer applies it when it reaches that time const ring = holdLen + fadeLen; const t60 = Math.min(60, Math.max(sound.t60 as number, 6 * ring)); const slow = t60 / (sound.t60 as number); send({ type: "timedParams", time: t, params: { ...sound, t60, hfDamp: (sound.hfDamp as number) / slow } }); fade.gain.setValueCurveAtTime(fadeCurve(1), t + Math.max(holdLen, 0.005), fadeLen); }, }; return handle; }, dispose() { window.clearInterval(timer); send({ type: "stop" }); window.setTimeout(() => { worker.terminate(); node?.disconnect(); fade.disconnect(); }, 1000); }, }; return inst; }; } /** "modal: " → streamed factory, for every built-in preset plus "modal: custom". */ export function streamedModalInstruments(): Record { const out: Record = {}; for (const p of PRESETS) out[`modal: ${p.name}`] = makeStreamedFactory(p.p); out["modal: custom"] = makeStreamedFactory(null); return out; }