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";
16// ---------------------------------------------------------------- workers
18type Reply = { type: string; id: number; frac?: number; msg?: string; error?: string; [k: string]: unknown };
20class Pool {
21 private idle: Worker[] = [];
22 private queue: { msg: Record<string, unknown>; transfer: Transferable[]; resolve: (r: Reply) => void; reject: (e: Error) => void; progress?: (f: number, msg?: string) => void }[] = [];
23 private pending = new Map<number, { resolve: (r: Reply) => void; reject: (e: Error) => void; progress?: (f: number, msg?: string) => void; worker: Worker }>();
24 private nextId = 1;
25 constructor(n: number) {
26 for (let i = 0; i < n; i++) {
27 const w = new Worker(new URL("./worker.ts", import.meta.url), { type: "module" });
28 w.onmessage = (e: MessageEvent<Reply>) => {
29 const r = e.data, p = this.pending.get(r.id);
30 if (!p) return;
31 if (r.type === "progress") { p.progress?.(r.frac ?? 0, r.msg); return; }
32 this.pending.delete(r.id);
33 this.idle.push(p.worker);
34 if (r.type === "error") p.reject(new Error(r.error)); else p.resolve(r);
35 this.pump();
36 };
37 this.idle.push(w);
38 }
39 }
40 call(msg: Record<string, unknown>, transfer: Transferable[] = [], progress?: (f: number, msg?: string) => void): Promise<Reply> {
41 return new Promise((resolve, reject) => { this.queue.push({ msg, transfer, resolve, reject, progress }); this.pump(); });
42 }
43 private pump() {
44 while (this.idle.length && this.queue.length) {
45 const w = this.idle.pop()!, job = this.queue.shift()!;
46 const id = this.nextId++;
47 this.pending.set(id, { resolve: job.resolve, reject: job.reject, progress: job.progress, worker: w });
48 w.postMessage({ ...job.msg, id }, job.transfer);
49 }
50 }
51 get size() { return this.idle.length + this.pending.size; }
52}
54const nCores = Math.max(2, Math.min(10, (navigator.hardwareConcurrency || 4) - 1));
55const renderPool = new Pool(1); // interactive renders
56const bulkPool = new Pool(nCores); // SF2 builds, FE
57const refPool = new Pool(1); // holds the reference SoundFont
59// ---------------------------------------------------------------- state
61const LS_PARAMS = "acoustic-base.params", LS_FE = "acoustic-base.feBody", LS_UI = "acoustic-base.ui";
62const load = <T,>(k: string): T | null => { try { const s = localStorage.getItem(k); return s ? (JSON.parse(s) as T) : null; } catch { return null; } };
63const save = (k: string, v: unknown) => { try { localStorage.setItem(k, JSON.stringify(v)); } catch { /* storage full or blocked */ } };
65let params: Params = mergeParams(load(LS_PARAMS) ?? {});
66let feBody: BodyModel | null = load<BodyModel>(LS_FE);
67const 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 {
68 note: number; velocity: number; auto: boolean; playMode: "sim" | "built" | "ref"; tab: string; refProgram: number; refBank: number; volume: number;
69};
70let last: { key: string; mic: Float32Array; pickup: Float32Array; info: Record<string, unknown>; fs: number; note: number; velocity: number } | null = null;
71const refCache = new Map<string, Float32Array>();
72let refLoaded: Promise<void> | null = null;
73let refName = "";
74let builtSf2: Uint8Array | null = null;
75let builtKey = 0;
76let renderSeq = 0;
77const audio = new Audio();
78audio.setVolume(ui.volume);
80const saveUi = () => save(LS_UI, ui);
81const feFresh = () => !!feBody && feBody.meta?.feKey === feInputsKey(params);
82const useFE = () => params.engine.bodyModel === "fe";
83const body = (): BodyModel => (useFE() && feBody ? feBody : parametricBody(params));
84const 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]);
86// ---------------------------------------------------------------- DOM
88const $ = <T extends HTMLElement = HTMLElement>(sel: string) => document.querySelector(sel) as T;
89const el = <K extends keyof HTMLElementTagNameMap>(tag: K, attrs: Record<string, unknown> = {}, ...kids: (Node | string)[]): HTMLElementTagNameMap[K] => {
90 const e = document.createElement(tag);
91 for (const [k, v] of Object.entries(attrs)) {
92 if (k === "class") e.className = String(v);
93 else if (k.startsWith("on")) e.addEventListener(k.slice(2), v as EventListener);
94 else if (v !== undefined && v !== false) e.setAttribute(k, String(v));
95 }
96 for (const c of kids) e.append(c);
97 return e;
98};
100$("#app").innerHTML = `
101<header>
102 <h1>Acoustic Bass <span>physical model</span></h1>
103 <div class="status" id="status"></div>
104 <div class="hbtns">
105 <button id="bLoad" title="Load parameters (JSON)">Load…</button>
106 <button id="bSave" title="Save parameters (JSON)">Save</button>
107 <button id="bReset" title="Restore the default parameters">Reset</button>
108 <input type="file" id="fParams" accept=".json" hidden />
109 </div>
110</header>
111<div class="main">
112 <aside id="params"></aside>
113 <section class="work">
114 <div class="transport">
115 <div class="noteinfo"><b id="noteName"></b><span id="fingerInfo"></span></div>
116 <label>Velocity <input type="range" id="vel" min="1" max="127" /><span id="velV"></span></label>
117 <button id="bRender" class="primary">Render ▶</button>
118 <button id="bSim" title="Play the last simulation render">Sim</button>
119 <button id="bRef" title="Play the reference SoundFont, same note and velocity">Ref</button>
120 <button id="bAB" title="Simulation, then reference">A/B</button>
121 <label class="chk"><input type="checkbox" id="auto" /> auto-render</label>
122 <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>
123 <label>Vol <input type="range" id="vol" min="0" max="1.5" step="0.01" /></label>
124 <button id="bWav" title="Download the render as WAV">WAV</button>
125 <button id="bRefFile" title="Choose the reference SoundFont (stays on this computer); bank 0 program 32 is played">Ref SF2…</button>
126 <input type="file" id="fRef" accept=".sf2,.sf3" hidden />
127 </div>
128 <div id="keyboard"></div>
129 <div class="progress"><div id="prog"></div></div>
130 <div class="mix">
131 <label>Mic <input type="range" id="mMic" min="0" max="1" step="0.01" /></label>
132 <label>Pickup <input type="range" id="mPick" min="0" max="1" step="0.01" /></label>
133 <span class="hint">mix applies without re-rendering</span>
134 <span id="metrics" class="metrics"></span>
135 </div>
136 <nav class="tabs" id="tabs"></nav>
137 <div id="panels"></div>
138 </section>
139</div>`;
141const status = (s: string, err = false) => { const e = $("#status"); e.textContent = s; e.classList.toggle("err", err); };
142const progress = (f: number) => { ($("#prog") as HTMLDivElement).style.width = `${Math.round(Math.max(0, Math.min(1, f)) * 100)}%`; };
144// ---------------------------------------------------------------- parameter panel
146const groups = new Map<string, ParamInfo[]>();
147for (const pi of PARAM_INFO) { if (!groups.has(pi.group)) groups.set(pi.group, []); groups.get(pi.group)!.push(pi); }
148const controls: { pi: ParamInfo; sync: () => void }[] = [];
149const openGroups = new Set<string>(load<string[]>("acoustic-base.groups") ?? ["Right hand", "Output"]);
151function fmtNum(v: number): string {
152 if (v === 0) return "0";
153 const a = Math.abs(v);
154 if (a >= 1e5 || a < 1e-3) return v.toExponential(2);
155 return String(+v.toPrecision(4));
156}
158function buildParamPanel() {
159 const root = $("#params");
160 root.innerHTML = "";
161 controls.length = 0;
162 for (const [g, list] of groups) {
163 const det = el("details", { class: "grp" });
164 if (openGroups.has(g)) det.open = true;
165 det.addEventListener("toggle", () => { if (det.open) openGroups.add(g); else openGroups.delete(g); save("acoustic-base.groups", [...openGroups]); });
166 det.append(el("summary", {}, g));
167 for (const pi of list) {
168 const row = el("div", { class: "prow", title: pi.help ?? "" });
169 row.append(el("span", { class: "plabel" }, pi.label));
170 const sc = pi.scale ?? 1;
171 if (pi.kind === "bool") {
172 const cb = el("input", { type: "checkbox" }) as HTMLInputElement;
173 cb.addEventListener("change", () => setParam(pi.path, cb.checked));
174 row.append(cb);
175 controls.push({ pi, sync: () => { cb.checked = !!getPath(params, pi.path); } });
176 } else if (pi.kind === "select") {
177 const s = el("select") as HTMLSelectElement;
178 for (const o of pi.options ?? []) s.append(el("option", { value: o }, o));
179 s.addEventListener("change", () => setParam(pi.path, s.value));
180 row.append(s);
181 controls.push({ pi, sync: () => { s.value = String(getPath(params, pi.path)); } });
182 } else {
183 const r = el("input", { type: "range", min: 0, max: 1000, step: 1 }) as HTMLInputElement;
184 const n = el("input", { type: "text", class: "num" }) as HTMLInputElement;
185 const lo = pi.min ?? 0, hi = pi.max ?? 1;
186 const toSlider = (v: number) => (pi.log ? Math.log(v / lo) / Math.log(hi / lo) : (v - lo) / (hi - lo)) * 1000;
187 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); };
188 r.addEventListener("input", () => { const v = fromSlider(Number(r.value)); n.value = fmtNum(v * sc); setParam(pi.path, v); });
189 n.addEventListener("change", () => { const v = Number(n.value) / sc; if (isFinite(v)) { setParam(pi.path, v); r.value = String(toSlider(v)); } });
190 row.append(r, n, el("span", { class: "unit" }, pi.unit ?? ""));
191 controls.push({ pi, sync: () => { const v = Number(getPath(params, pi.path)); r.value = String(toSlider(v)); n.value = fmtNum(v * sc); } });
192 }
193 det.append(row);
194 }
195 if (g === "Body (parametric)") det.append(lowModesEditor());
196 if (g === "Body (FE)") det.append(feControls());
197 root.append(det);
198 }
199 syncControls();
200}
202function syncControls() { for (const c of controls) c.sync(); }
204let changeTimer = 0;
205function setParam(path: string, v: unknown) {
206 setPath(params, path, v);
207 save(LS_PARAMS, params);
208 window.clearTimeout(changeTimer);
209 changeTimer = window.setTimeout(onParamsChanged, 250);
210}
212function onParamsChanged() {
213 updateFeInfo();
214 drawKeyboard();
215 updateNoteInfo();
216 if (ui.tab === "body") drawBody();
217 if (ui.tab === "sf2") drawSf2Panel();
218 if (ui.auto && last && last.key !== renderKey(ui.note, ui.velocity)) void renderCurrent(false);
219}
221function lowModesEditor(): HTMLElement {
222 const wrap = el("div", { class: "lowmodes" });
223 const draw = () => {
224 wrap.innerHTML = "";
225 const t = el("table");
226 t.append(el("tr", {}, ...["", "f Hz", "Q", "mass kg", "lat", "vol m²", ""].map((h) => el("th", {}, h))));
227 params.body.lowModes.forEach((m, i) => {
228 const tr = el("tr");
229 tr.append(el("td", {}, m.label));
230 for (const k of ["f", "q", "mass", "lateral", "rad"] as const) {
231 const inp = el("input", { type: "text", value: String(m[k]), class: "num" }) as HTMLInputElement;
232 inp.addEventListener("change", () => { const v = Number(inp.value); if (isFinite(v)) { m[k] = v; setParam("body.lowModes", params.body.lowModes); } });
233 tr.append(el("td", {}, inp));
234 }
235 tr.append(el("td", {}, el("button", { class: "small", onclick: () => { params.body.lowModes.splice(i, 1); setParam("body.lowModes", params.body.lowModes); draw(); } }, "×")));
236 t.append(tr);
237 });
238 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,
239 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"));
240 };
241 draw();
242 return wrap;
243}
245function feControls(): HTMLElement {
246 const wrap = el("div", { class: "fectl" });
247 const info = el("div", { class: "sub", id: "feInfo" });
248 const bCompute = el("button", { class: "primary small", onclick: () => void computeFE() }, "Compute FE body");
249 const bDown = el("button", { class: "small", onclick: () => { if (feBody) download(new Blob([JSON.stringify(feBody)], { type: "application/json" }), "fe-body.json"); } }, "Download");
250 const fIn = el("input", { type: "file", accept: ".json", hidden: true }) as HTMLInputElement;
251 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(); });
252 const bUp = el("button", { class: "small", onclick: () => fIn.click() }, "Load…");
253 wrap.append(el("div", { class: "btnrow" }, bCompute, bDown, bUp, fIn), info);
254 return wrap;
255}
257function updateFeInfo() {
258 const e = document.getElementById("feInfo");
259 if (!e) return;
260 if (!feBody) { e.textContent = "No FE body yet. Compute it (geometry and woods above), then set Engine → Body model to fe."; return; }
261 const low = feBody.modes.filter((m) => m.f < 400).slice(0, 8).map((m) => `${m.label ?? ""} ${m.f.toFixed(0)}`).join(", ");
262 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)."}`;
263}
265async function computeFE() {
266 status("Computing the FE body…");
267 progress(0);
268 try {
269 const r = await bulkPool.call({ type: "fe", params: cloneParams(params) }, [], (f, msg) => { progress(f); if (msg) status(`FE: ${msg}`); });
270 feBody = r.body as BodyModel;
271 feBody.meta = { ...(feBody.meta ?? {}), elapsed: r.elapsed };
272 save(LS_FE, feBody);
273 status(`FE body: ${feBody.modes.length} modes in ${Number(r.elapsed).toFixed(1)} s`);
274 if (params.engine.bodyModel !== "fe") setParam("engine.bodyModel", "fe"); else { drawBody(); drawSf2Panel(); }
275 syncControls();
276 } catch (e) { status(`FE failed: ${(e as Error).message.split("\n")[0]}`, true); }
277 progress(1);
278 updateFeInfo();
279}
281// ---------------------------------------------------------------- keyboard
283const KB_LO = 24, KB_HI = 62;
284const isBlack = (n: number) => [1, 3, 6, 8, 10].includes(n % 12);
285const held = new Set<number>();
287function drawKeyboard() {
288 const kb = $("#keyboard");
289 kb.innerHTML = "";
290 const whites = [];
291 for (let n = KB_LO; n <= KB_HI; n++) if (!isBlack(n)) whites.push(n);
292 const ww = 100 / whites.length;
293 const roots = new Set(sampleNotes(params));
294 let wi = 0;
295 for (let n = KB_LO; n <= KB_HI; n++) {
296 const black = isBlack(n);
297 const left = black ? (wi - 0.32) * ww : wi * ww;
298 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)` });
299 k.style.left = `${left}%`; k.style.width = `${black ? ww * 0.64 : ww}%`;
300 if (roots.has(n)) k.append(el("i", { class: "root" }));
301 if (!black && n % 12 === 0) k.append(el("span", {}, noteName(n)));
302 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); });
303 kb.append(k);
304 if (!black) wi++;
305 }
306}
308let pointerNote = -1;
309window.addEventListener("pointerup", () => { if (pointerNote >= 0) { keyUp(pointerNote); pointerNote = -1; } });
311/** update the selected / held marks without rebuilding the keyboard */
312function markKeys() {
313 document.querySelectorAll<HTMLElement>("#keyboard .key").forEach((k) => {
314 const n = Number(k.dataset.n);
315 k.classList.toggle("sel", n === ui.note);
316 k.classList.toggle("down", held.has(n));
317 });
318}
320function keyDown(n: number, vel: number) {
321 held.add(n);
322 if (ui.playMode === "sim") {
323 ui.note = n; ui.velocity = vel; saveUi(); syncTransport();
324 void renderCurrent(true);
325 } else {
326 void (async () => { await ensureLiveBank(); audio.noteOn(n, vel); })();
327 }
328 markKeys();
329}
330function keyUp(n: number) {
331 held.delete(n);
332 if (ui.playMode !== "sim") audio.noteOff(n);
333 markKeys();
334}
336async function ensureLiveBank() {
337 if (ui.playMode === "built") {
338 if (!builtSf2) { status("Build the SF2 first (SF2 tab)", true); return; }
339 await audio.loadBank(`built${builtKey}`, builtSf2.buffer.slice(builtSf2.byteOffset, builtSf2.byteOffset + builtSf2.byteLength) as ArrayBuffer, params.sf2.bank, params.sf2.program);
340 } else if (ui.playMode === "ref") {
341 const data = await fetchRef();
342 await audio.loadBank(`ref:${refName}:${data.byteLength}`, data, ui.refBank, ui.refProgram);
343 }
344}
346// computer keyboard: A W S E D F T G Y H U J K O L P ; from C of the base octave
347const KEYMAP = "awsedftgyhujkolp;";
348let kbBase = 24;
349window.addEventListener("keydown", (e) => {
350 if (e.repeat || (e.target as HTMLElement).tagName === "INPUT" || (e.target as HTMLElement).tagName === "SELECT") return;
351 const i = KEYMAP.indexOf(e.key.toLowerCase());
352 if (i >= 0) { keyDown(kbBase + i, ui.velocity); return; }
353 if (e.key === "z") kbBase = Math.max(12, kbBase - 12);
354 if (e.key === "x") kbBase = Math.min(72, kbBase + 12);
355 if (e.key === " " && ui.playMode === "sim" && last) { e.preventDefault(); void playSim(); }
356});
357window.addEventListener("keyup", (e) => { const i = KEYMAP.indexOf(e.key.toLowerCase()); if (i >= 0) keyUp(kbBase + i); });
359// Web MIDI
360if ("requestMIDIAccess" in navigator) {
361 navigator.requestMIDIAccess().then((acc) => {
362 const hook = () => acc.inputs.forEach((inp) => { inp.onmidimessage = (ev) => {
363 const d = ev.data; if (!d) return;
364 const st = d[0] & 0xf0;
365 if (st === 0x90 && d[2] > 0) keyDown(d[1], d[2]);
366 else if (st === 0x80 || (st === 0x90 && d[2] === 0)) keyUp(d[1]);
367 else if (st === 0xb0 && d[1] === 64) audio.sustain(d[2] >= 64);
368 }; });
369 hook(); acc.onstatechange = hook;
370 }).catch(() => { /* no MIDI */ });
371}
373// ---------------------------------------------------------------- render / reference
375/** Make sure the FE body matches the parameters (when it is in use): load the shipped default or compute. */
376let feEnsuring: Promise<void> | null = null;
377async function ensureFE(): Promise<void> {
378 if (!useFE() || feFresh()) return;
379 if (!feEnsuring) feEnsuring = (async () => {
380 try {
381 const r = await fetch(feDefaultUrl);
382 if (r.ok) { const b = (await r.json()) as BodyModel; if (b.meta?.feKey === feInputsKey(params)) { feBody = b; save(LS_FE, b); updateFeInfo(); return; } }
383 } catch { /* not served */ }
384 await computeFE();
385 })().finally(() => { feEnsuring = null; });
386 return feEnsuring;
387}
389async function renderCurrent(play: boolean) {
390 await ensureFE();
391 const note = ui.note, vel = ui.velocity;
392 const key = renderKey(note, vel);
393 if (last && last.key === key) { if (play) void playSim(); return; }
394 const seq = ++renderSeq;
395 status(`Rendering ${noteName(note)} v${vel}…`);
396 progress(0);
397 const b = useFE() && feBody ? feBody : undefined;
398 try {
399 const r = await renderPool.call({ type: "render", params: cloneParams(params), body: b, note, velocity: vel }, [], (f) => { if (seq === renderSeq) progress(f); });
400 if (seq !== renderSeq) return;
401 const info = r.info as Record<string, unknown>;
402 last = { key, mic: r.mic as Float32Array, pickup: r.pickup as Float32Array, info, fs: Number(info.sampleRate), note, velocity: vel };
403 progress(1);
404 status(`${noteName(note)} v${vel}: rendered in ${Number(info.elapsed).toFixed(2)} s (${(info.modeCounts as { body: number }).body} body modes)`);
405 updateNoteInfo();
406 analyse();
407 if (play) void playSim();
408 } catch (e) { status(`Render failed: ${(e as Error).message.split("\n")[0]}`, true); }
409}
411const SIM_PLAY_GAIN = 1.6;
412const simAudio = () => (last ? mixOutput(params, last.mic, last.pickup) : new Float32Array(0));
413async function playSim() { if (last) await audio.play(simAudio(), last.fs, SIM_PLAY_GAIN); }
415// The reference SoundFont: the dev server serves one at ref.sf2 (GeneralUser GS from ~/Downloads,
416// or $REF_SF2); on the deployed site the user picks a file (nothing is uploaded).
417let refData: ArrayBuffer | null = null;
418async function fetchRef(): Promise<ArrayBuffer> {
419 if (refData) return refData;
420 status("Loading the reference SoundFont…");
421 let res: Response | null = null;
422 try { res = await fetch(`${import.meta.env.BASE_URL}ref.sf2`); } catch { res = null; }
423 const ok = !!res && res.ok && (res.headers.get("Content-Type") ?? "").includes("octet-stream");
424 if (!ok) throw new Error("no reference SoundFont: choose one with 'Ref SF2…' (e.g. GeneralUser GS, program 32)");
425 refData = await res!.arrayBuffer();
426 refName = "GeneralUser GS";
427 status(`Reference loaded (${(refData.byteLength / 1e6).toFixed(0)} MB)`);
428 return refData;
429}
431async function setRefFile(f: File) {
432 refData = await f.arrayBuffer();
433 refName = f.name.replace(/\.sf[23]$/i, "");
434 refLoaded = null;
435 refCache.clear();
436 status(`Reference: ${f.name} (${(refData.byteLength / 1e6).toFixed(0)} MB), bank ${ui.refBank} program ${ui.refProgram}`);
437 if (ui.playMode === "ref") void ensureLiveBank();
438 void analyse();
439}
441async function ensureRefWorker() {
442 if (!refLoaded) refLoaded = (async () => { const d = await fetchRef(); await refPool.call({ type: "refBank", buffer: d.slice(0) }); })();
443 try { await refLoaded; } catch (e) { refLoaded = null; throw e; }
444}
446async function refAudio(note: number, vel: number): Promise<Float32Array> {
447 const k = `${ui.refBank}:${ui.refProgram}:${note}:${vel}:${params.engine.duration}`;
448 if (refCache.has(k)) return refCache.get(k)!;
449 await ensureRefWorker();
450 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 });
451 const x = r.audio as Float32Array;
452 refCache.set(k, x);
453 return x;
454}
456async function playRef() {
457 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); }
458 catch (e) { status(`Reference: ${(e as Error).message}`, true); }
459}
461// ---------------------------------------------------------------- analysis panels
463const TABS: [string, string][] = [["sound", "Sound"], ["spectro", "Spectrogram"], ["partials", "Partials"], ["body", "Body"], ["sf2", "SF2"]];
464function buildTabs() {
465 const nav = $("#tabs"), panels = $("#panels");
466 nav.innerHTML = ""; panels.innerHTML = "";
467 for (const [id, label] of TABS) {
468 nav.append(el("button", { class: ui.tab === id ? "on" : "", onclick: () => { ui.tab = id; saveUi(); buildTabs(); } }, label));
469 const p = el("div", { class: "panel", id: `panel-${id}` });
470 p.hidden = ui.tab !== id;
471 panels.append(p);
472 }
473 $("#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>`;
474 $("#panel-spectro").innerHTML = `<div class="plots one"><figure><canvas id="cSgSim" class="tall"></canvas></figure><figure><canvas id="cSgRef" class="tall"></canvas></figure></div>`;
475 $("#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>`;
476 $("#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>`;
477 $("#panel-sf2").innerHTML = `<div id="sf2Info"></div>`;
478 ($("#bStr") as HTMLSelectElement).value = String(fingering(params, ui.note).string);
479 $("#bStr").addEventListener("change", drawBody);
480 if (ui.tab === "body") drawBody();
481 else if (ui.tab === "sf2") drawSf2Panel();
482 else analyse();
483}
485const C_SIM = "var(--sim)", C_REF = "var(--ref)";
486const cssv = (v: string) => getComputedStyle(document.documentElement).getPropertyValue(v.slice(4, -1)).trim();
488async function analyse() {
489 if (!last || (ui.tab !== "sound" && ui.tab !== "spectro" && ui.tab !== "partials")) return;
490 const fs = last.fs, x = simAudio();
491 let ref: Float32Array | null = null;
492 try { ref = await refAudio(last.note, last.velocity); } catch { ref = null; }
493 const sim = cssv(C_SIM), refc = cssv(C_REF);
494 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)); };
495 const xs = onset(x), rs = ref ? onset(ref) : null;
496 const ed = envelopeDecay(xs, fs);
497 const metrics = [`sim: t20 ${ed.t20.toFixed(2)} s, centroid ${centroid(xs, fs, 0, 0.15).toFixed(0)} Hz`];
498 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`); }
499 $("#metrics").textContent = metrics.join(" · ");
500 if (ui.tab === "sound") {
501 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) }; };
502 const es = env(xs, fs), er = rs ? env(rs, 44100) : null;
503 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" });
504 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) }; };
505 const ss = spec(xs, fs), sr2 = rs ? spec(rs, 44100) : null;
506 const marks = Array.from({ length: 12 }, (_, i) => ({ x: (i + 1) * midiToHz(last!.note) }));
507 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 });
508 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)) }; };
509 const ws = wave(xs, fs), wr = rs ? wave(rs, 44100) : null;
510 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" });
511 const sm = spec(onset(last.mic), fs), sp = spec(onset(last.pickup), fs);
512 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 });
513 } else if (ui.tab === "spectro") {
514 const sg = spectrogram(xs, 4096, 512);
515 spectrogramPlot($("#cSgSim") as HTMLCanvasElement, sg.frames, fs, 4096, 512, { title: "simulation" });
516 if (rs) { const sgr = spectrogram(rs, 4096, 512); spectrogramPlot($("#cSgRef") as HTMLCanvasElement, sgr.frames, 44100, 4096, 512, { title: `reference (${refName} prog ${ui.refProgram})` }); }
517 } else if (ui.tab === "partials") {
518 const f1 = midiToHz(last.note);
519 const ps = partialDecay(xs, fs, f1, 24), pr = rs ? partialDecay(rs, 44100, f1, 24) : [];
520 const rel = (a: { levelDb: number }[]) => a.map((p) => p.levelDb - (a[0]?.levelDb ?? 0));
521 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" });
522 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" });
523 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("");
524 $("#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>`;
525 }
526}
528function drawBody() {
529 if (ui.tab !== "body") return;
530 const b = body();
531 const si = Number(($("#bStr") as HTMLSelectElement).value || 0);
532 const N = 600, f = Array.from({ length: N }, (_, i) => 30 * Math.pow(8000 / 30, i / (N - 1)));
533 const db = (re: Float64Array, im: Float64Array) => Array.from(re, (r, i) => 20 * Math.log10(Math.hypot(r, im[i]) + 1e-20));
534 const yy = bridgeAdmittance(b, f, si, "y"), yz = bridgeAdmittance(b, f, si, "z");
535 const marks = b.modes.filter((m) => m.label && m.f < 1000).map((m) => ({ x: m.f, label: m.label }));
536 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 : [] });
537 const hy = radiationTransfer(b, f, si, "y"), hz = radiationTransfer(b, f, si, "z");
538 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" });
539 $("#bodyInfo").textContent = `${b.source} body, ${b.modes.length} modes`;
540 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("");
541 $("#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>`;
542}
544function drawSf2Panel() {
545 if (ui.tab !== "sf2") return;
546 const jobs = sampleJobs(params);
547 const notes = sampleNotes(params);
548 const total = jobs.reduce((s, j) => s + j.length, 0);
549 $("#sf2Info").innerHTML = `
550 <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>
551 <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>
552 <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>
553 <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>`;
554 $("#bBuild").addEventListener("click", () => void buildSf2InBrowser());
555 $("#bDl").addEventListener("click", () => { if (builtSf2) download(new Blob([builtSf2 as BlobPart], { type: "audio/x-soundfont" }), "acoustic-bass.sf2"); });
556 $("#bDlP").addEventListener("click", () => download(new Blob([JSON.stringify(params, null, 2)], { type: "application/json" }), "acoustic-bass-params.json"));
557 $("#bPlayBuilt").addEventListener("click", () => { ui.playMode = "built"; saveUi(); syncTransport(); void ensureLiveBank(); });
558 $("#bPrebuilt").addEventListener("click", async () => {
559 status("Loading the prebuilt SF2…");
560 builtSf2 = new Uint8Array(await (await fetch(prebuiltSf2Url)).arrayBuffer());
561 builtKey++;
562 ui.playMode = "built"; saveUi(); syncTransport();
563 await ensureLiveBank();
564 status("Prebuilt SF2 loaded: the keys play it live");
565 drawSf2Panel();
566 });
567}
569async function buildSf2InBrowser() {
570 await ensureFE();
571 const p = cloneParams(params);
572 p.engine.oversample = p.sf2.oversample;
573 const b = useFE() && feBody ? feBody : parametricBody(p);
574 const jobs = sampleJobs(p);
575 const results: Float32Array[] = new Array(jobs.length);
576 let done = 0;
577 const t0 = performance.now();
578 status(`Building SF2: 0/${jobs.length}`);
579 progress(0);
580 try {
581 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) => {
582 results[i] = mixOutput(p, r.mic as Float32Array, r.pickup as Float32Array);
583 done++; progress(done / jobs.length); status(`Building SF2: ${done}/${jobs.length}`);
584 })));
585 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}).`;
586 builtSf2 = buildSf2(p, jobs, results, p.engine.sampleRate, comment).sf2;
587 builtKey++;
588 status(`SF2 built: ${jobs.length} samples, ${(builtSf2.length / 1e6).toFixed(1)} MB, ${((performance.now() - t0) / 1000).toFixed(0)} s`);
589 } catch (e) { status(`SF2 build failed: ${(e as Error).message.split("\n")[0]}`, true); }
590 drawSf2Panel();
591}
593// ---------------------------------------------------------------- transport
595function updateNoteInfo() {
596 $("#noteName").textContent = `${noteName(ui.note)} ${midiToHz(ui.note).toFixed(1)} Hz`;
597 const fg = fingering(params, ui.note);
598 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`;
599 let s = ` ${where}, vibrating length ${(fg.length * 100).toFixed(1)} cm`;
600 if (last && last.note === ui.note) {
601 const i = last.info as { releaseForce: number; slipTime: number; stickTime: number };
602 s += ` · release ${i.releaseForce.toFixed(1)} N, slip ${(i.slipTime * 1000).toFixed(1)} ms, pull ${(i.stickTime * 1000).toFixed(0)} ms`;
603 }
604 $("#fingerInfo").textContent = s;
605}
607function syncTransport() {
608 ($("#vel") as HTMLInputElement).value = String(ui.velocity);
609 $("#velV").textContent = String(ui.velocity);
610 ($("#auto") as HTMLInputElement).checked = ui.auto;
611 ($("#playMode") as HTMLSelectElement).value = ui.playMode;
612 ($("#vol") as HTMLInputElement).value = String(ui.volume);
613 ($("#mMic") as HTMLInputElement).value = String(params.output.micMix);
614 ($("#mPick") as HTMLInputElement).value = String(params.output.pickupMix);
615 updateNoteInfo();
616}
618function download(blob: Blob, name: string) {
619 const a = el("a", { href: URL.createObjectURL(blob), download: name });
620 document.body.append(a); a.click(); a.remove();
621 setTimeout(() => URL.revokeObjectURL(a.href), 5000);
622}
624$("#vel").addEventListener("input", () => { ui.velocity = Number(($("#vel") as HTMLInputElement).value); $("#velV").textContent = String(ui.velocity); saveUi(); });
625$("#vel").addEventListener("change", () => { if (ui.auto) void renderCurrent(false); });
626$("#auto").addEventListener("change", () => { ui.auto = ($("#auto") as HTMLInputElement).checked; saveUi(); });
627$("#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)); });
628$("#vol").addEventListener("input", () => { ui.volume = Number(($("#vol") as HTMLInputElement).value); audio.setVolume(ui.volume); saveUi(); });
629$("#bRender").addEventListener("click", () => void renderCurrent(true));
630$("#bSim").addEventListener("click", () => void playSim());
631$("#bRef").addEventListener("click", () => void playRef());
632$("#bAB").addEventListener("click", async () => { if (!last) await renderCurrent(false); await playSim(); await new Promise((r) => setTimeout(r, 300)); await playRef(); });
633$("#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`); });
634for (const [id, path] of [["#mMic", "output.micMix"], ["#mPick", "output.pickupMix"]] as const) {
635 $(id).addEventListener("input", () => { setPath(params, path, Number(($(id) as HTMLInputElement).value)); save(LS_PARAMS, params); syncControls(); });
636 $(id).addEventListener("change", () => { void analyse(); });
637}
638$("#bRefFile").addEventListener("click", () => ($("#fRef") as HTMLInputElement).click());
639$("#fRef").addEventListener("change", () => { const f = ($("#fRef") as HTMLInputElement).files?.[0]; if (f) void setRefFile(f); });
640$("#bSave").addEventListener("click", () => download(new Blob([JSON.stringify(params, null, 2)], { type: "application/json" }), "acoustic-bass-params.json"));
641$("#bLoad").addEventListener("click", () => ($("#fParams") as HTMLInputElement).click());
642$("#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(); });
643$("#bReset").addEventListener("click", () => { if (!confirm("Restore all parameters to their defaults?")) return; params = defaultParams(); save(LS_PARAMS, params); syncControls(); syncTransport(); onParamsChanged(); });
644window.addEventListener("resize", () => { if (ui.tab === "body") drawBody(); else void analyse(); });
646buildParamPanel();
647buildTabs();
648drawKeyboard();
649syncTransport();
650updateFeInfo();
651status("Click a key to render a note (or press Render). A/B compares with the reference SoundFont.");
652void ensureFE().catch(() => { /* reported by computeFE */ });