// Sanity checks for the analysis, run with `npm test`. import { analyze, detectSegment, detectTear, DEFAULT_SETTINGS, energyBand, bandLevels, bandpass, smoothLog } from "../src/analysis/analyze.ts"; import { syntheticTear } from "../src/audio/synthetic.ts"; import { decodeWav, encodeWavFloat32 } from "../src/audio/wav.ts"; import { exportDataset, readDataset } from "../src/storage/dataset.ts"; import type { RecordingMeta } from "../src/storage/db.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, energyLow: 0, energyHigh: fs / 2 }); check("Parseval (energy of white noise)", Math.abs(a.energyRaw / e - 1) < 0.02, `${a.energyRaw.toExponential(3)} vs ${e.toExponential(3)}`); } // Band levels: white noise in 15–20 kHz carries 5/24 of the power { const x = new Float32Array(fs); let s = 11; for (let i = 0; i < x.length; i++) { s = (s * 1103515245 + 12345) & 0x7fffffff; x[i] = (s / 0x7fffffff - 0.5) * 0.2; } let p = 0; for (const v of x) p += v * v; p /= x.length; const lv = bandLevels(x, fs, { lo: 15000, hi: 20000 }); const mid = lv.power.slice(10, -10); const mean = mid.reduce((a, v) => a + v, 0) / mid.length; check("band level of white noise", Math.abs(mean / (p * 5 / 24) - 1) < 0.05, `${(mean / p).toFixed(4)} vs ${(5 / 24).toFixed(4)}`); } // Band-pass: a 15 kHz tone passes, a 1 kHz tone is removed { const n = 48000; const tone = (f: number) => Float32Array.from({ length: n }, (_, i) => Math.sin((2 * Math.PI * f * i) / fs)); const rms = (v: Float32Array) => Math.sqrt(v.slice(4800, -4800).reduce((a, x) => a + x * x, 0) / (v.length - 9600)); const pass = rms(bandpass(tone(15000), fs, { lo: 10000, hi: 20000 })) / rms(tone(15000)); const stop = rms(bandpass(tone(1000), fs, { lo: 10000, hi: 20000 })) / rms(tone(1000)); check("band-pass keeps 15 kHz, removes 1 kHz", Math.abs(pass - 1) < 0.01 && stop < 1e-3, `pass ${pass.toFixed(4)}, stop ${stop.toExponential(1)}`); } // A single click counts in full wherever it sits in the range, even right at an edge { const errs: number[] = []; for (const off of [0.001, 0.005, 0.01, 0.0213, 0.5, 0.5107, 1.0, 1.995]) { const x = new Float32Array(fs * 4); let r = 1; let prev = 0; const o = Math.round((1 + off) * fs); for (let i = 0; i < 96; i++) { r = (r * 1103515245 + 12345) & 0x7fffffff; const g = r / 0x7fffffff - 0.5; x[o + i] = (g - prev) * Math.exp(-i / 12); prev = g; } let e = 0; for (const v of x) e += v * v; const a = analyze(x, fs, { start: 1, end: 3 }, { ...DEFAULT_SETTINGS, energyLow: 0, energyHigh: fs / 2 }); errs.push(Math.abs(10 * Math.log10(a.energyRaw / (e / fs)))); } check("one click's energy does not depend on where it sits in the range", Math.max(...errs) < 0.01, `worst ${Math.max(...errs).toFixed(3)} dB`); } // Synthetic tears: same clicks at different durations const results: { T: number; energyDb: number; shapeDb: number[] }[] = []; for (const T of [0.3, 1, 3, 10]) { const x = syntheticTear({ tearSeconds: T, seed: 3 }); const seg = detectSegment(x, fs, energyBand(DEFAULT_SETTINGS)); check(`detect segment T=${T}`, !!seg && Math.abs(seg.start - 1) < 0.03 && Math.abs(seg.end - (1 + T)) < 0.03, seg ? `${seg.start.toFixed(3)}–${seg.end.toFixed(3)}` : "none"); if (!seg) continue; const a = analyze(x, fs, seg, DEFAULT_SETTINGS); const shape = smoothLog(a.freqs, a.netEsd.map((v) => v / a.energy), 1000, 20000, 1 / 3).v.map((v) => 10 * Math.log10(v)); results.push({ T, energyDb: 10 * Math.log10(a.energy), shapeDb: shape }); console.log(` T=${T}s energy=${(10 * Math.log10(a.energy)).toFixed(2)} dB snr=${a.snrDb.toFixed(1)} dB 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); let worst = 0; for (const r of results) r.shapeDb.forEach((v, i) => (worst = Math.max(worst, Math.abs(v - results[0].shapeDb[i])))); check("synthetic spectrum shape independent of duration (1/3 octave, 1–20 kHz, within 1.5 dB)", worst < 1.5, `worst ${worst.toFixed(2)} dB`); // Harder cases for finding the tear. `quiet(sec)` is background only; `clicksAt` adds a tear's // clicks (no background) starting at a given time. { const band = energyBand(DEFAULT_SETTINGS); const quiet = (sec: number, seed = 9, db = -75) => syntheticTear({ tearSeconds: 0, clicks: 0, quietSeconds: sec / 2, seed, backgroundDbfs: db }); const clicksAt = (x: Float32Array, t0: number, T: number, clicks: number, seed: number, gain = 1) => { const c = syntheticTear({ tearSeconds: T, clicks, quietSeconds: 0, seed, backgroundDbfs: -400 }); const o = Math.round(t0 * fs); for (let i = 0; i < c.length && o + i < x.length; i++) x[o + i] += gain * c[i]; }; // a key press: a loud ~8 ms broadband burst const keyAt = (x: Float32Array, t0: number, amp: number, seed: number) => { let r = seed; const o = Math.round(t0 * fs); for (let i = 0; i < Math.round(0.008 * fs); i++) { r = (r * 1103515245 + 12345) & 0x7fffffff; x[o + i] += amp * (r / 0x7fffffff - 0.5) * Math.exp(-i / (0.002 * fs)); } }; const near = (seg: { start: number; end: number } | null, a: number, b: number, tol: number) => !!seg && Math.abs(seg.start - a) < tol && Math.abs(seg.end - b) < tol; const show = (seg: { start: number; end: number } | null) => (seg ? `${seg.start.toFixed(3)}–${seg.end.toFixed(3)}` : "none"); const captured = (x: Float32Array, seg: { start: number; end: number } | null, a: number, b: number) => { if (!seg) return -Infinity; const got = analyze(x, fs, seg, DEFAULT_SETTINGS).energy; const want = analyze(x, fs, { start: a - 0.05, end: b + 0.05 }, DEFAULT_SETTINGS).energy; return 10 * Math.log10(got / want); }; { const x = syntheticTear({ tearSeconds: 8, quietSeconds: 0.15, seed: 4 }); const seg = detectSegment(x, fs, band); check("tear filling almost the whole recording", near(seg, 0.15, 8.15, 0.03), show(seg)); } { // a slow, sparse tear: 150 clicks over 10 s, and a 0.4 s pause in the middle const x = quiet(12.4); clicksAt(x, 1, 5, 75, 21); clicksAt(x, 6.4, 5, 75, 22); const seg = detectSegment(x, fs, band); const db = captured(x, seg, 1, 11.4); check("slow sparse tear with a pause, all of it found", !!seg && seg.start > 0.9 && seg.end < 11.5 && db > -0.02, `${show(seg)}, energy ${db.toFixed(2)} dB of the whole tear`); } { // key presses (press and release) before and after the tear are left out const x = quiet(5); keyAt(x, 0.45, 0.4, 1); keyAt(x, 0.56, 0.3, 2); clicksAt(x, 1, 3, 4000, 23); keyAt(x, 4.35, 0.4, 3); const d = detectTear(x, fs, band); check("key presses near the tear are left out", near(d.segment, 1, 4, 0.03) && d.leftOut.length === 2, `${show(d.segment)}, left out ${d.leftOut.map(show).join(", ")}`); } { // a fast tear is shorter than a key press is loud; the tear still has more energy const x = quiet(3); keyAt(x, 0.6, 0.4, 4); clicksAt(x, 1, 0.15, 4000, 24); const seg = detectSegment(x, fs, band); check("very fast tear next to a key press", near(seg, 1, 1.15, 0.03), show(seg)); } { // strong low-frequency noise (hum and rumble) does not matter const clean = syntheticTear({ tearSeconds: 2, seed: 5 }); const x = clean.slice(); let r = 0; for (let i = 0; i < x.length; i++) { r = 0.999 * r + 0.02 * (Math.random() - 0.5); x[i] += 0.3 * Math.sin((2 * Math.PI * 100 * i) / fs) + r; } const seg = detectSegment(x, fs, band); const db = seg ? 10 * Math.log10(analyze(x, fs, seg, DEFAULT_SETTINGS).energy / analyze(clean, fs, seg, DEFAULT_SETTINGS).energy) : NaN; check("loud hum and rumble below the band change neither range nor energy", near(seg, 1, 3, 0.03) && Math.abs(db) < 0.05, `${show(seg)}, energy ${db.toFixed(3)} dB`); } { // a quiet tear over a noisier background (20 dB less signal than usual) const x = quiet(4, 10, -65); clicksAt(x, 1, 2, 4000, 25, 0.1); const seg = detectSegment(x, fs, band); const db = captured(x, seg, 1, 3); check("quiet tear in more background noise", near(seg, 1, 3, 0.06) && db > -0.3, `${show(seg)}, energy ${db.toFixed(2)} dB of the whole tear`); } { const x = quiet(3); check("background alone: no tear found", detectSegment(x, fs, band) === null); } } // 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])); } // Dataset export/import round trip { const audio = new Map(); const recs: RecordingMeta[] = [0.4, 2].map((T, i) => { const x = syntheticTear({ tearSeconds: T, seed: i }); const id = `id-${i}`; audio.set(id, x); return { id, createdAt: 1700000000000 + i, label: i ? "second" : "", notes: "n", material: "paper", source: "mic", sampleRate: fs, length: x.length, segment: { start: 1, end: 1 + T }, segmentManual: i === 1 }; }); const blob = await exportDataset(recs, DEFAULT_SETTINGS, async (id) => audio.get(id)!); const ds = await readDataset(new File([blob], "d.zip")); const same = ds.samples.length === 2 && ds.samples.every(({ meta, audio: x }, i) => JSON.stringify(meta) === JSON.stringify(recs[i]) && x.every((v, j) => v === audio.get(meta.id)![j])) && JSON.stringify(ds.settings) === JSON.stringify(DEFAULT_SETTINGS); check("dataset export/import round trip", same); } if (failed) { console.log(`${failed} check(s) failed`); throw new Error("checks failed"); }