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