1// A modal-synth instrument rendered in a Web Worker, ahead of playback, and streamed to a player
2// worklet. Same sound and interface as the direct (AudioWorklet) modal instrument, but the
3// synthesis runs on another core with a buffer of AHEAD seconds, so the real-time audio thread
4// only copies samples. Notes must be played at least AHEAD + a little before their time.
5// Each instrument measures what one voice costs on this device (once, remembered) and caps its
6// polyphony to fit, so a burst of notes can't push its renderer past real time.
8import { DEFAULTS, type Params } from "@modal-synth/engine/params.ts";
9import type { Msg } from "@modal-synth/engine/synth.ts";
10import { PRESETS } from "@modal-synth/presets.ts";
11import playerUrl from "./player.ts?worker&url";
12import { fadeCurve } from "../fade.ts";
13import { voiceCost, voicesThatFit } from "./capacity.ts";
14import { parseModalPreset, routeEffects } from "../modal.ts";
15import type { NoteHandle, NoteInstrument, NoteInstrumentFactory } from "../types.ts";
16import type { FromWorker, ToWorker } from "./protocol.ts";
18/** seconds of audio kept rendered ahead of playback */
19export const AHEAD = 2.0;
20/** how early notes must be played (scheduled) relative to their time */
21export const SCHEDULE_AHEAD = AHEAD + 0.5;
22const NOTE_OFF_LEAD = AHEAD + 0.3; // release messages are sent this far ahead of their time
23const FLUSH_MS = 50;
25const loaded = new WeakMap<BaseAudioContext, Promise<void>>();
26function loadPlayer(ctx: AudioContext): Promise<void> {
27 let p = loaded.get(ctx);
28 if (!p) {
29 p = ctx.audioWorklet.addModule(playerUrl);
30 loaded.set(ctx, p);
31 }
32 return p;
33}
35export function makeStreamedFactory(preset: Params | null): NoteInstrumentFactory {
36 return (ctx, out, opts) => {
37 const sound: Params = { ...DEFAULTS, ...(preset ?? parseModalPreset(opts.custom) ?? {}), ...(opts.overrides ?? {}) };
38 const fade = ctx.createGain();
39 routeEffects(ctx, fade, out, sound, opts);
41 const worker = new Worker(new URL("./renderWorker.ts", import.meta.url), { type: "module" });
42 const send = (m: ToWorker, transfer: Transferable[] = []) => worker.postMessage(m, transfer);
43 let load = 0;
44 let underruns = 0;
45 const wanted = Math.round(sound.voices as number);
46 let allowed = wanted;
47 let node: AudioWorkletNode | null = null;
48 const ready = (async () => {
49 const [perVoice] = await Promise.all([voiceCost({ ...sound, voices: 1 }, ctx.sampleRate), loadPlayer(ctx)]);
50 allowed = voicesThatFit(perVoice, wanted);
51 node = new AudioWorkletNode(ctx, "pcm-player", { numberOfInputs: 0, outputChannelCount: [2] });
52 node.connect(fade);
53 const ch = new MessageChannel();
54 node.port.postMessage({ type: "port", port: ch.port2 }, [ch.port2]);
55 const workerReady = new Promise<void>((resolve) => {
56 worker.onmessage = (e: MessageEvent<FromWorker>) => {
57 if (e.data.type === "ready") resolve();
58 else if (e.data.type === "load") {
59 load = e.data.load;
60 underruns = e.data.underruns;
61 }
62 };
63 });
64 send(
65 {
66 type: "init",
67 sampleRate: ctx.sampleRate,
68 params: { ...sound, voices: allowed },
69 port: ch.port1,
70 startFrame: Math.round((ctx.currentTime + 0.05) * ctx.sampleRate),
71 aheadFrames: Math.round(AHEAD * ctx.sampleRate),
72 },
73 [ch.port1],
74 );
75 await workerReady;
76 })();
78 const synthMsg = (msg: Msg) => send({ type: "synth", msg });
80 // releases wait here until shortly before they're due, so the final note can be extended;
81 // a release is skipped if the same pitch was struck again after its note began
82 interface Off { note: number; on: number; time: number }
83 let offs: Off[] = [];
84 const lastOn = new Map<number, number>();
85 const flush = () => {
86 const horizon = ctx.currentTime + NOTE_OFF_LEAD;
87 const keep: Off[] = [];
88 for (const o of offs) {
89 if (o.time > horizon) keep.push(o);
90 else if ((lastOn.get(o.note) ?? -Infinity) <= o.on) synthMsg({ type: "noteOff", note: o.note, time: o.time });
91 }
92 offs = keep;
93 };
94 const timer = window.setInterval(flush, FLUSH_MS);
95 let holding = false;
97 const inst: NoteInstrument = {
98 ready,
99 load: () => load,
100 underruns: () => underruns,
101 voices: () => ({ allowed, wanted }),
102 horizon: (time) => send({ type: "horizon", time }),
103 play({ when, freq, velocity, duration }) {
104 if (velocity <= 0) return null;
105 const note = 69 + 12 * Math.log2(freq / 440);
106 synthMsg({ type: "noteOn", note, vel: Math.max(0.01, Math.min(1, velocity)), time: when });
107 if (opts.immediateRelease) {
108 synthMsg({ type: "noteOff", note, time: when + duration });
109 return null;
110 }
111 lastOn.set(note, when);
112 const off: Off = { note, on: when, time: when + duration };
113 offs.push(off);
114 const handle: NoteHandle = {
115 hold(from, holdLen, fadeLen) {
116 const t = Math.max(from, ctx.currentTime);
117 off.time = t + holdLen + fadeLen;
118 if (holding) return; // instrument-wide: the first hold schedules it
119 holding = true;
120 // lengthen the decay (base and high-frequency loss alike) from `t`, as the direct
121 // instrument does; the renderer applies it when it reaches that time
122 const ring = holdLen + fadeLen;
123 const t60 = Math.min(60, Math.max(sound.t60 as number, 6 * ring));
124 const slow = t60 / (sound.t60 as number);
125 send({ type: "timedParams", time: t, params: { ...sound, voices: allowed, t60, hfDamp: (sound.hfDamp as number) / slow } });
126 fade.gain.setValueCurveAtTime(fadeCurve(1), t + Math.max(holdLen, 0.005), fadeLen);
127 },
128 };
129 return handle;
130 },
131 dispose() {
132 window.clearInterval(timer);
133 send({ type: "stop" });
134 window.setTimeout(() => {
135 worker.terminate();
136 node?.disconnect();
137 fade.disconnect();
138 }, 1000);
139 },
140 };
141 return inst;
142 };
143}
145/** "modal: <name>" → streamed factory, for every built-in preset plus "modal: custom". */
146export function streamedModalInstruments(): Record<string, NoteInstrumentFactory> {
147 const out: Record<string, NoteInstrumentFactory> = {};
148 for (const p of PRESETS) out[`modal: ${p.name}`] = makeStreamedFactory(p.p);
149 out["modal: custom"] = makeStreamedFactory(null);
150 return out;
151}