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 const early: Msg[] = [];
49 const post = (m: Msg) => (node ? node.port.postMessage(m) : early.push(m));
51 const ready = loadWorklet(ctx).then(() => {
52 node = new AudioWorkletNode(ctx, "modal-synth", { numberOfInputs: 0, outputChannelCount: [2] });
53 node.port.onmessage = () => {}; // snapshots for modal-synth's views; not needed here
54 node.port.postMessage({ type: "params", params: sound } satisfies Msg);
55 for (const m of early.splice(0)) node.port.postMessage(m);
56 node.connect(fade);
57 });
59 // noteOffs are held here until shortly before they're due, so the final note can be extended.
60 // Notes are identified by pitch in the synth; a noteOff is skipped if the same pitch was
61 // re-struck after its noteOn (the newer note has its own noteOff).
62 interface Off { note: number; on: number; time: number }
63 let offs: Off[] = [];
64 const lastOn = new Map<number, number>();
65 const flush = () => {
66 const horizon = ctx.currentTime + NOTE_OFF_LEAD;
67 const keep: Off[] = [];
68 for (const o of offs) {
69 if (o.time > horizon) keep.push(o);
70 else if ((lastOn.get(o.note) ?? -Infinity) <= o.on) post({ type: "noteOff", note: o.note, time: o.time });
71 }
72 offs = keep;
73 };
74 const timer = window.setInterval(flush, FLUSH_MS);
76 const inst: NoteInstrument = {
77 ready,
78 play({ when, freq, velocity, duration }) {
79 if (velocity <= 0) return null;
80 const note = 69 + 12 * Math.log2(freq / 440);
81 post({ type: "noteOn", note, vel: Math.max(0.01, Math.min(1, velocity)), time: when });
82 lastOn.set(note, when);
83 const off: Off = { note, on: when, time: when + duration };
84 offs.push(off);
85 const handle: NoteHandle = {
86 hold(from, holdLen, fadeLen) {
87 const t = Math.max(from, ctx.currentTime);
88 const ring = holdLen + fadeLen;
89 // keep the damper off through the whole hold and fade (if still queued, the release moves later)
90 off.time = t + ring;
91 // a plucked or struck body decays by itself: lengthen its decay so it really rings through
92 // the hold. Only the final note is sounding by then, so the instrument-wide change is safe.
93 // Both the base decay (t60) and the frequency-dependent loss (hfDamp) are slowed by the same
94 // factor, so the note keeps its tone color while it rings.
95 const t60 = Math.min(60, Math.max(sound.t60 as number, 6 * ring));
96 const slow = t60 / (sound.t60 as number);
97 const ringing: Params = { ...sound, t60, hfDamp: (sound.hfDamp as number) / slow };
98 window.setTimeout(() => post({ type: "params", params: ringing }), Math.max(0, (t - ctx.currentTime) * 1000));
99 fade.gain.setValueCurveAtTime(fadeCurve(1), t + Math.max(holdLen, 0.005), fadeLen);
100 },
101 };
102 return handle;
103 },
104 dispose() {
105 window.clearInterval(timer);
106 post({ type: "panic" });
107 window.setTimeout(() => {
108 node?.disconnect();
109 node?.port.close();
110 fade.disconnect();
111 }, 1000);
112 },
113 };
114 return inst;
115 };
116}
118/** Menu name → factory, for every built-in modal-synth preset plus "modal: custom". */
119export function modalInstruments(): Record<string, NoteInstrumentFactory> {
120 const out: Record<string, NoteInstrumentFactory> = {};
121 for (const p of PRESETS) out[`modal: ${p.name}`] = makeModalFactory(p.p);
122 out["modal: custom"] = makeModalFactory(null);
123 return out;
124}
126// ── drones: one held note of a sustained preset, with color mapped onto synth settings ──
128/** Settings the synth reads every block, so they can follow the energy while a note is held. */
129export const LIVE_TARGETS = [
130 "bowForce", "bowSpeed", "bowNoise", "exPos", "reedPressure", "reedGain", "breath",
131 "selfGain", "selfSat", "noiseLevel", "noiseColor", "tension", "cascade", "curvature",
132 "fbGain", "fbFreq", "fbQ", "fbSat", "hfDamp", "t60", "pickup", "tilt", "vibDepth",
133];
135/** 0..1 → a modal-synth setting's value, following that setting's own slider scale. */
136export function targetValue(id: string, u: number): number {
137 const d = PARAM_BY_ID[id];
138 if (!d || d.kind !== "num") return NaN;
139 const x = Math.max(0, Math.min(1, u));
140 if (d.scale === "log") return d.min * Math.pow(d.max / d.min, x);
141 if (d.scale === "pow2") return d.min + (d.max - d.min) * x * x;
142 return d.min + (d.max - d.min) * x;
143}
145const SUSTAINED_EXCITERS = ["bow", "reed", "selfosc", "noise"];
146const DRONE_UPDATE_MS = 50; // at most this often, a "params" message to the worklet
147const NORM_REF = 0.3; // with normalize on, level 1 ≈ this RMS (about the placeholder hum's)
148const NORM_TAU = 1.5; // seconds: how slowly the loudness compensation follows
149const NORM_RANGE = 20; // compensation limited to ×1/20 … ×20
151export function makeModalDroneFactory(preset: Params | null): DroneInstrumentFactory {
152 return (ctx, out, opts) => {
153 const base: Params = { ...DEFAULTS, ...(preset ?? parseModalPreset(opts.custom) ?? {}), voices: 1 };
154 const gain = ctx.createGain();
155 gain.gain.value = 0;
156 const fx = new FX(ctx, out);
157 gain.connect(fx.input);
158 fx.set(base);
159 // loudness meter on the raw synth output, for normalization
160 const meter = ctx.createAnalyser();
161 meter.fftSize = 2048;
162 const buf = new Float32Array(meter.fftSize);
163 let msq = NORM_REF * NORM_REF; // smoothed mean square
164 let lastMeter = 0;
165 let comp = 1;
167 let node: AudioWorkletNode | null = null;
168 const early: Msg[] = [];
169 const post = (m: Msg) => (node ? node.port.postMessage(m) : early.push(m));
170 const ready = loadWorklet(ctx).then(() => {
171 node = new AudioWorkletNode(ctx, "modal-synth", { numberOfInputs: 0, outputChannelCount: [2] });
172 node.port.onmessage = () => {};
173 node.port.postMessage({ type: "params", params: base } satisfies Msg);
174 for (const m of early.splice(0)) node.port.postMessage(m);
175 node.connect(gain);
176 node.connect(meter);
177 });
179 let note: number | null = null;
180 let sent: Params = base;
181 let lastPost = 0;
182 let desc = "";
183 const midi = (f: number) => 69 + 12 * Math.log2(f / 440);
185 return {
186 ready,
187 start(when, freq) {
188 note = midi(freq);
189 post({ type: "noteOn", note, vel: 1, time: when });
190 },
191 stop(when, release) {
192 const t = Math.max(ctx.currentTime, when - release);
193 gain.gain.cancelScheduledValues(t);
194 gain.gain.setTargetAtTime(0, t, release / 4);
195 if (note !== null) post({ type: "noteOff", note, time: t });
196 note = null;
197 },
198 set(when, { level, color, freq, timbre, normalize }) {
199 // loudness normalization: follow the measured level slowly, compensate toward NORM_REF
200 const now = performance.now() / 1000;
201 const dt = lastMeter ? Math.min(0.5, now - lastMeter) : 0;
202 lastMeter = now;
203 if (normalize && node) {
204 meter.getFloatTimeDomainData(buf);
205 let s = 0;
206 for (const x of buf) s += x * x;
207 s /= buf.length;
208 if (s > 1e-10) msq += (s - msq) * (1 - Math.exp(-dt / NORM_TAU));
209 comp = Math.max(1 / NORM_RANGE, Math.min(NORM_RANGE, NORM_REF / Math.sqrt(msq)));
210 } else comp = 1;
211 gain.gain.setTargetAtTime(level * comp, when, 0.08);
212 // retune by restarting the note if the pitch setting moved
213 const m = midi(freq);
214 if (note !== null && Math.abs(m - note) > 0.01) {
215 post({ type: "noteOff", note, time: when });
216 note = m;
217 post({ type: "noteOn", note, vel: 1, time: when });
218 }
219 // color → mapped settings, throttled
220 const wall = performance.now();
221 if (!timbre?.length || wall - lastPost < DRONE_UPDATE_MS) return;
222 const next: Params = { ...base };
223 const parts: string[] = [];
224 let changed = false;
225 for (const tm of timbre) {
226 if (!LIVE_TARGETS.includes(tm.target)) continue;
227 const v = targetValue(tm.target, tm.from + (tm.to - tm.from) * color);
228 if (!Number.isFinite(v)) continue;
229 next[tm.target] = v;
230 parts.push(`${tm.target} ${Number(v.toPrecision(3))}`);
231 const d = PARAM_BY_ID[tm.target] as { min: number; max: number };
232 if (Math.abs(v - (sent[tm.target] as number)) > 0.002 * (d.max - d.min)) changed = true;
233 }
234 desc = parts.join(", ");
235 if (!changed) return;
236 sent = next;
237 lastPost = wall;
238 post({ type: "params", params: next });
239 },
240 describe: () => (comp !== 1 ? `${desc}${desc ? ", " : ""}gain ${(20 * Math.log10(comp)).toFixed(1)} dB` : desc),
241 dispose() {
242 post({ type: "panic" });
243 window.setTimeout(() => {
244 node?.disconnect();
245 node?.port.close();
246 gain.disconnect();
247 }, 1000);
248 },
249 };
250 };
251}
253/** Sustained presets (bowed, blown, self-oscillating, fed back) as "modal: <name>", plus "modal: custom". */
254export function modalDrones(): Record<string, DroneInstrumentFactory> {
255 const out: Record<string, DroneInstrumentFactory> = {};
256 for (const p of PRESETS) {
257 const q = { ...DEFAULTS, ...p.p };
258 if (SUSTAINED_EXCITERS.includes(q.exciter as string) || (q.fbGain as number) > 0) out[`modal: ${p.name}`] = makeModalDroneFactory(p.p);
259 }
260 out["modal: custom"] = makeModalDroneFactory(null);
261 return out;
262}