// Sanity checks for the analysis, run with `npm test`. import { analyze, detectSegment, DEFAULT_SETTINGS } from "../src/analysis/analyze.ts"; import { syntheticTear } from "../src/audio/synthetic.ts"; import { decodeWav, encodeWavFloat32 } from "../src/audio/wav.ts"; let failed = 0; function check(name: string, ok: boolean, detail = "") { console.log(`${ok ? "ok " : "FAIL"} ${name}${detail ? " " + detail : ""}`); if (!ok) failed++; } const fs = 48000; // Parseval: white noise of known power, full band { const x = new Float32Array(fs * 2); let s = 7; for (let i = 0; i < x.length; i++) { s = (s * 1103515245 + 12345) & 0x7fffffff; x[i] = (s / 0x7fffffff - 0.5) * 0.2; } let e = 0; for (const v of x) e += v * v; e /= fs; const a = analyze(x, fs, { start: 0, end: 2 }, { ...DEFAULT_SETTINGS, bandLow: 0, bandHigh: fs / 2 }); check("Parseval (energy of white noise)", Math.abs(a.energyRaw / e - 1) < 0.02, `${a.energyRaw.toExponential(3)} vs ${e.toExponential(3)}`); } // Synthetic tears: same clicks at different durations const results: { T: number; energyDb: number; median: number; seg: [number, number] }[] = []; for (const T of [0.3, 1, 3, 10]) { const x = syntheticTear({ tearSeconds: T, seed: 3 }); const seg = detectSegment(x, fs); 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"); if (!seg) continue; const a = analyze(x, fs, seg, DEFAULT_SETTINGS); results.push({ T, energyDb: 10 * Math.log10(a.energy), median: a.medianFreq, seg: [seg.start, seg.end] }); 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`); } const es = results.map((r) => r.energyDb); check("synthetic energy independent of duration (range < 1 dB)", Math.max(...es) - Math.min(...es) < 1); const ms = results.map((r) => r.median); check("synthetic median frequency independent of duration (range < 10%)", Math.max(...ms) / Math.min(...ms) < 1.1); // WAV round trip { const x = syntheticTear({ tearSeconds: 0.5 }); const blob = encodeWavFloat32(x, fs); const d = decodeWav(await blob.arrayBuffer()); check("WAV float32 round trip", !!d && d.sampleRate === fs && d.samples.length === x.length && d.samples.every((v, i) => v === x[i])); } if (failed) { console.log(`${failed} check(s) failed`); throw new Error("checks failed"); }