// Instruments from the sibling modal-synth project (coupled nonlinear modal oscillators), // imported live via the @modal-synth alias. Each instrument instance is one AudioWorklet synth // (up to 16 voices) followed by modal-synth's own effects (saturation, delay, reverb). import { FX } from "@modal-synth/audio/fx.ts"; import workletUrl from "@modal-synth/audio/worklet.ts?worker&url"; import { DEFAULTS, PARAM_BY_ID, type Params } from "@modal-synth/engine/params.ts"; import type { Msg } from "@modal-synth/engine/synth.ts"; import { PRESETS } from "@modal-synth/presets.ts"; import { fadeCurve } from "./fade.ts"; import type { DroneInstrumentFactory, InstrumentOptions, NoteHandle, NoteInstrument, NoteInstrumentFactory } from "./types.ts"; const loaded = new WeakMap>(); function loadWorklet(ctx: AudioContext): Promise { let p = loaded.get(ctx); if (!p) { p = ctx.audioWorklet.addModule(workletUrl); loaded.set(ctx, p); } return p; } /** Parse a pasted preset (the JSON from modal-synth's Copy button). */ export function parseModalPreset(text: string | undefined): Params | null { if (!text || !text.trim()) return null; try { const v = JSON.parse(text); return v && typeof v === "object" && !Array.isArray(v) ? (v as Params) : null; } catch { return null; } } /** * Effects after an instrument: its own modal-synth FX (reverb/delay/saturation), nothing, or a * shared reverb send (dry at the preset's volume, send at its reverb amount; the preset's * delay/saturation, unused by the album's instruments, are skipped). */ export function routeEffects(ctx: AudioContext, from: AudioNode, out: AudioNode, sound: Params, opts: InstrumentOptions) { const effects = opts.effects ?? "own"; if (effects === "own") { const fx = new FX(ctx, out); from.connect(fx.input); fx.set(sound); return; } const vol = ctx.createGain(); vol.gain.value = Math.pow(10, (sound.volume as number) / 20); from.connect(vol).connect(out); if (effects !== "none") { const send = ctx.createGain(); send.gain.value = (sound.reverbMix as number) * vol.gain.value; from.connect(send).connect(effects.send); } } const NOTE_OFF_LEAD = 0.2; // post noteOffs to the worklet this far ahead of their time const FLUSH_MS = 25; export function makeModalFactory(preset: Params | null): NoteInstrumentFactory { return (ctx, out, opts) => { const sound: Params = { ...DEFAULTS, ...(preset ?? parseModalPreset(opts.custom) ?? {}), ...(opts.overrides ?? {}) }; // synth → fade (used by the final-note hold) → effects → our output const fade = ctx.createGain(); routeEffects(ctx, fade, out, sound, opts); let node: AudioWorkletNode | null = null; let cpu = 0; // smoothed audio-thread load of this synth const early: Msg[] = []; const post = (m: Msg) => (node ? node.port.postMessage(m) : early.push(m)); const ready = loadWorklet(ctx).then(() => { node = new AudioWorkletNode(ctx, "modal-synth", { numberOfInputs: 0, outputChannelCount: [2] }); // snapshots (30/s) carry the synth's own measure of its processing time / real time node.port.onmessage = (e: MessageEvent<{ type?: string; cpu?: number }>) => { if (e.data?.type === "snap" && typeof e.data.cpu === "number") cpu += (e.data.cpu - cpu) * 0.2; }; node.port.postMessage({ type: "params", params: sound } satisfies Msg); for (const m of early.splice(0)) node.port.postMessage(m); node.connect(fade); }); // noteOffs are held here until shortly before they're due, so the final note can be extended. // Notes are identified by pitch in the synth; a noteOff is skipped if the same pitch was // re-struck after its noteOn (the newer note has its own noteOff). interface Off { note: number; on: number; time: number } let offs: Off[] = []; const lastOn = new Map(); const flush = () => { const horizon = ctx.currentTime + NOTE_OFF_LEAD; const keep: Off[] = []; for (const o of offs) { if (o.time > horizon) keep.push(o); else if ((lastOn.get(o.note) ?? -Infinity) <= o.on) post({ type: "noteOff", note: o.note, time: o.time }); } offs = keep; }; const timer = window.setInterval(flush, FLUSH_MS); const offline = typeof OfflineAudioContext !== "undefined" && (ctx as BaseAudioContext) instanceof OfflineAudioContext; const immediate = offline || !!opts.immediateRelease; let holding = false; const inst: NoteInstrument = { ready, load: () => cpu, play({ when, freq, velocity, duration }) { if (velocity <= 0) return null; const note = 69 + 12 * Math.log2(freq / 440); post({ type: "noteOn", note, vel: Math.max(0.01, Math.min(1, velocity)), time: when }); if (immediate) { // device checks (and offline renders, which can't run the release timer): release now post({ type: "noteOff", note, time: when + duration }); return null; } lastOn.set(note, when); const off: Off = { note, on: when, time: when + duration }; offs.push(off); const handle: NoteHandle = { hold(from, holdLen, fadeLen) { const t = Math.max(from, ctx.currentTime); const ring = holdLen + fadeLen; // keep the damper off through the whole hold and fade (if still queued, the release moves later) off.time = t + ring; // the decay change and fade are instrument-wide: when several voices (orbits) end on this // instrument, the first hold schedules them and later ones just keep their dampers off if (holding) return; holding = true; // a plucked or struck body decays by itself: lengthen its decay so it really rings through // the hold. Only the final note is sounding by then, so the instrument-wide change is safe. // Both the base decay (t60) and the frequency-dependent loss (hfDamp) are slowed by the same // factor, so the note keeps its tone color while it rings. const t60 = Math.min(60, Math.max(sound.t60 as number, 6 * ring)); const slow = t60 / (sound.t60 as number); const ringing: Params = { ...sound, t60, hfDamp: (sound.hfDamp as number) / slow }; window.setTimeout(() => post({ type: "params", params: ringing }), Math.max(0, (t - ctx.currentTime) * 1000)); fade.gain.setValueCurveAtTime(fadeCurve(1), t + Math.max(holdLen, 0.005), fadeLen); }, }; return handle; }, dispose() { window.clearInterval(timer); post({ type: "panic" }); window.setTimeout(() => { node?.disconnect(); node?.port.close(); fade.disconnect(); }, 1000); }, }; return inst; }; } /** Menu name → factory, for every built-in modal-synth preset plus "modal: custom". */ export function modalInstruments(): Record { const out: Record = {}; for (const p of PRESETS) out[`modal: ${p.name}`] = makeModalFactory(p.p); out["modal: custom"] = makeModalFactory(null); return out; } // ── drones: one held note of a sustained preset, with color mapped onto synth settings ── /** Settings the synth reads every block, so they can follow the energy while a note is held. */ export const LIVE_TARGETS = [ "bowForce", "bowSpeed", "bowNoise", "exPos", "reedPressure", "reedGain", "breath", "selfGain", "selfSat", "noiseLevel", "noiseColor", "tension", "cascade", "curvature", "fbGain", "fbFreq", "fbQ", "fbSat", "hfDamp", "t60", "pickup", "tilt", "vibDepth", ]; /** 0..1 → a modal-synth setting's value, following that setting's own slider scale. */ export function targetValue(id: string, u: number): number { const d = PARAM_BY_ID[id]; if (!d || d.kind !== "num") return NaN; const x = Math.max(0, Math.min(1, u)); if (d.scale === "log") return d.min * Math.pow(d.max / d.min, x); if (d.scale === "pow2") return d.min + (d.max - d.min) * x * x; return d.min + (d.max - d.min) * x; } const SUSTAINED_EXCITERS = ["bow", "reed", "selfosc", "noise"]; const DRONE_UPDATE_MS = 50; // at most this often, a "params" message to the worklet const NORM_REF = 0.3; // with normalize on, level 1 ≈ this RMS (about the placeholder hum's) const NORM_TAU = 1.5; // seconds: how slowly the loudness compensation follows const NORM_RANGE = 20; // compensation limited to ×1/20 … ×20 export function makeModalDroneFactory(preset: Params | null): DroneInstrumentFactory { return (ctx, out, opts) => { const base: Params = { ...DEFAULTS, ...(preset ?? parseModalPreset(opts.custom) ?? {}), voices: 1 }; const gain = ctx.createGain(); gain.gain.value = 0; const fx = new FX(ctx, out); gain.connect(fx.input); fx.set(base); // loudness meter on the raw synth output, for normalization const meter = ctx.createAnalyser(); meter.fftSize = 2048; const buf = new Float32Array(meter.fftSize); let msq = NORM_REF * NORM_REF; // smoothed mean square let lastMeter = 0; let comp = 1; let node: AudioWorkletNode | null = null; let cpu = 0; // smoothed audio-thread load of this synth const early: Msg[] = []; const post = (m: Msg) => (node ? node.port.postMessage(m) : early.push(m)); const ready = loadWorklet(ctx).then(() => { node = new AudioWorkletNode(ctx, "modal-synth", { numberOfInputs: 0, outputChannelCount: [2] }); node.port.onmessage = (e: MessageEvent<{ type?: string; cpu?: number }>) => { if (e.data?.type === "snap" && typeof e.data.cpu === "number") cpu += (e.data.cpu - cpu) * 0.2; }; node.port.postMessage({ type: "params", params: base } satisfies Msg); for (const m of early.splice(0)) node.port.postMessage(m); node.connect(gain); node.connect(meter); }); let note: number | null = null; let sent: Params = base; let lastPost = 0; let desc = ""; const midi = (f: number) => 69 + 12 * Math.log2(f / 440); return { ready, load: () => cpu, start(when, freq) { note = midi(freq); post({ type: "noteOn", note, vel: 1, time: when }); }, stop(when, release) { const t = Math.max(ctx.currentTime, when - release); gain.gain.cancelScheduledValues(t); gain.gain.setTargetAtTime(0, t, release / 4); if (note !== null) post({ type: "noteOff", note, time: t }); note = null; }, set(when, { level, color, freq, timbre, normalize }) { // loudness normalization: follow the measured level slowly, compensate toward NORM_REF const now = performance.now() / 1000; const dt = lastMeter ? Math.min(0.5, now - lastMeter) : 0; lastMeter = now; if (normalize && node) { meter.getFloatTimeDomainData(buf); let s = 0; for (const x of buf) s += x * x; s /= buf.length; if (s > 1e-10) msq += (s - msq) * (1 - Math.exp(-dt / NORM_TAU)); comp = Math.max(1 / NORM_RANGE, Math.min(NORM_RANGE, NORM_REF / Math.sqrt(msq))); } else comp = 1; gain.gain.setTargetAtTime(level * comp, when, 0.08); // retune by restarting the note if the pitch setting moved const m = midi(freq); if (note !== null && Math.abs(m - note) > 0.01) { post({ type: "noteOff", note, time: when }); note = m; post({ type: "noteOn", note, vel: 1, time: when }); } // color → mapped settings, throttled const wall = performance.now(); if (!timbre?.length || wall - lastPost < DRONE_UPDATE_MS) return; const next: Params = { ...base }; const parts: string[] = []; let changed = false; for (const tm of timbre) { if (!LIVE_TARGETS.includes(tm.target)) continue; const v = targetValue(tm.target, tm.from + (tm.to - tm.from) * color); if (!Number.isFinite(v)) continue; next[tm.target] = v; parts.push(`${tm.target} ${Number(v.toPrecision(3))}`); const d = PARAM_BY_ID[tm.target] as { min: number; max: number }; if (Math.abs(v - (sent[tm.target] as number)) > 0.002 * (d.max - d.min)) changed = true; } desc = parts.join(", "); if (!changed) return; sent = next; lastPost = wall; post({ type: "params", params: next }); }, describe: () => (comp !== 1 ? `${desc}${desc ? ", " : ""}gain ${(20 * Math.log10(comp)).toFixed(1)} dB` : desc), dispose() { post({ type: "panic" }); window.setTimeout(() => { node?.disconnect(); node?.port.close(); gain.disconnect(); }, 1000); }, }; }; } /** Sustained presets (bowed, blown, self-oscillating, fed back) as "modal: ", plus "modal: custom". */ export function modalDrones(): Record { const out: Record = {}; for (const p of PRESETS) { const q = { ...DEFAULTS, ...p.p }; if (SUSTAINED_EXCITERS.includes(q.exciter as string) || (q.fbGain as number) > 0) out[`modal: ${p.name}`] = makeModalDroneFactory(p.p); } out["modal: custom"] = makeModalDroneFactory(null); return out; }