1// Instruments from the sibling modal-synth project (coupled nonlinear modal oscillators),
2// imported live via the @modal-synth alias. Each instrument instance is one AudioWorklet synth
3// (up to 16 voices) followed by modal-synth's own effects (saturation, delay, reverb).
5import { FX } from "@modal-synth/audio/fx.ts";
6import workletUrl from "@modal-synth/audio/worklet.ts?worker&url";
7import { DEFAULTS, PARAM_BY_ID, type Params } from "@modal-synth/engine/params.ts";
8import type { Msg } from "@modal-synth/engine/synth.ts";
9import { PRESETS } from "@modal-synth/presets.ts";
10import { fadeCurve } from "./fade.ts";
11import type { DroneInstrumentFactory, NoteHandle, NoteInstrument, NoteInstrumentFactory } from "./types.ts";
13const loaded = new WeakMap<BaseAudioContext, Promise<void>>();
14function loadWorklet(ctx: AudioContext): Promise<void> {
15 let p = loaded.get(ctx);
16 if (!p) {
17 p = ctx.audioWorklet.addModule(workletUrl);
18 loaded.set(ctx, p);
19 }
20 return p;
21}
23/** Parse a pasted preset (the JSON from modal-synth's Copy button). */
24export function parseModalPreset(text: string | undefined): Params | null {
25 if (!text || !text.trim()) return null;
26 try {
27 const v = JSON.parse(text);
28 return v && typeof v === "object" && !Array.isArray(v) ? (v as Params) : null;
29 } catch {
30 return null;
31 }
32}
34const NOTE_OFF_LEAD = 0.2; // post noteOffs to the worklet this far ahead of their time
35const FLUSH_MS = 25;
37export function makeModalFactory(preset: Params | null): NoteInstrumentFactory {
38 return (ctx, out, opts) => {
39 const sound: Params = { ...DEFAULTS, ...(preset ?? parseModalPreset(opts.custom) ?? {}) };
41 // synth → fade (used by the final-note hold) → modal-synth FX → our output
42 const fade = ctx.createGain();
43 const fx = new FX(ctx, out);
44 fade.connect(fx.input);
45 fx.set(sound);
47 let node: AudioWorkletNode | null = null;
48 let cpu = 0; // smoothed audio-thread load of this synth
49 const early: Msg[] = [];
50 const post = (m: Msg) => (node ? node.port.postMessage(m) : early.push(m));
52 const ready = loadWorklet(ctx).then(() => {
53 node = new AudioWorkletNode(ctx, "modal-synth", { numberOfInputs: 0, outputChannelCount: [2] });
54 // snapshots (30/s) carry the synth's own measure of its processing time / real time
55 node.port.onmessage = (e: MessageEvent<{ type?: string; cpu?: number }>) => {
56 if (e.data?.type === "snap" && typeof e.data.cpu === "number") cpu += (e.data.cpu - cpu) * 0.2;
57 };
58 node.port.postMessage({ type: "params", params: sound } satisfies Msg);
59 for (const m of early.splice(0)) node.port.postMessage(m);
60 node.connect(fade);
61 });
63 // noteOffs are held here until shortly before they're due, so the final note can be extended.
64 // Notes are identified by pitch in the synth; a noteOff is skipped if the same pitch was
65 // re-struck after its noteOn (the newer note has its own noteOff).
66 interface Off { note: number; on: number; time: number }
67 let offs: Off[] = [];
68 const lastOn = new Map<number, number>();
69 const flush = () => {
70 const horizon = ctx.currentTime + NOTE_OFF_LEAD;
71 const keep: Off[] = [];
72 for (const o of offs) {
73 if (o.time > horizon) keep.push(o);
74 else if ((lastOn.get(o.note) ?? -Infinity) <= o.on) post({ type: "noteOff", note: o.note, time: o.time });
75 }
76 offs = keep;
77 };
78 const timer = window.setInterval(flush, FLUSH_MS);
79 const offline = typeof OfflineAudioContext !== "undefined" && (ctx as BaseAudioContext) instanceof OfflineAudioContext;
80 const immediate = offline || !!opts.immediateRelease;
81 let holding = false;
83 const inst: NoteInstrument = {
84 ready,
85 load: () => cpu,
86 play({ when, freq, velocity, duration }) {
87 if (velocity <= 0) return null;
88 const note = 69 + 12 * Math.log2(freq / 440);
89 post({ type: "noteOn", note, vel: Math.max(0.01, Math.min(1, velocity)), time: when });
90 if (immediate) {
91 // device checks (and offline renders, which can't run the release timer): release now
92 post({ type: "noteOff", note, time: when + duration });
93 return null;
94 }
95 lastOn.set(note, when);
96 const off: Off = { note, on: when, time: when + duration };
97 offs.push(off);
98 const handle: NoteHandle = {
99 hold(from, holdLen, fadeLen) {
100 const t = Math.max(from, ctx.currentTime);
101 const ring = holdLen + fadeLen;
102 // keep the damper off through the whole hold and fade (if still queued, the release moves later)
103 off.time = t + ring;
104 // the decay change and fade are instrument-wide: when several voices (orbits) end on this
105 // instrument, the first hold schedules them and later ones just keep their dampers off
106 if (holding) return;
107 holding = true;
108 // a plucked or struck body decays by itself: lengthen its decay so it really rings through
109 // the hold. Only the final note is sounding by then, so the instrument-wide change is safe.
110 // Both the base decay (t60) and the frequency-dependent loss (hfDamp) are slowed by the same
111 // factor, so the note keeps its tone color while it rings.
112 const t60 = Math.min(60, Math.max(sound.t60 as number, 6 * ring));
113 const slow = t60 / (sound.t60 as number);
114 const ringing: Params = { ...sound, t60, hfDamp: (sound.hfDamp as number) / slow };
115 window.setTimeout(() => post({ type: "params", params: ringing }), Math.max(0, (t - ctx.currentTime) * 1000));
116 fade.gain.setValueCurveAtTime(fadeCurve(1), t + Math.max(holdLen, 0.005), fadeLen);
117 },
118 };
119 return handle;
120 },
121 dispose() {
122 window.clearInterval(timer);
123 post({ type: "panic" });
124 window.setTimeout(() => {
125 node?.disconnect();
126 node?.port.close();
127 fade.disconnect();
128 }, 1000);
129 },
130 };
131 return inst;
132 };
133}
135/** Menu name → factory, for every built-in modal-synth preset plus "modal: custom". */
136export function modalInstruments(): Record<string, NoteInstrumentFactory> {
137 const out: Record<string, NoteInstrumentFactory> = {};
138 for (const p of PRESETS) out[`modal: ${p.name}`] = makeModalFactory(p.p);
139 out["modal: custom"] = makeModalFactory(null);
140 return out;
141}
143// ── drones: one held note of a sustained preset, with color mapped onto synth settings ──
145/** Settings the synth reads every block, so they can follow the energy while a note is held. */
146export const LIVE_TARGETS = [
147 "bowForce", "bowSpeed", "bowNoise", "exPos", "reedPressure", "reedGain", "breath",
148 "selfGain", "selfSat", "noiseLevel", "noiseColor", "tension", "cascade", "curvature",
149 "fbGain", "fbFreq", "fbQ", "fbSat", "hfDamp", "t60", "pickup", "tilt", "vibDepth",
150];
152/** 0..1 → a modal-synth setting's value, following that setting's own slider scale. */
153export function targetValue(id: string, u: number): number {
154 const d = PARAM_BY_ID[id];
155 if (!d || d.kind !== "num") return NaN;
156 const x = Math.max(0, Math.min(1, u));
157 if (d.scale === "log") return d.min * Math.pow(d.max / d.min, x);
158 if (d.scale === "pow2") return d.min + (d.max - d.min) * x * x;
159 return d.min + (d.max - d.min) * x;
160}
162const SUSTAINED_EXCITERS = ["bow", "reed", "selfosc", "noise"];
163const DRONE_UPDATE_MS = 50; // at most this often, a "params" message to the worklet
164const NORM_REF = 0.3; // with normalize on, level 1 ≈ this RMS (about the placeholder hum's)
165const NORM_TAU = 1.5; // seconds: how slowly the loudness compensation follows
166const NORM_RANGE = 20; // compensation limited to ×1/20 … ×20
168export function makeModalDroneFactory(preset: Params | null): DroneInstrumentFactory {
169 return (ctx, out, opts) => {
170 const base: Params = { ...DEFAULTS, ...(preset ?? parseModalPreset(opts.custom) ?? {}), voices: 1 };
171 const gain = ctx.createGain();
172 gain.gain.value = 0;
173 const fx = new FX(ctx, out);
174 gain.connect(fx.input);
175 fx.set(base);
176 // loudness meter on the raw synth output, for normalization
177 const meter = ctx.createAnalyser();
178 meter.fftSize = 2048;
179 const buf = new Float32Array(meter.fftSize);
180 let msq = NORM_REF * NORM_REF; // smoothed mean square
181 let lastMeter = 0;
182 let comp = 1;
184 let node: AudioWorkletNode | null = null;
185 let cpu = 0; // smoothed audio-thread load of this synth
186 const early: Msg[] = [];
187 const post = (m: Msg) => (node ? node.port.postMessage(m) : early.push(m));
188 const ready = loadWorklet(ctx).then(() => {
189 node = new AudioWorkletNode(ctx, "modal-synth", { numberOfInputs: 0, outputChannelCount: [2] });
190 node.port.onmessage = (e: MessageEvent<{ type?: string; cpu?: number }>) => {
191 if (e.data?.type === "snap" && typeof e.data.cpu === "number") cpu += (e.data.cpu - cpu) * 0.2;
192 };
193 node.port.postMessage({ type: "params", params: base } satisfies Msg);
194 for (const m of early.splice(0)) node.port.postMessage(m);
195 node.connect(gain);
196 node.connect(meter);
197 });
199 let note: number | null = null;
200 let sent: Params = base;
201 let lastPost = 0;
202 let desc = "";
203 const midi = (f: number) => 69 + 12 * Math.log2(f / 440);
205 return {
206 ready,
207 load: () => cpu,
208 start(when, freq) {
209 note = midi(freq);
210 post({ type: "noteOn", note, vel: 1, time: when });
211 },
212 stop(when, release) {
213 const t = Math.max(ctx.currentTime, when - release);
214 gain.gain.cancelScheduledValues(t);
215 gain.gain.setTargetAtTime(0, t, release / 4);
216 if (note !== null) post({ type: "noteOff", note, time: t });
217 note = null;
218 },
219 set(when, { level, color, freq, timbre, normalize }) {
220 // loudness normalization: follow the measured level slowly, compensate toward NORM_REF
221 const now = performance.now() / 1000;
222 const dt = lastMeter ? Math.min(0.5, now - lastMeter) : 0;
223 lastMeter = now;
224 if (normalize && node) {
225 meter.getFloatTimeDomainData(buf);
226 let s = 0;
227 for (const x of buf) s += x * x;
228 s /= buf.length;
229 if (s > 1e-10) msq += (s - msq) * (1 - Math.exp(-dt / NORM_TAU));
230 comp = Math.max(1 / NORM_RANGE, Math.min(NORM_RANGE, NORM_REF / Math.sqrt(msq)));
231 } else comp = 1;
232 gain.gain.setTargetAtTime(level * comp, when, 0.08);
233 // retune by restarting the note if the pitch setting moved
234 const m = midi(freq);
235 if (note !== null && Math.abs(m - note) > 0.01) {
236 post({ type: "noteOff", note, time: when });
237 note = m;
238 post({ type: "noteOn", note, vel: 1, time: when });
239 }
240 // color → mapped settings, throttled
241 const wall = performance.now();
242 if (!timbre?.length || wall - lastPost < DRONE_UPDATE_MS) return;
243 const next: Params = { ...base };
244 const parts: string[] = [];
245 let changed = false;
246 for (const tm of timbre) {
247 if (!LIVE_TARGETS.includes(tm.target)) continue;
248 const v = targetValue(tm.target, tm.from + (tm.to - tm.from) * color);
249 if (!Number.isFinite(v)) continue;
250 next[tm.target] = v;
251 parts.push(`${tm.target} ${Number(v.toPrecision(3))}`);
252 const d = PARAM_BY_ID[tm.target] as { min: number; max: number };
253 if (Math.abs(v - (sent[tm.target] as number)) > 0.002 * (d.max - d.min)) changed = true;
254 }
255 desc = parts.join(", ");
256 if (!changed) return;
257 sent = next;
258 lastPost = wall;
259 post({ type: "params", params: next });
260 },
261 describe: () => (comp !== 1 ? `${desc}${desc ? ", " : ""}gain ${(20 * Math.log10(comp)).toFixed(1)} dB` : desc),
262 dispose() {
263 post({ type: "panic" });
264 window.setTimeout(() => {
265 node?.disconnect();
266 node?.port.close();
267 gain.disconnect();
268 }, 1000);
269 },
270 };
271 };
272}
274/** Sustained presets (bowed, blown, self-oscillating, fed back) as "modal: <name>", plus "modal: custom". */
275export function modalDrones(): Record<string, DroneInstrumentFactory> {
276 const out: Record<string, DroneInstrumentFactory> = {};
277 for (const p of PRESETS) {
278 const q = { ...DEFAULTS, ...p.p };
279 if (SUSTAINED_EXCITERS.includes(q.exciter as string) || (q.fbGain as number) > 0) out[`modal: ${p.name}`] = makeModalDroneFactory(p.p);
280 }
281 out["modal: custom"] = makeModalDroneFactory(null);
282 return out;
283}