1// Compare simulation renders (renders/sim_N_V.wav) with the reference (refs/ref_N_V.wav):
2// envelope decay, spectral centroid early/late, and partial levels and T60s.
3// node scripts/compare.ts note:vel ...
4import fs from "node:fs";
5import path from "node:path";
6import { decodeWav, envelopeDecay, centroid, partialDecay, rms } from "../src/core/dsp.ts";
7import { midiToHz } from "../src/core/strings.ts";
9const root = path.join(import.meta.dirname, "..");
10const load = (f: string) => decodeWav(new Uint8Array(fs.readFileSync(f)));
11const notes = process.argv.slice(2).map((a) => a.split(":").map(Number) as [number, number]);
12for (const [n, v] of notes) {
13 const rows: string[] = [];
14 for (const [tag, f] of [["sim", `renders/sim_${n}_${v}.wav`], ["ref", `refs/ref_${n}_${v}.wav`]] as const) {
15 const fp = path.join(root, f);
16 if (!fs.existsSync(fp)) { rows.push(`${tag}: missing ${f}`); continue; }
17 const { x, fs: sr } = load(fp);
18 // start at the onset
19 let pk = 0; for (const s of x) pk = Math.max(pk, Math.abs(s));
20 let s0 = 0; while (s0 < x.length && Math.abs(x[s0]) < 0.01 * pk) s0++;
21 const y = x.subarray(Math.max(0, s0 - 44));
22 const ed = envelopeDecay(y, sr);
23 const pd = partialDecay(y, sr, midiToHz(n), 16);
24 const l1 = pd[0]?.levelDb ?? 0;
25 rows.push(`${tag}: rms(0-.3) ${(20 * Math.log10(rms(y, sr, 0, 0.3) / pk)).toFixed(1)} dB re peak | t20 ${ed.t20.toFixed(2)} t40 ${ed.t40.toFixed(2)} s | centroid 0-.1 ${centroid(y, sr, 0, 0.1).toFixed(0)} .5-1.5 ${centroid(y, sr, 0.5, 1.5).toFixed(0)} Hz`);
26 rows.push(` partial dB re 1: ${pd.map((p) => (p.levelDb - l1).toFixed(0).padStart(4)).join("")}`);
27 rows.push(` T60 s: ${pd.map((p) => (isFinite(p.t60) ? p.t60.toFixed(1) : " inf").padStart(4)).join("")}`);
28 }
29 console.log(`== note ${n} (${midiToHz(n).toFixed(1)} Hz) vel ${v}\n` + rows.join("\n"));
30}