/ music / double-pendulum
Sign in
music / double-pendulum
double-pendulum / src / instruments / modal.ts
324 lines · 13.9 KBCodeBlameHistory
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";
216afddorbits: render instruments ahead in Web WorkersJeremy Magland 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;
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 }
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 }
73fe08adouble pendulum: album app with composition 1 (poincaré)Jeremy Magland 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) => {
f7d91baAdd composition 4: crashJeremy Magland 62 const sound: Params = { ...DEFAULTS, ...(preset ?? parseModalPreset(opts.custom) ?? {}), ...(opts.overrides ?? {}) };
79e1f25orbits: lighter on phones (faster engine, shared reverb, cached drawing)Jeremy Magland 64 // synth → fade (used by the final-note hold) → effects → our output
73fe08adouble pendulum: album app with composition 1 (poincaré)Jeremy Magland 65 const fade = ctx.createGain();
216afddorbits: render instruments ahead in Web WorkersJeremy Magland 66 routeEffects(ctx, fade, out, sound, opts);
68 let node: AudioWorkletNode | null = null;
8a22646orbits: limit the orbit count to what the device can play liveJeremy Magland 69 let cpu = 0; // smoothed audio-thread load of this synth
73fe08adouble pendulum: album app with composition 1 (poincaré)Jeremy Magland 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] });
8a22646orbits: limit the orbit count to what the device can play liveJeremy Magland 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 };
73fe08adouble pendulum: album app with composition 1 (poincaré)Jeremy Magland 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);
8a22646orbits: limit the orbit count to what the device can play liveJeremy Magland 100 const offline = typeof OfflineAudioContext !== "undefined" && (ctx as BaseAudioContext) instanceof OfflineAudioContext;
101 const immediate = offline || !!opts.immediateRelease;
5c043e1Add composition 2: orbitsJeremy Magland 102 let holding = false;
104 const inst: NoteInstrument = {
105 ready,
73fe08adouble pendulum: album app with composition 1 (poincaré)Jeremy Magland 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 });
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 }
73fe08adouble pendulum: album app with composition 1 (poincaré)Jeremy Magland 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;
5c043e1Add composition 2: orbitsJeremy Magland 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;
73fe08adouble pendulum: album app with composition 1 (poincaré)Jeremy Magland 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 };
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;
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;
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) => {
192 const base: Params = {
193 ...DEFAULTS,
194 ...(preset ?? parseModalPreset(opts.custom) ?? {}),
195 ...(opts.overrides ?? {}),
196 voices: 1,
197 ...(glide ? { bendRange: Math.max(1, Math.min(24, Math.round(glide.range))) } : {}),
198 };
73fe08adouble pendulum: album app with composition 1 (poincaré)Jeremy Magland 199 const gain = ctx.createGain();
200 gain.gain.value = 0;
201 const fx = new FX(ctx, out);
202 gain.connect(fx.input);
203 fx.set(base);
204 // loudness meter on the raw synth output, for normalization
205 const meter = ctx.createAnalyser();
206 meter.fftSize = 2048;
207 const buf = new Float32Array(meter.fftSize);
208 let msq = NORM_REF * NORM_REF; // smoothed mean square
209 let lastMeter = 0;
210 let comp = 1;
212 let node: AudioWorkletNode | null = null;
8a22646orbits: limit the orbit count to what the device can play liveJeremy Magland 213 let cpu = 0; // smoothed audio-thread load of this synth
73fe08adouble pendulum: album app with composition 1 (poincaré)Jeremy Magland 214 const early: Msg[] = [];
215 const post = (m: Msg) => (node ? node.port.postMessage(m) : early.push(m));
216 const ready = loadWorklet(ctx).then(() => {
217 node = new AudioWorkletNode(ctx, "modal-synth", { numberOfInputs: 0, outputChannelCount: [2] });
8a22646orbits: limit the orbit count to what the device can play liveJeremy Magland 218 node.port.onmessage = (e: MessageEvent<{ type?: string; cpu?: number }>) => {
219 if (e.data?.type === "snap" && typeof e.data.cpu === "number") cpu += (e.data.cpu - cpu) * 0.2;
220 };
73fe08adouble pendulum: album app with composition 1 (poincaré)Jeremy Magland 221 node.port.postMessage({ type: "params", params: base } satisfies Msg);
222 for (const m of early.splice(0)) node.port.postMessage(m);
223 node.connect(gain);
224 node.connect(meter);
225 });
227 let note: number | null = null;
73fe08adouble pendulum: album app with composition 1 (poincaré)Jeremy Magland 229 let sent: Params = base;
230 let lastPost = 0;
231 let desc = "";
232 const midi = (f: number) => 69 + 12 * Math.log2(f / 440);
234 return {
235 ready,
73fe08adouble pendulum: album app with composition 1 (poincaré)Jeremy Magland 237 start(when, freq) {
239 // begin already bent to the starting pitch
240 bend = Math.max(-1, Math.min(1, (midi(freq) - glide.center) / (base.bendRange as number)));
241 post({ type: "bend", value: bend });
242 }
243 note = glide ? glide.center : midi(freq);
73fe08adouble pendulum: album app with composition 1 (poincaré)Jeremy Magland 244 post({ type: "noteOn", note, vel: 1, time: when });
245 },
246 stop(when, release) {
247 const t = Math.max(ctx.currentTime, when - release);
248 gain.gain.cancelScheduledValues(t);
249 gain.gain.setTargetAtTime(0, t, release / 4);
250 if (note !== null) post({ type: "noteOff", note, time: t });
251 note = null;
252 },
253 set(when, { level, color, freq, timbre, normalize }) {
254 // loudness normalization: follow the measured level slowly, compensate toward NORM_REF
255 const now = performance.now() / 1000;
256 const dt = lastMeter ? Math.min(0.5, now - lastMeter) : 0;
257 lastMeter = now;
258 if (normalize && node) {
259 meter.getFloatTimeDomainData(buf);
260 let s = 0;
261 for (const x of buf) s += x * x;
262 s /= buf.length;
263 if (s > 1e-10) msq += (s - msq) * (1 - Math.exp(-dt / NORM_TAU));
264 comp = Math.max(1 / NORM_RANGE, Math.min(NORM_RANGE, NORM_REF / Math.sqrt(msq)));
265 } else comp = 1;
266 gain.gain.setTargetAtTime(level * comp, when, 0.08);
92338afcrash: viola click; height voice from modal-synth (glided with pitch bend)Jeremy Magland 267 // follow the pitch: glide with pitch bend, or restart the note if the pitch setting moved
73fe08adouble pendulum: album app with composition 1 (poincaré)Jeremy Magland 268 const m = midi(freq);
270 const range = base.bendRange as number;
271 const b = Math.max(-1, Math.min(1, (m - glide.center) / range));
272 if (Math.abs(b - bend) > 1e-4) {
273 bend = b;
274 post({ type: "bend", value: b });
275 }
276 } else if (note !== null && Math.abs(m - note) > 0.01) {
73fe08adouble pendulum: album app with composition 1 (poincaré)Jeremy Magland 277 post({ type: "noteOff", note, time: when });
278 note = m;
279 post({ type: "noteOn", note, vel: 1, time: when });
280 }
281 // color → mapped settings, throttled
282 const wall = performance.now();
283 if (!timbre?.length || wall - lastPost < DRONE_UPDATE_MS) return;
284 const next: Params = { ...base };
285 const parts: string[] = [];
286 let changed = false;
287 for (const tm of timbre) {
288 if (!LIVE_TARGETS.includes(tm.target)) continue;
289 const v = targetValue(tm.target, tm.from + (tm.to - tm.from) * color);
290 if (!Number.isFinite(v)) continue;
291 next[tm.target] = v;
292 parts.push(`${tm.target} ${Number(v.toPrecision(3))}`);
293 const d = PARAM_BY_ID[tm.target] as { min: number; max: number };
294 if (Math.abs(v - (sent[tm.target] as number)) > 0.002 * (d.max - d.min)) changed = true;
295 }
296 desc = parts.join(", ");
297 if (!changed) return;
298 sent = next;
299 lastPost = wall;
300 post({ type: "params", params: next });
301 },
302 describe: () => (comp !== 1 ? `${desc}${desc ? ", " : ""}gain ${(20 * Math.log10(comp)).toFixed(1)} dB` : desc),
303 dispose() {
304 post({ type: "panic" });
305 window.setTimeout(() => {
306 node?.disconnect();
307 node?.port.close();
308 gain.disconnect();
309 }, 1000);
310 },
311 };
312 };
315/** Sustained presets (bowed, blown, self-oscillating, fed back) as "modal: <name>", plus "modal: custom". */
316export function modalDrones(): Record<string, DroneInstrumentFactory> {
317 const out: Record<string, DroneInstrumentFactory> = {};
318 for (const p of PRESETS) {
319 const q = { ...DEFAULTS, ...p.p };
320 if (SUSTAINED_EXCITERS.includes(q.exciter as string) || (q.fbGain as number) > 0) out[`modal: ${p.name}`] = makeModalDroneFactory(p.p);
321 }
322 out["modal: custom"] = makeModalDroneFactory(null);
323 return out;
↑↓ move↵openescclose