/ magland / rip-sound-analyzer
Sign in
magland / rip-sound-analyzer
rip-sound-analyzer / scripts / check-analysis.ts
56 lines · 2.5 KBBlameHistoryRaw
1// Sanity checks for the analysis, run with `npm test`.
2import { analyze, detectSegment, DEFAULT_SETTINGS } from "../src/analysis/analyze.ts";
3import { syntheticTear } from "../src/audio/synthetic.ts";
4import { decodeWav, encodeWavFloat32 } from "../src/audio/wav.ts";
6let failed = 0;
7function check(name: string, ok: boolean, detail = "") {
8 console.log(`${ok ? "ok " : "FAIL"} ${name}${detail ? " " + detail : ""}`);
9 if (!ok) failed++;
12const fs = 48000;
14// Parseval: white noise of known power, full band
16 const x = new Float32Array(fs * 2);
17 let s = 7;
18 for (let i = 0; i < x.length; i++) {
19 s = (s * 1103515245 + 12345) & 0x7fffffff;
20 x[i] = (s / 0x7fffffff - 0.5) * 0.2;
21 }
22 let e = 0;
23 for (const v of x) e += v * v;
24 e /= fs;
25 const a = analyze(x, fs, { start: 0, end: 2 }, { ...DEFAULT_SETTINGS, bandLow: 0, bandHigh: fs / 2 });
26 check("Parseval (energy of white noise)", Math.abs(a.energyRaw / e - 1) < 0.02, `${a.energyRaw.toExponential(3)} vs ${e.toExponential(3)}`);
29// Synthetic tears: same clicks at different durations
30const results: { T: number; energyDb: number; median: number; seg: [number, number] }[] = [];
31for (const T of [0.3, 1, 3, 10]) {
32 const x = syntheticTear({ tearSeconds: T, seed: 3 });
33 const seg = detectSegment(x, fs);
34 check(`detect segment T=${T}`, !!seg && Math.abs(seg.start - 1) < 0.08 && Math.abs(seg.end - (1 + T)) < 0.08, seg ? `${seg.start.toFixed(3)}–${seg.end.toFixed(3)}` : "none");
35 if (!seg) continue;
36 const a = analyze(x, fs, seg, DEFAULT_SETTINGS);
37 results.push({ T, energyDb: 10 * Math.log10(a.energy), median: a.medianFreq, seg: [seg.start, seg.end] });
38 console.log(` T=${T}s energy=${(10 * Math.log10(a.energy)).toFixed(2)} dB snr=${a.snrDb.toFixed(1)} dB median=${a.medianFreq.toFixed(0)} Hz centroid=${a.centroid.toFixed(0)} Hz peak=${a.peakDbfs.toFixed(1)} dBFS`);
40const es = results.map((r) => r.energyDb);
41check("synthetic energy independent of duration (range < 1 dB)", Math.max(...es) - Math.min(...es) < 1);
42const ms = results.map((r) => r.median);
43check("synthetic median frequency independent of duration (range < 10%)", Math.max(...ms) / Math.min(...ms) < 1.1);
45// WAV round trip
47 const x = syntheticTear({ tearSeconds: 0.5 });
48 const blob = encodeWavFloat32(x, fs);
49 const d = decodeWav(await blob.arrayBuffer());
50 check("WAV float32 round trip", !!d && d.sampleRate === fs && d.samples.length === x.length && d.samples.every((v, i) => v === x[i]));
53if (failed) {
54 console.log(`${failed} check(s) failed`);
55 throw new Error("checks failed");
↑↓ move↵openescclose