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