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