087c169Physically simulated pizzicato double bass and an SF2 built from itJeremy Magland 1// The browser app: parameters, keyboard, rendering in workers, A/B against the reference SoundFont,
2// analysis plots, the FE body, and building/playing the SF2.
4import { cloneParams, defaultParams, feInputsKey, getPath, mergeParams, PARAM_INFO, setPath, type ParamInfo, type Params } from "../core/params.ts";
5import { parametricBody } from "../core/body.ts";
6import { bridgeAdmittance, radiationTransfer, STRING_NAMES, type BodyModel } from "../core/types.ts";
7import { mixOutput } from "../core/engine.ts";
8import { fingering, midiToHz } from "../core/strings.ts";
9import { centroid, encodeWav, envelopeDecay, partialDecay, spectrogram, spectrumDb } from "../core/dsp.ts";
10import { buildSf2, noteName, sampleJobs, sampleNotes } from "../core/sf2.ts";
11import { linePlot, spectrogramPlot } from "./plots.ts";
12import { Audio } from "./synth.ts";
13import feDefaultUrl from "../../bodies/fe_default.json?url";
14import prebuiltSf2Url from "../../acoustic-bass.sf2?url";
182eaafAdd a Physics 3D tab: slow-motion 3D replay of the simulationJeremy Magland 15import feDefaultShapesUrl from "../../bodies/fe_default_shapes.bin?url";
16import type { PhysicsView, VizHost } from "./viz/index.ts";
17import type { Recording } from "../core/engine.ts";
18import type { FEShapes } from "../fe/shapes.ts";
20// ---------------------------------------------------------------- workers
22type Reply = { type: string; id: number; frac?: number; msg?: string; error?: string; [k: string]: unknown };
24class Pool {
25 private idle: Worker[] = [];
26 private queue: { msg: Record<string, unknown>; transfer: Transferable[]; resolve: (r: Reply) => void; reject: (e: Error) => void; progress?: (f: number, msg?: string) => void }[] = [];
27 private pending = new Map<number, { resolve: (r: Reply) => void; reject: (e: Error) => void; progress?: (f: number, msg?: string) => void; worker: Worker }>();
28 private nextId = 1;
29 constructor(n: number) {
30 for (let i = 0; i < n; i++) {
31 const w = new Worker(new URL("./worker.ts", import.meta.url), { type: "module" });
32 w.onmessage = (e: MessageEvent<Reply>) => {
33 const r = e.data, p = this.pending.get(r.id);
34 if (!p) return;
35 if (r.type === "progress") { p.progress?.(r.frac ?? 0, r.msg); return; }
36 this.pending.delete(r.id);
37 this.idle.push(p.worker);
38 if (r.type === "error") p.reject(new Error(r.error)); else p.resolve(r);
39 this.pump();
40 };
41 this.idle.push(w);
42 }
43 }
44 call(msg: Record<string, unknown>, transfer: Transferable[] = [], progress?: (f: number, msg?: string) => void): Promise<Reply> {
45 return new Promise((resolve, reject) => { this.queue.push({ msg, transfer, resolve, reject, progress }); this.pump(); });
46 }
47 private pump() {
48 while (this.idle.length && this.queue.length) {
49 const w = this.idle.pop()!, job = this.queue.shift()!;
50 const id = this.nextId++;
51 this.pending.set(id, { resolve: job.resolve, reject: job.reject, progress: job.progress, worker: w });
52 w.postMessage({ ...job.msg, id }, job.transfer);
53 }
54 }
55 get size() { return this.idle.length + this.pending.size; }
56}
58const nCores = Math.max(2, Math.min(10, (navigator.hardwareConcurrency || 4) - 1));
59const renderPool = new Pool(1); // interactive renders
60const bulkPool = new Pool(nCores); // SF2 builds, FE
61const refPool = new Pool(1); // holds the reference SoundFont
63// ---------------------------------------------------------------- state
65const LS_PARAMS = "acoustic-base.params", LS_FE = "acoustic-base.feBody", LS_UI = "acoustic-base.ui";
66const load = <T,>(k: string): T | null => { try { const s = localStorage.getItem(k); return s ? (JSON.parse(s) as T) : null; } catch { return null; } };
67const save = (k: string, v: unknown) => { try { localStorage.setItem(k, JSON.stringify(v)); } catch { /* storage full or blocked */ } };
69let params: Params = mergeParams(load(LS_PARAMS) ?? {});
70let feBody: BodyModel | null = load<BodyModel>(LS_FE);
71const ui = { note: 33, velocity: 90, auto: true, playMode: "sim" as "sim" | "built" | "ref", tab: "sound", refProgram: 32, refBank: 0, volume: 0.8, ...(load<Record<string, unknown>>(LS_UI) ?? {}) } as {
72 note: number; velocity: number; auto: boolean; playMode: "sim" | "built" | "ref"; tab: string; refProgram: number; refBank: number; volume: number;
73};
74let last: { key: string; mic: Float32Array; pickup: Float32Array; info: Record<string, unknown>; fs: number; note: number; velocity: number } | null = null;
75const refCache = new Map<string, Float32Array>();
76let refLoaded: Promise<void> | null = null;
77let refName = "";
78let builtSf2: Uint8Array | null = null;
79let builtKey = 0;
80let renderSeq = 0;
81const audio = new Audio();
82audio.setVolume(ui.volume);
84const saveUi = () => save(LS_UI, ui);
85const feFresh = () => !!feBody && feBody.meta?.feKey === feInputsKey(params);
86const useFE = () => params.engine.bodyModel === "fe";
87const body = (): BodyModel => (useFE() && feBody ? feBody : parametricBody(params));
88const renderKey = (note: number, vel: number) => JSON.stringify([params.engine, params.strings, params.pluck, params.stop, useFE() ? feInputsKey(params) : params.body, params.fe.stringSpacing, params.fe.bridgeHeight, params.output.micDistance, params.output.pickupPaPerN, params.output.pickupLateral, note, vel]);
90// ---------------------------------------------------------------- DOM
92const $ = <T extends HTMLElement = HTMLElement>(sel: string) => document.querySelector(sel) as T;
93const el = <K extends keyof HTMLElementTagNameMap>(tag: K, attrs: Record<string, unknown> = {}, ...kids: (Node | string)[]): HTMLElementTagNameMap[K] => {
94 const e = document.createElement(tag);
95 for (const [k, v] of Object.entries(attrs)) {
96 if (k === "class") e.className = String(v);
97 else if (k.startsWith("on")) e.addEventListener(k.slice(2), v as EventListener);
98 else if (v !== undefined && v !== false) e.setAttribute(k, String(v));
99 }
100 for (const c of kids) e.append(c);
101 return e;
102};
104$("#app").innerHTML = `
105<header>
106 <h1>Acoustic Bass <span>physical model</span></h1>
107 <div class="status" id="status"></div>
108 <div class="hbtns">
109 <button id="bLoad" title="Load parameters (JSON)">Load…</button>
110 <button id="bSave" title="Save parameters (JSON)">Save</button>
111 <button id="bReset" title="Restore the default parameters">Reset</button>
112 <input type="file" id="fParams" accept=".json" hidden />
113 </div>
114</header>
115<div class="main">
116 <aside id="params"></aside>
117 <section class="work">
118 <div class="transport">
119 <div class="noteinfo"><b id="noteName"></b><span id="fingerInfo"></span></div>
120 <label>Velocity <input type="range" id="vel" min="1" max="127" /><span id="velV"></span></label>
121 <button id="bRender" class="primary">Render ▶</button>
122 <button id="bSim" title="Play the last simulation render">Sim</button>
123 <button id="bRef" title="Play the reference SoundFont, same note and velocity">Ref</button>
124 <button id="bAB" title="Simulation, then reference">A/B</button>
125 <label class="chk"><input type="checkbox" id="auto" /> auto-render</label>
126 <label>Keys play <select id="playMode"><option value="sim">simulation (render)</option><option value="built">built SF2 (live)</option><option value="ref">reference SF2 (live)</option></select></label>
127 <label>Vol <input type="range" id="vol" min="0" max="1.5" step="0.01" /></label>
128 <button id="bWav" title="Download the render as WAV">WAV</button>
129 <button id="bRefFile" title="Choose the reference SoundFont (stays on this computer); bank 0 program 32 is played">Ref SF2…</button>
130 <input type="file" id="fRef" accept=".sf2,.sf3" hidden />
131 </div>
132 <div id="keyboard"></div>
133 <div class="progress"><div id="prog"></div></div>
134 <div class="mix">
135 <label>Mic <input type="range" id="mMic" min="0" max="1" step="0.01" /></label>
136 <label>Pickup <input type="range" id="mPick" min="0" max="1" step="0.01" /></label>
137 <span class="hint">mix applies without re-rendering</span>
138 <span id="metrics" class="metrics"></span>
139 </div>
140 <nav class="tabs" id="tabs"></nav>
141 <div id="panels"></div>
142 </section>
143</div>`;
145const status = (s: string, err = false) => { const e = $("#status"); e.textContent = s; e.classList.toggle("err", err); };
146const progress = (f: number) => { ($("#prog") as HTMLDivElement).style.width = `${Math.round(Math.max(0, Math.min(1, f)) * 100)}%`; };
148// ---------------------------------------------------------------- parameter panel
150const groups = new Map<string, ParamInfo[]>();
151for (const pi of PARAM_INFO) { if (!groups.has(pi.group)) groups.set(pi.group, []); groups.get(pi.group)!.push(pi); }
152const controls: { pi: ParamInfo; sync: () => void }[] = [];
153const openGroups = new Set<string>(load<string[]>("acoustic-base.groups") ?? ["Right hand", "Output"]);
155function fmtNum(v: number): string {
156 if (v === 0) return "0";
157 const a = Math.abs(v);
158 if (a >= 1e5 || a < 1e-3) return v.toExponential(2);
159 return String(+v.toPrecision(4));
160}
162function buildParamPanel() {
163 const root = $("#params");
164 root.innerHTML = "";
165 controls.length = 0;
166 for (const [g, list] of groups) {
167 const det = el("details", { class: "grp" });
168 if (openGroups.has(g)) det.open = true;
169 det.addEventListener("toggle", () => { if (det.open) openGroups.add(g); else openGroups.delete(g); save("acoustic-base.groups", [...openGroups]); });
170 det.append(el("summary", {}, g));
171 for (const pi of list) {
172 const row = el("div", { class: "prow", title: pi.help ?? "" });
173 row.append(el("span", { class: "plabel" }, pi.label));
174 const sc = pi.scale ?? 1;
175 if (pi.kind === "bool") {
176 const cb = el("input", { type: "checkbox" }) as HTMLInputElement;
177 cb.addEventListener("change", () => setParam(pi.path, cb.checked));
178 row.append(cb);
179 controls.push({ pi, sync: () => { cb.checked = !!getPath(params, pi.path); } });
180 } else if (pi.kind === "select") {
181 const s = el("select") as HTMLSelectElement;
182 for (const o of pi.options ?? []) s.append(el("option", { value: o }, o));
183 s.addEventListener("change", () => setParam(pi.path, s.value));
184 row.append(s);
185 controls.push({ pi, sync: () => { s.value = String(getPath(params, pi.path)); } });
186 } else {
187 const r = el("input", { type: "range", min: 0, max: 1000, step: 1 }) as HTMLInputElement;
188 const n = el("input", { type: "text", class: "num" }) as HTMLInputElement;
189 const lo = pi.min ?? 0, hi = pi.max ?? 1;
190 const toSlider = (v: number) => (pi.log ? Math.log(v / lo) / Math.log(hi / lo) : (v - lo) / (hi - lo)) * 1000;
191 const fromSlider = (s: number) => { let v = pi.log ? lo * Math.pow(hi / lo, s / 1000) : lo + ((hi - lo) * s) / 1000; if (pi.step && !pi.log) v = Math.round(v / pi.step) * pi.step; return +v.toPrecision(6); };
192 r.addEventListener("input", () => { const v = fromSlider(Number(r.value)); n.value = fmtNum(v * sc); setParam(pi.path, v); });
193 n.addEventListener("change", () => { const v = Number(n.value) / sc; if (isFinite(v)) { setParam(pi.path, v); r.value = String(toSlider(v)); } });
194 row.append(r, n, el("span", { class: "unit" }, pi.unit ?? ""));
195 controls.push({ pi, sync: () => { const v = Number(getPath(params, pi.path)); r.value = String(toSlider(v)); n.value = fmtNum(v * sc); } });
196 }
197 det.append(row);
198 }
199 if (g === "Body (parametric)") det.append(lowModesEditor());
200 if (g === "Body (FE)") det.append(feControls());
201 root.append(det);
202 }
203 syncControls();
204}
206function syncControls() { for (const c of controls) c.sync(); }
208let changeTimer = 0;
209function setParam(path: string, v: unknown) {
210 setPath(params, path, v);
211 save(LS_PARAMS, params);
212 window.clearTimeout(changeTimer);
213 changeTimer = window.setTimeout(onParamsChanged, 250);
214}
216function onParamsChanged() {
217 updateFeInfo();
218 drawKeyboard();
219 updateNoteInfo();
220 if (ui.tab === "body") drawBody();
221 if (ui.tab === "sf2") drawSf2Panel();
182eaafAdd a Physics 3D tab: slow-motion 3D replay of the simulationJeremy Magland 222 physics?.noteChanged();
087c169Physically simulated pizzicato double bass and an SF2 built from itJeremy Magland 223 if (ui.auto && last && last.key !== renderKey(ui.note, ui.velocity)) void renderCurrent(false);
224}
226function lowModesEditor(): HTMLElement {
227 const wrap = el("div", { class: "lowmodes" });
228 const draw = () => {
229 wrap.innerHTML = "";
230 const t = el("table");
231 t.append(el("tr", {}, ...["", "f Hz", "Q", "mass kg", "lat", "vol m²", ""].map((h) => el("th", {}, h))));
232 params.body.lowModes.forEach((m, i) => {
233 const tr = el("tr");
234 tr.append(el("td", {}, m.label));
235 for (const k of ["f", "q", "mass", "lateral", "rad"] as const) {
236 const inp = el("input", { type: "text", value: String(m[k]), class: "num" }) as HTMLInputElement;
237 inp.addEventListener("change", () => { const v = Number(inp.value); if (isFinite(v)) { m[k] = v; setParam("body.lowModes", params.body.lowModes); } });
238 tr.append(el("td", {}, inp));
239 }
240 tr.append(el("td", {}, el("button", { class: "small", onclick: () => { params.body.lowModes.splice(i, 1); setParam("body.lowModes", params.body.lowModes); draw(); } }, "×")));
241 t.append(tr);
242 });
243 wrap.append(el("div", { class: "sub" }, "Signature modes (A0 air, corpus modes): frequency, Q, effective mass at the bridge, lateral/vertical coupling, volume per unit bridge displacement (monopole strength)."), t,
244 el("button", { class: "small", onclick: () => { const lm = params.body.lowModes; const f = (lm[lm.length - 1]?.f ?? 300) * 1.2; lm.push({ label: `M${lm.length + 1}`, f: Math.round(f), q: 25, mass: 1, lateral: 0.5, rad: 0.05 }); setParam("body.lowModes", lm); draw(); } }, "+ mode"));
245 };
246 draw();
247 return wrap;
248}
250function feControls(): HTMLElement {
251 const wrap = el("div", { class: "fectl" });
252 const info = el("div", { class: "sub", id: "feInfo" });
253 const bCompute = el("button", { class: "primary small", onclick: () => void computeFE() }, "Compute FE body");
254 const bDown = el("button", { class: "small", onclick: () => { if (feBody) download(new Blob([JSON.stringify(feBody)], { type: "application/json" }), "fe-body.json"); } }, "Download");
255 const fIn = el("input", { type: "file", accept: ".json", hidden: true }) as HTMLInputElement;
256 fIn.addEventListener("change", async () => { const f = fIn.files?.[0]; if (!f) return; feBody = JSON.parse(await f.text()) as BodyModel; save(LS_FE, feBody); updateFeInfo(); onParamsChanged(); });
257 const bUp = el("button", { class: "small", onclick: () => fIn.click() }, "Load…");
258 wrap.append(el("div", { class: "btnrow" }, bCompute, bDown, bUp, fIn), info);
259 return wrap;
260}
262function updateFeInfo() {
263 const e = document.getElementById("feInfo");
264 if (!e) return;
265 if (!feBody) { e.textContent = "No FE body yet. Compute it (geometry and woods above), then set Engine → Body model to fe."; return; }
266 const low = feBody.modes.filter((m) => m.f < 400).slice(0, 8).map((m) => `${m.label ?? ""} ${m.f.toFixed(0)}`).join(", ");
267 e.textContent = `${feBody.modes.length} modes${feBody.meta?.elapsed ? `, computed in ${Number(feBody.meta.elapsed).toFixed(1)} s` : ""}. Low modes: ${low}. ${!feFresh() ? "Out of date: the geometry or woods changed; it is recomputed before the next render." : useFE() ? "In use." : "Not in use (Engine → Body model)."}`;
268}
270async function computeFE() {
271 status("Computing the FE body…");
272 progress(0);
273 try {
274 const r = await bulkPool.call({ type: "fe", params: cloneParams(params) }, [], (f, msg) => { progress(f); if (msg) status(`FE: ${msg}`); });
275 feBody = r.body as BodyModel;
276 feBody.meta = { ...(feBody.meta ?? {}), elapsed: r.elapsed };
277 save(LS_FE, feBody);
278 status(`FE body: ${feBody.modes.length} modes in ${Number(r.elapsed).toFixed(1)} s`);
279 if (params.engine.bodyModel !== "fe") setParam("engine.bodyModel", "fe"); else { drawBody(); drawSf2Panel(); }
280 syncControls();
281 } catch (e) { status(`FE failed: ${(e as Error).message.split("\n")[0]}`, true); }
282 progress(1);
283 updateFeInfo();
284}
286// ---------------------------------------------------------------- keyboard
288const KB_LO = 24, KB_HI = 62;
289const isBlack = (n: number) => [1, 3, 6, 8, 10].includes(n % 12);
290const held = new Set<number>();
292function drawKeyboard() {
293 const kb = $("#keyboard");
294 kb.innerHTML = "";
295 const whites = [];
296 for (let n = KB_LO; n <= KB_HI; n++) if (!isBlack(n)) whites.push(n);
297 const ww = 100 / whites.length;
298 const roots = new Set(sampleNotes(params));
299 let wi = 0;
300 for (let n = KB_LO; n <= KB_HI; n++) {
301 const black = isBlack(n);
302 const left = black ? (wi - 0.32) * ww : wi * ww;
303 const k = el("div", { class: `key ${black ? "black" : "white"}${n === ui.note ? " sel" : ""}${held.has(n) ? " down" : ""}${n < 28 ? " ext" : ""}`, "data-n": n, title: `${noteName(n)} (${midiToHz(n).toFixed(1)} Hz)` });
304 k.style.left = `${left}%`; k.style.width = `${black ? ww * 0.64 : ww}%`;
305 if (roots.has(n)) k.append(el("i", { class: "root" }));
306 if (!black && n % 12 === 0) k.append(el("span", {}, noteName(n)));
307 k.addEventListener("pointerdown", (e) => { e.preventDefault(); const r = k.getBoundingClientRect(); const v = Math.round(20 + 107 * Math.min(1, Math.max(0, (e.clientY - r.top) / r.height))); pointerNote = n; keyDown(n, ui.playMode === "sim" ? ui.velocity : v); });
308 kb.append(k);
309 if (!black) wi++;
310 }
311}
313let pointerNote = -1;
314window.addEventListener("pointerup", () => { if (pointerNote >= 0) { keyUp(pointerNote); pointerNote = -1; } });
316/** update the selected / held marks without rebuilding the keyboard */
317function markKeys() {
318 document.querySelectorAll<HTMLElement>("#keyboard .key").forEach((k) => {
319 const n = Number(k.dataset.n);
320 k.classList.toggle("sel", n === ui.note);
321 k.classList.toggle("down", held.has(n));
322 });
323}
325function keyDown(n: number, vel: number) {
326 held.add(n);
327 if (ui.playMode === "sim") {
328 ui.note = n; ui.velocity = vel; saveUi(); syncTransport();
329 void renderCurrent(true);
330 } else {
331 void (async () => { await ensureLiveBank(); audio.noteOn(n, vel); })();
332 }
333 markKeys();
334}
335function keyUp(n: number) {
336 held.delete(n);
337 if (ui.playMode !== "sim") audio.noteOff(n);
338 markKeys();
339}
341async function ensureLiveBank() {
342 if (ui.playMode === "built") {
343 if (!builtSf2) { status("Build the SF2 first (SF2 tab)", true); return; }
344 await audio.loadBank(`built${builtKey}`, builtSf2.buffer.slice(builtSf2.byteOffset, builtSf2.byteOffset + builtSf2.byteLength) as ArrayBuffer, params.sf2.bank, params.sf2.program);
345 } else if (ui.playMode === "ref") {
346 const data = await fetchRef();
347 await audio.loadBank(`ref:${refName}:${data.byteLength}`, data, ui.refBank, ui.refProgram);
348 }
349}
351// computer keyboard: A W S E D F T G Y H U J K O L P ; from C of the base octave
352const KEYMAP = "awsedftgyhujkolp;";
353let kbBase = 24;
354window.addEventListener("keydown", (e) => {
355 if (e.repeat || (e.target as HTMLElement).tagName === "INPUT" || (e.target as HTMLElement).tagName === "SELECT") return;
356 const i = KEYMAP.indexOf(e.key.toLowerCase());
357 if (i >= 0) { keyDown(kbBase + i, ui.velocity); return; }
358 if (e.key === "z") kbBase = Math.max(12, kbBase - 12);
359 if (e.key === "x") kbBase = Math.min(72, kbBase + 12);
360 if (e.key === " " && ui.playMode === "sim" && last) { e.preventDefault(); void playSim(); }
361});
362window.addEventListener("keyup", (e) => { const i = KEYMAP.indexOf(e.key.toLowerCase()); if (i >= 0) keyUp(kbBase + i); });
364// Web MIDI
365if ("requestMIDIAccess" in navigator) {
366 navigator.requestMIDIAccess().then((acc) => {
367 const hook = () => acc.inputs.forEach((inp) => { inp.onmidimessage = (ev) => {
368 const d = ev.data; if (!d) return;
369 const st = d[0] & 0xf0;
370 if (st === 0x90 && d[2] > 0) keyDown(d[1], d[2]);
371 else if (st === 0x80 || (st === 0x90 && d[2] === 0)) keyUp(d[1]);
372 else if (st === 0xb0 && d[1] === 64) audio.sustain(d[2] >= 64);
373 }; });
374 hook(); acc.onstatechange = hook;
375 }).catch(() => { /* no MIDI */ });
376}
378// ---------------------------------------------------------------- render / reference
380/** Make sure the FE body matches the parameters (when it is in use): load the shipped default or compute. */
381let feEnsuring: Promise<void> | null = null;
382async function ensureFE(): Promise<void> {
383 if (!useFE() || feFresh()) return;
384 if (!feEnsuring) feEnsuring = (async () => {
385 try {
386 const r = await fetch(feDefaultUrl);
387 if (r.ok) { const b = (await r.json()) as BodyModel; if (b.meta?.feKey === feInputsKey(params)) { feBody = b; save(LS_FE, b); updateFeInfo(); return; } }
388 } catch { /* not served */ }
389 await computeFE();
390 })().finally(() => { feEnsuring = null; });
391 return feEnsuring;
392}
394async function renderCurrent(play: boolean) {
395 await ensureFE();
396 const note = ui.note, vel = ui.velocity;
397 const key = renderKey(note, vel);
398 if (last && last.key === key) { if (play) void playSim(); return; }
399 const seq = ++renderSeq;
400 status(`Rendering ${noteName(note)} v${vel}…`);
401 progress(0);
402 const b = useFE() && feBody ? feBody : undefined;
403 try {
404 const r = await renderPool.call({ type: "render", params: cloneParams(params), body: b, note, velocity: vel }, [], (f) => { if (seq === renderSeq) progress(f); });
405 if (seq !== renderSeq) return;
406 const info = r.info as Record<string, unknown>;
407 last = { key, mic: r.mic as Float32Array, pickup: r.pickup as Float32Array, info, fs: Number(info.sampleRate), note, velocity: vel };
408 progress(1);
409 status(`${noteName(note)} v${vel}: rendered in ${Number(info.elapsed).toFixed(2)} s (${(info.modeCounts as { body: number }).body} body modes)`);
410 updateNoteInfo();
411 analyse();
182eaafAdd a Physics 3D tab: slow-motion 3D replay of the simulationJeremy Magland 412 physics?.noteChanged();
087c169Physically simulated pizzicato double bass and an SF2 built from itJeremy Magland 413 if (play) void playSim();
414 } catch (e) { status(`Render failed: ${(e as Error).message.split("\n")[0]}`, true); }
415}
417const SIM_PLAY_GAIN = 1.6;
418const simAudio = () => (last ? mixOutput(params, last.mic, last.pickup) : new Float32Array(0));
419async function playSim() { if (last) await audio.play(simAudio(), last.fs, SIM_PLAY_GAIN); }
421// The reference SoundFont: the dev server serves one at ref.sf2 (GeneralUser GS from ~/Downloads,
422// or $REF_SF2); on the deployed site the user picks a file (nothing is uploaded).
423let refData: ArrayBuffer | null = null;
424async function fetchRef(): Promise<ArrayBuffer> {
425 if (refData) return refData;
426 status("Loading the reference SoundFont…");
427 let res: Response | null = null;
428 try { res = await fetch(`${import.meta.env.BASE_URL}ref.sf2`); } catch { res = null; }
429 const ok = !!res && res.ok && (res.headers.get("Content-Type") ?? "").includes("octet-stream");
430 if (!ok) throw new Error("no reference SoundFont: choose one with 'Ref SF2…' (e.g. GeneralUser GS, program 32)");
431 refData = await res!.arrayBuffer();
432 refName = "GeneralUser GS";
433 status(`Reference loaded (${(refData.byteLength / 1e6).toFixed(0)} MB)`);
434 return refData;
435}
437async function setRefFile(f: File) {
438 refData = await f.arrayBuffer();
439 refName = f.name.replace(/\.sf[23]$/i, "");
440 refLoaded = null;
441 refCache.clear();
442 status(`Reference: ${f.name} (${(refData.byteLength / 1e6).toFixed(0)} MB), bank ${ui.refBank} program ${ui.refProgram}`);
443 if (ui.playMode === "ref") void ensureLiveBank();
444 void analyse();
445}
447async function ensureRefWorker() {
448 if (!refLoaded) refLoaded = (async () => { const d = await fetchRef(); await refPool.call({ type: "refBank", buffer: d.slice(0) }); })();
449 try { await refLoaded; } catch (e) { refLoaded = null; throw e; }
450}
452async function refAudio(note: number, vel: number): Promise<Float32Array> {
453 const k = `${ui.refBank}:${ui.refProgram}:${note}:${vel}:${params.engine.duration}`;
454 if (refCache.has(k)) return refCache.get(k)!;
455 await ensureRefWorker();
456 const r = await refPool.call({ type: "ref", note, velocity: vel, program: ui.refProgram, bank: ui.refBank, len: params.engine.duration, hold: params.engine.duration - 0.5 });
457 const x = r.audio as Float32Array;
458 refCache.set(k, x);
459 return x;
460}
462async function playRef() {
463 try { const x = await refAudio(ui.note, ui.velocity); status(`Reference ${refName} program ${ui.refProgram}: ${noteName(ui.note)} v${ui.velocity}`); await audio.play(x, 44100, 1); }
464 catch (e) { status(`Reference: ${(e as Error).message}`, true); }
465}
467// ---------------------------------------------------------------- analysis panels
182eaafAdd a Physics 3D tab: slow-motion 3D replay of the simulationJeremy Magland 469const TABS: [string, string][] = [["sound", "Sound"], ["spectro", "Spectrogram"], ["partials", "Partials"], ["body", "Body"], ["physics", "Physics 3D"], ["sf2", "SF2"]];
471// The physics view (3D, slow motion) is loaded on first use: three.js is large.
472const physicsRoot = el("div");
473let physics: PhysicsView | null = null;
474let physicsLoading: Promise<PhysicsView> | null = null;
475const vizHost: VizHost = {
476 params: () => params,
477 note: () => ui.note,
478 velocity: () => ui.velocity,
479 useFE,
480 feKey: () => feInputsKey(params),
481 body: async () => { await ensureFE(); return body(); },
482 record: async (p, b, note, velocity, duration, spec, prog) => {
483 const r = await renderPool.call({ type: "record", params: p, body: b, note, velocity, duration, spec }, [], prog);
484 return { recording: r.recording as Recording, mic: r.mic as Float32Array, pickup: r.pickup as Float32Array, sampleRate: Number((r.info as { sampleRate: number }).sampleRate) };
485 },
486 computeShapes: async (p, prog) => (await bulkPool.call({ type: "feShapes", params: p }, [], prog)).shapes as FEShapes,
487 defaultShapesUrl: feDefaultShapesUrl,
488 status,
489 progress,
490 playAudio: (x, fs) => { void audio.play(x, fs, SIM_PLAY_GAIN); },
491 stopAudio: () => audio.stop(),
492 mix: (mic, pickup) => mixOutput(params, mic, pickup),
493};
494async function showPhysics() {
495 if (!physicsLoading) physicsLoading = import("./viz/index.ts").then((m) => (physics = new m.PhysicsView(physicsRoot, vizHost)));
496 status("Loading the 3D view…");
497 const v = await physicsLoading;
498 if (ui.tab === "physics") await v.show();
499}
087c169Physically simulated pizzicato double bass and an SF2 built from itJeremy Magland 501function buildTabs() {
502 const nav = $("#tabs"), panels = $("#panels");
503 nav.innerHTML = ""; panels.innerHTML = "";
504 for (const [id, label] of TABS) {
182eaafAdd a Physics 3D tab: slow-motion 3D replay of the simulationJeremy Magland 505 nav.append(el("button", { class: ui.tab === id ? "on" : "", onclick: () => { if (ui.tab === "physics" && id !== "physics") physics?.hide(); ui.tab = id; saveUi(); buildTabs(); } }, label));
087c169Physically simulated pizzicato double bass and an SF2 built from itJeremy Magland 506 const p = el("div", { class: "panel", id: `panel-${id}` });
507 p.hidden = ui.tab !== id;
508 panels.append(p);
509 }
510 $("#panel-sound").innerHTML = `<div class="plots"><figure><figcaption>Envelope (RMS, 20 ms), dB</figcaption><canvas id="cEnv"></canvas></figure><figure><figcaption>Spectrum of the first 0.5 s, dB re peak</figcaption><canvas id="cSpec"></canvas></figure><figure><figcaption>Waveform, first 60 ms (each normalised)</figcaption><canvas id="cWave"></canvas></figure><figure><figcaption>Mic vs pickup spectrum (first 0.5 s)</figcaption><canvas id="cMP"></canvas></figure></div>`;
511 $("#panel-spectro").innerHTML = `<div class="plots one"><figure><canvas id="cSgSim" class="tall"></canvas></figure><figure><canvas id="cSgRef" class="tall"></canvas></figure></div>`;
512 $("#panel-partials").innerHTML = `<div class="plots"><figure><figcaption>Partial level, dB re partial 1</figcaption><canvas id="cPL"></canvas></figure><figure><figcaption>Partial T60, s</figcaption><canvas id="cPT"></canvas></figure></div><div id="ptable"></div>`;
513 $("#panel-body").innerHTML = `<div class="bodyctl"><label>String <select id="bStr">${STRING_NAMES.map((s, i) => `<option value="${i}">${s}</option>`).join("")}</select></label><span id="bodyInfo" class="sub"></span></div><div class="plots"><figure><figcaption>Bridge admittance at the notch |Y|, dB re 1 s/kg</figcaption><canvas id="cY"></canvas></figure><figure><figcaption>Radiation: pressure at the mic per newton at the notch, dB re 1 Pa/N</figcaption><canvas id="cH"></canvas></figure></div><div id="modeList" class="modelist"></div>`;
514 $("#panel-sf2").innerHTML = `<div id="sf2Info"></div>`;
182eaafAdd a Physics 3D tab: slow-motion 3D replay of the simulationJeremy Magland 515 $("#panel-physics").append(physicsRoot);
087c169Physically simulated pizzicato double bass and an SF2 built from itJeremy Magland 516 ($("#bStr") as HTMLSelectElement).value = String(fingering(params, ui.note).string);
517 $("#bStr").addEventListener("change", drawBody);
518 if (ui.tab === "body") drawBody();
519 else if (ui.tab === "sf2") drawSf2Panel();
182eaafAdd a Physics 3D tab: slow-motion 3D replay of the simulationJeremy Magland 520 else if (ui.tab === "physics") void showPhysics();
087c169Physically simulated pizzicato double bass and an SF2 built from itJeremy Magland 521 else analyse();
522}
524const C_SIM = "var(--sim)", C_REF = "var(--ref)";
525const cssv = (v: string) => getComputedStyle(document.documentElement).getPropertyValue(v.slice(4, -1)).trim();
527async function analyse() {
528 if (!last || (ui.tab !== "sound" && ui.tab !== "spectro" && ui.tab !== "partials")) return;
529 const fs = last.fs, x = simAudio();
530 let ref: Float32Array | null = null;
14b3daaPoint to 'Ref SF2…' when no reference SoundFont is availableJeremy Magland 531 try { ref = await refAudio(last.note, last.velocity); } catch { ref = null; if (!refData) status("Rendered. For the A/B comparison, choose a reference SoundFont with 'Ref SF2…' (e.g. GeneralUser GS)."); }
087c169Physically simulated pizzicato double bass and an SF2 built from itJeremy Magland 532 const sim = cssv(C_SIM), refc = cssv(C_REF);
533 const onset = (a: Float32Array) => { let pk = 0; for (const v of a) pk = Math.max(pk, Math.abs(v)); let s = 0; while (s < a.length && Math.abs(a[s]) < 0.02 * pk) s++; return a.subarray(Math.max(0, s - 88)); };
534 const xs = onset(x), rs = ref ? onset(ref) : null;
535 const ed = envelopeDecay(xs, fs);
536 const metrics = [`sim: t20 ${ed.t20.toFixed(2)} s, centroid ${centroid(xs, fs, 0, 0.15).toFixed(0)} Hz`];
537 if (rs) { const er = envelopeDecay(rs, 44100); metrics.push(`ref: t20 ${er.t20.toFixed(2)} s, centroid ${centroid(rs, 44100, 0, 0.15).toFixed(0)} Hz`); }
538 $("#metrics").textContent = metrics.join(" · ");
539 if (ui.tab === "sound") {
540 const env = (a: Float32Array, sr: number) => { const w = Math.round(0.02 * sr), t: number[] = [], y: number[] = []; let pk = -300; for (let s = 0; s + w <= a.length; s += w) { let e = 0; for (let i = s; i < s + w; i++) e += a[i] * a[i]; const db = 10 * Math.log10(e / w + 1e-20); t.push(s / sr); y.push(db); pk = Math.max(pk, db); } return { t, y: y.map((v) => v - pk) }; };
541 const es = env(xs, fs), er = rs ? env(rs, 44100) : null;
542 linePlot($("#cEnv") as HTMLCanvasElement, [{ x: es.t, y: es.y, color: sim, label: "sim" }, ...(er ? [{ x: er.t, y: er.y, color: refc, label: "ref" }] : [])], { ymin: -70, ymax: 2, xlabel: "s" });
543 const spec = (a: Float32Array, sr: number) => { const n = 16384; const sp = spectrumDb(a, 0, n); const pk = Math.max(...sp); const f = Array.from(sp, (_, i) => (i * sr) / n); return { f, y: Array.from(sp, (v) => v - pk) }; };
544 const ss = spec(xs, fs), sr2 = rs ? spec(rs, 44100) : null;
545 const marks = Array.from({ length: 12 }, (_, i) => ({ x: (i + 1) * midiToHz(last!.note) }));
546 linePlot($("#cSpec") as HTMLCanvasElement, [{ x: ss.f, y: ss.y, color: sim, label: "sim", width: 1 }, ...(sr2 ? [{ x: sr2.f, y: sr2.y, color: refc, label: "ref", width: 1 }] : [])], { xlog: true, xmin: 25, xmax: 12000, ymin: -90, ymax: 3, xlabel: "Hz", marks });
547 const wave = (a: Float32Array, sr: number) => { const n = Math.round(0.06 * sr); let pk = 0; for (let i = 0; i < n && i < a.length; i++) pk = Math.max(pk, Math.abs(a[i])); return { t: Array.from({ length: Math.min(n, a.length) }, (_, i) => (i / sr) * 1000), y: Array.from(a.subarray(0, n), (v) => v / (pk || 1)) }; };
548 const ws = wave(xs, fs), wr = rs ? wave(rs, 44100) : null;
549 linePlot($("#cWave") as HTMLCanvasElement, [...(wr ? [{ x: wr.t, y: wr.y, color: refc, label: "ref", width: 1 }] : []), { x: ws.t, y: ws.y, color: sim, label: "sim", width: 1.2 }], { ymin: -1.05, ymax: 1.05, xlabel: "ms" });
550 const sm = spec(onset(last.mic), fs), sp = spec(onset(last.pickup), fs);
551 linePlot($("#cMP") as HTMLCanvasElement, [{ x: sm.f, y: sm.y, color: sim, label: "mic", width: 1 }, { x: sp.f, y: sp.y, color: cssv("var(--alt)"), label: "pickup", width: 1 }], { xlog: true, xmin: 25, xmax: 12000, ymin: -90, ymax: 3, xlabel: "Hz", marks });
552 } else if (ui.tab === "spectro") {
553 const sg = spectrogram(xs, 4096, 512);
554 spectrogramPlot($("#cSgSim") as HTMLCanvasElement, sg.frames, fs, 4096, 512, { title: "simulation" });
555 if (rs) { const sgr = spectrogram(rs, 4096, 512); spectrogramPlot($("#cSgRef") as HTMLCanvasElement, sgr.frames, 44100, 4096, 512, { title: `reference (${refName} prog ${ui.refProgram})` }); }
556 } else if (ui.tab === "partials") {
557 const f1 = midiToHz(last.note);
558 const ps = partialDecay(xs, fs, f1, 24), pr = rs ? partialDecay(rs, 44100, f1, 24) : [];
559 const rel = (a: { levelDb: number }[]) => a.map((p) => p.levelDb - (a[0]?.levelDb ?? 0));
560 linePlot($("#cPL") as HTMLCanvasElement, [{ x: ps.map((p) => p.n), y: rel(ps), color: sim, label: "sim" }, { x: pr.map((p) => p.n), y: rel(pr), color: refc, label: "ref" }], { ymin: -70, ymax: 15, xlabel: "partial" });
561 linePlot($("#cPT") as HTMLCanvasElement, [{ x: ps.map((p) => p.n), y: ps.map((p) => Math.min(30, p.t60)), color: sim, label: "sim", points: true }, { x: pr.map((p) => p.n), y: pr.map((p) => Math.min(30, p.t60)), color: refc, label: "ref", points: true }], { ymin: 0, xlabel: "partial" });
562 const rows = ps.map((p, i) => `<tr><td>${p.n}</td><td>${p.f.toFixed(1)}</td><td>${(p.f / (p.n * f1)).toFixed(4)}</td><td>${(p.levelDb - ps[0].levelDb).toFixed(1)}</td><td>${pr[i] ? (pr[i].levelDb - pr[0].levelDb).toFixed(1) : ""}</td><td>${isFinite(p.t60) ? p.t60.toFixed(2) : "∞"}</td><td>${pr[i] && isFinite(pr[i].t60) ? pr[i].t60.toFixed(2) : ""}</td></tr>`).join("");
563 $("#ptable").innerHTML = `<table class="ptab"><tr><th>n</th><th>f Hz</th><th>f / (n f1)</th><th>sim dB</th><th>ref dB</th><th>sim T60</th><th>ref T60</th></tr>${rows}</table><p class="sub">The reference sample is pitch-shifted, looped and shaped by envelopes, so its T60s describe the SoundFont's envelopes, not a string.</p>`;
564 }
565}
567function drawBody() {
568 if (ui.tab !== "body") return;
569 const b = body();
570 const si = Number(($("#bStr") as HTMLSelectElement).value || 0);
571 const N = 600, f = Array.from({ length: N }, (_, i) => 30 * Math.pow(8000 / 30, i / (N - 1)));
572 const db = (re: Float64Array, im: Float64Array) => Array.from(re, (r, i) => 20 * Math.log10(Math.hypot(r, im[i]) + 1e-20));
573 const yy = bridgeAdmittance(b, f, si, "y"), yz = bridgeAdmittance(b, f, si, "z");
574 const marks = b.modes.filter((m) => m.label && m.f < 1000).map((m) => ({ x: m.f, label: m.label }));
575 linePlot($("#cY") as HTMLCanvasElement, [{ x: f, y: db(yy.re, yy.im), color: cssv(C_SIM), label: "vertical" }, { x: f, y: db(yz.re, yz.im), color: cssv("var(--alt)"), label: "lateral" }], { xlog: true, xlabel: "Hz", marks: marks.length < 30 ? marks : [] });
576 const hy = radiationTransfer(b, f, si, "y"), hz = radiationTransfer(b, f, si, "z");
577 linePlot($("#cH") as HTMLCanvasElement, [{ x: f, y: db(hy.re, hy.im), color: cssv(C_SIM), label: "vertical force" }, { x: f, y: db(hz.re, hz.im), color: cssv("var(--alt)"), label: "lateral force" }], { xlog: true, xlabel: "Hz" });
578 $("#bodyInfo").textContent = `${b.source} body, ${b.modes.length} modes`;
579 const list = b.modes.slice(0, 60).map((m) => `<tr><td>${m.label ?? ""}</td><td>${m.f.toFixed(1)}</td><td>${(1 / (2 * m.zeta)).toFixed(0)}</td><td>${(1 / (m.by[si] ** 2)).toFixed(2)}</td><td>${Math.abs(m.bz[si] / (m.by[si] || 1e-12)).toFixed(2)}</td><td>${Math.hypot(m.radRe, m.radIm).toExponential(1)}</td></tr>`).join("");
580 $("#modeList").innerHTML = `<table class="ptab"><tr><th></th><th>f Hz</th><th>Q</th><th>m_eff kg</th><th>|lat/vert|</th><th>|rad|</th></tr>${list}</table>`;
581}
583function drawSf2Panel() {
584 if (ui.tab !== "sf2") return;
585 const jobs = sampleJobs(params);
586 const notes = sampleNotes(params);
587 const total = jobs.reduce((s, j) => s + j.length, 0);
588 $("#sf2Info").innerHTML = `
589 <p>${notes.length} notes (${notes.map(noteName).join(", ")}) × ${params.sf2.velocities.length} velocity layers (${params.sf2.velocities.join(" / ")}) = ${jobs.length} samples, ${total.toFixed(0)} s of audio, about ${(total * 44100 * 2 / 1e6).toFixed(1)} MB. Body: ${useFE() ? "FE" : "parametric"}; mix mic ${params.output.micMix} + pickup ${params.output.pickupMix}; rendered at ${params.sf2.oversample}× oversampling on ${nCores} workers.</p>
590 <div class="btnrow"><button id="bBuild" class="primary">Build SF2</button><button id="bDl" ${builtSf2 ? "" : "disabled"}>Download SF2</button><button id="bDlP">Download params</button><button id="bPlayBuilt" ${builtSf2 ? "" : "disabled"}>Play it on the keys</button></div>
591 <p>Prebuilt: <a href="${prebuiltSf2Url}" download="acoustic-bass.sf2">acoustic-bass.sf2</a> (default parameters, FE body). <button id="bPrebuilt" class="small">Play it on the keys</button></p>
592 <p class="sub">The SF2 has one preset, "${params.sf2.presetName}" (bank ${params.sf2.bank}, program ${params.sf2.program}). Each sample covers the keys nearest its root; layers ${[1, ...params.sf2.layerTop.map((v) => v + 1)].map((lo, i) => `${lo}–${i < params.sf2.layerTop.length ? params.sf2.layerTop[i] : 127}`).join(", ")}. For the same SF2 from the command line: save the params and run <code>node scripts/build_sf2.ts --params params.json</code>.</p>`;
593 $("#bBuild").addEventListener("click", () => void buildSf2InBrowser());
594 $("#bDl").addEventListener("click", () => { if (builtSf2) download(new Blob([builtSf2 as BlobPart], { type: "audio/x-soundfont" }), "acoustic-bass.sf2"); });
595 $("#bDlP").addEventListener("click", () => download(new Blob([JSON.stringify(params, null, 2)], { type: "application/json" }), "acoustic-bass-params.json"));
596 $("#bPlayBuilt").addEventListener("click", () => { ui.playMode = "built"; saveUi(); syncTransport(); void ensureLiveBank(); });
597 $("#bPrebuilt").addEventListener("click", async () => {
598 status("Loading the prebuilt SF2…");
599 builtSf2 = new Uint8Array(await (await fetch(prebuiltSf2Url)).arrayBuffer());
600 builtKey++;
601 ui.playMode = "built"; saveUi(); syncTransport();
602 await ensureLiveBank();
603 status("Prebuilt SF2 loaded: the keys play it live");
604 drawSf2Panel();
605 });
606}
608async function buildSf2InBrowser() {
609 await ensureFE();
610 const p = cloneParams(params);
611 p.engine.oversample = p.sf2.oversample;
612 const b = useFE() && feBody ? feBody : parametricBody(p);
613 const jobs = sampleJobs(p);
614 const results: Float32Array[] = new Array(jobs.length);
615 let done = 0;
616 const t0 = performance.now();
617 status(`Building SF2: 0/${jobs.length}`);
618 progress(0);
619 try {
620 await Promise.all(jobs.map((j, i) => bulkPool.call({ type: "render", params: p, body: b, note: j.note, velocity: j.velocity, duration: j.length }).then((r) => {
621 results[i] = mixOutput(p, r.mic as Float32Array, r.pickup as Float32Array);
622 done++; progress(done / jobs.length); status(`Building SF2: ${done}/${jobs.length}`);
623 })));
624 const comment = `Pizzicato double bass simulated by acoustic-base (${p.engine.stringModel} strings, ${b.source} body with ${b.modes.length} modes, mic ${p.output.micMix} + pickup ${p.output.pickupMix}).`;
625 builtSf2 = buildSf2(p, jobs, results, p.engine.sampleRate, comment).sf2;
626 builtKey++;
627 status(`SF2 built: ${jobs.length} samples, ${(builtSf2.length / 1e6).toFixed(1)} MB, ${((performance.now() - t0) / 1000).toFixed(0)} s`);
628 } catch (e) { status(`SF2 build failed: ${(e as Error).message.split("\n")[0]}`, true); }
629 drawSf2Panel();
630}
632// ---------------------------------------------------------------- transport
634function updateNoteInfo() {
635 $("#noteName").textContent = `${noteName(ui.note)} ${midiToHz(ui.note).toFixed(1)} Hz`;
636 const fg = fingering(params, ui.note);
637 const where = fg.shift < 0 ? `${STRING_NAMES[0]} string on the extension` : fg.shift === 0 ? `open ${STRING_NAMES[fg.string]} string` : `${STRING_NAMES[fg.string]} string, +${fg.shift} semitones`;
638 let s = ` ${where}, vibrating length ${(fg.length * 100).toFixed(1)} cm`;
639 if (last && last.note === ui.note) {
640 const i = last.info as { releaseForce: number; slipTime: number; stickTime: number };
641 s += ` · release ${i.releaseForce.toFixed(1)} N, slip ${(i.slipTime * 1000).toFixed(1)} ms, pull ${(i.stickTime * 1000).toFixed(0)} ms`;
642 }
643 $("#fingerInfo").textContent = s;
644}
646function syncTransport() {
647 ($("#vel") as HTMLInputElement).value = String(ui.velocity);
648 $("#velV").textContent = String(ui.velocity);
649 ($("#auto") as HTMLInputElement).checked = ui.auto;
650 ($("#playMode") as HTMLSelectElement).value = ui.playMode;
651 ($("#vol") as HTMLInputElement).value = String(ui.volume);
652 ($("#mMic") as HTMLInputElement).value = String(params.output.micMix);
653 ($("#mPick") as HTMLInputElement).value = String(params.output.pickupMix);
654 updateNoteInfo();
655}
657function download(blob: Blob, name: string) {
658 const a = el("a", { href: URL.createObjectURL(blob), download: name });
659 document.body.append(a); a.click(); a.remove();
660 setTimeout(() => URL.revokeObjectURL(a.href), 5000);
661}
663$("#vel").addEventListener("input", () => { ui.velocity = Number(($("#vel") as HTMLInputElement).value); $("#velV").textContent = String(ui.velocity); saveUi(); });
664$("#vel").addEventListener("change", () => { if (ui.auto) void renderCurrent(false); });
665$("#auto").addEventListener("change", () => { ui.auto = ($("#auto") as HTMLInputElement).checked; saveUi(); });
666$("#playMode").addEventListener("change", () => { ui.playMode = ($("#playMode") as HTMLSelectElement).value as typeof ui.playMode; saveUi(); if (ui.playMode !== "sim") void ensureLiveBank().catch((e) => status(String(e), true)); });
667$("#vol").addEventListener("input", () => { ui.volume = Number(($("#vol") as HTMLInputElement).value); audio.setVolume(ui.volume); saveUi(); });
668$("#bRender").addEventListener("click", () => void renderCurrent(true));
669$("#bSim").addEventListener("click", () => void playSim());
670$("#bRef").addEventListener("click", () => void playRef());
671$("#bAB").addEventListener("click", async () => { if (!last) await renderCurrent(false); await playSim(); await new Promise((r) => setTimeout(r, 300)); await playRef(); });
672$("#bWav").addEventListener("click", () => { if (last) download(new Blob([encodeWav(simAudio(), last.fs, { scale: SIM_PLAY_GAIN }) as BlobPart], { type: "audio/wav" }), `bass_${noteName(last.note)}_v${last.velocity}.wav`); });
673for (const [id, path] of [["#mMic", "output.micMix"], ["#mPick", "output.pickupMix"]] as const) {
674 $(id).addEventListener("input", () => { setPath(params, path, Number(($(id) as HTMLInputElement).value)); save(LS_PARAMS, params); syncControls(); });
675 $(id).addEventListener("change", () => { void analyse(); });
676}
677$("#bRefFile").addEventListener("click", () => ($("#fRef") as HTMLInputElement).click());
678$("#fRef").addEventListener("change", () => { const f = ($("#fRef") as HTMLInputElement).files?.[0]; if (f) void setRefFile(f); });
679$("#bSave").addEventListener("click", () => download(new Blob([JSON.stringify(params, null, 2)], { type: "application/json" }), "acoustic-bass-params.json"));
680$("#bLoad").addEventListener("click", () => ($("#fParams") as HTMLInputElement).click());
681$("#fParams").addEventListener("change", async () => { const f = ($("#fParams") as HTMLInputElement).files?.[0]; if (!f) return; params = mergeParams(JSON.parse(await f.text())); save(LS_PARAMS, params); syncControls(); syncTransport(); onParamsChanged(); });
682$("#bReset").addEventListener("click", () => { if (!confirm("Restore all parameters to their defaults?")) return; params = defaultParams(); save(LS_PARAMS, params); syncControls(); syncTransport(); onParamsChanged(); });
683window.addEventListener("resize", () => { if (ui.tab === "body") drawBody(); else void analyse(); });
685buildParamPanel();
686buildTabs();
687drawKeyboard();
688syncTransport();
689updateFeInfo();
690status("Click a key to render a note (or press Render). A/B compares with the reference SoundFont.");
691void ensureFE().catch(() => { /* reported by computeFE */ });