d0a8b32Rip Sound Analyzer: record tears, inspect one, compare across speedsJeremy Magland 1// Sanity checks for the analysis, run with `npm test`.
751f8faSelect the tear on level, waveform or spectrogram; 10–20 kHz analysis bandJeremy Magland 2import { analyze, detectSegment, DEFAULT_SETTINGS, energyBand, bandLevels, bandpass, smoothLog } from "../src/analysis/analyze.ts";
d0a8b32Rip Sound Analyzer: record tears, inspect one, compare across speedsJeremy Magland 3import { syntheticTear } from "../src/audio/synthetic.ts";
4import { decodeWav, encodeWavFloat32 } from "../src/audio/wav.ts";
bf56870Export/import the whole dataset; filtered waveform by defaultJeremy Magland 5import { exportDataset, readDataset } from "../src/storage/dataset.ts";
6import type { RecordingMeta } from "../src/storage/db.ts";
8let failed = 0;
9function check(name: string, ok: boolean, detail = "") {
10 console.log(`${ok ? "ok " : "FAIL"} ${name}${detail ? " " + detail : ""}`);
11 if (!ok) failed++;
12}
14const fs = 48000;
16// Parseval: white noise of known power, full band
17{
18 const x = new Float32Array(fs * 2);
19 let s = 7;
20 for (let i = 0; i < x.length; i++) {
21 s = (s * 1103515245 + 12345) & 0x7fffffff;
22 x[i] = (s / 0x7fffffff - 0.5) * 0.2;
23 }
24 let e = 0;
25 for (const v of x) e += v * v;
26 e /= fs;
8bf83cfMeasure energy and find the tear in a 15–20 kHz bandJeremy Magland 27 const a = analyze(x, fs, { start: 0, end: 2 }, { ...DEFAULT_SETTINGS, energyLow: 0, energyHigh: fs / 2 });
d0a8b32Rip Sound Analyzer: record tears, inspect one, compare across speedsJeremy Magland 28 check("Parseval (energy of white noise)", Math.abs(a.energyRaw / e - 1) < 0.02, `${a.energyRaw.toExponential(3)} vs ${e.toExponential(3)}`);
29}
8bf83cfMeasure energy and find the tear in a 15–20 kHz bandJeremy Magland 31// Band levels: white noise in 15–20 kHz carries 5/24 of the power
32{
33 const x = new Float32Array(fs);
34 let s = 11;
35 for (let i = 0; i < x.length; i++) {
36 s = (s * 1103515245 + 12345) & 0x7fffffff;
37 x[i] = (s / 0x7fffffff - 0.5) * 0.2;
38 }
39 let p = 0;
40 for (const v of x) p += v * v;
41 p /= x.length;
42 const lv = bandLevels(x, fs, { lo: 15000, hi: 20000 });
43 const mid = lv.power.slice(10, -10);
44 const mean = mid.reduce((a, v) => a + v, 0) / mid.length;
45 check("band level of white noise", Math.abs(mean / (p * 5 / 24) - 1) < 0.05, `${(mean / p).toFixed(4)} vs ${(5 / 24).toFixed(4)}`);
46}
751f8faSelect the tear on level, waveform or spectrogram; 10–20 kHz analysis bandJeremy Magland 48// Band-pass: a 15 kHz tone passes, a 1 kHz tone is removed
49{
50 const n = 48000;
51 const tone = (f: number) => Float32Array.from({ length: n }, (_, i) => Math.sin((2 * Math.PI * f * i) / fs));
52 const rms = (v: Float32Array) => Math.sqrt(v.slice(4800, -4800).reduce((a, x) => a + x * x, 0) / (v.length - 9600));
53 const pass = rms(bandpass(tone(15000), fs, { lo: 10000, hi: 20000 })) / rms(tone(15000));
54 const stop = rms(bandpass(tone(1000), fs, { lo: 10000, hi: 20000 })) / rms(tone(1000));
55 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)}`);
56}
d0a8b32Rip Sound Analyzer: record tears, inspect one, compare across speedsJeremy Magland 58// Synthetic tears: same clicks at different durations
cc4197eDrop median frequency and centroidJeremy Magland 59const results: { T: number; energyDb: number; shapeDb: number[] }[] = [];
d0a8b32Rip Sound Analyzer: record tears, inspect one, compare across speedsJeremy Magland 60for (const T of [0.3, 1, 3, 10]) {
61 const x = syntheticTear({ tearSeconds: T, seed: 3 });
8bf83cfMeasure energy and find the tear in a 15–20 kHz bandJeremy Magland 62 const seg = detectSegment(x, fs, energyBand(DEFAULT_SETTINGS));
d0a8b32Rip Sound Analyzer: record tears, inspect one, compare across speedsJeremy Magland 63 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");
64 if (!seg) continue;
65 const a = analyze(x, fs, seg, DEFAULT_SETTINGS);
751f8faSelect the tear on level, waveform or spectrogram; 10–20 kHz analysis bandJeremy Magland 66 const shape = smoothLog(a.freqs, a.netEsd.map((v) => v / a.energy), 1000, 20000, 1 / 3).v.map((v) => 10 * Math.log10(v));
cc4197eDrop median frequency and centroidJeremy Magland 67 results.push({ T, energyDb: 10 * Math.log10(a.energy), shapeDb: shape });
68 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`);
70const es = results.map((r) => r.energyDb);
71check("synthetic energy independent of duration (range < 1 dB)", Math.max(...es) - Math.min(...es) < 1);
73for (const r of results) r.shapeDb.forEach((v, i) => (worst = Math.max(worst, Math.abs(v - results[0].shapeDb[i]))));
74check("synthetic spectrum shape independent of duration (1/3 octave, 1–20 kHz, within 1.5 dB)", worst < 1.5, `worst ${worst.toFixed(2)} dB`);
76// WAV round trip
77{
78 const x = syntheticTear({ tearSeconds: 0.5 });
79 const blob = encodeWavFloat32(x, fs);
80 const d = decodeWav(await blob.arrayBuffer());
81 check("WAV float32 round trip", !!d && d.sampleRate === fs && d.samples.length === x.length && d.samples.every((v, i) => v === x[i]));
82}
bf56870Export/import the whole dataset; filtered waveform by defaultJeremy Magland 84// Dataset export/import round trip
85{
86 const audio = new Map<string, Float32Array>();
87 const recs: RecordingMeta[] = [0.4, 2].map((T, i) => {
88 const x = syntheticTear({ tearSeconds: T, seed: i });
89 const id = `id-${i}`;
90 audio.set(id, x);
91 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 };
92 });
93 const blob = await exportDataset(recs, DEFAULT_SETTINGS, async (id) => audio.get(id)!);
94 const ds = await readDataset(new File([blob], "d.zip"));
95 const same =
96 ds.samples.length === 2 &&
97 ds.samples.every(({ meta, audio: x }, i) => JSON.stringify(meta) === JSON.stringify(recs[i]) && x.every((v, j) => v === audio.get(meta.id)![j])) &&
98 JSON.stringify(ds.settings) === JSON.stringify(DEFAULT_SETTINGS);
99 check("dataset export/import round trip", same);
100}
d0a8b32Rip Sound Analyzer: record tears, inspect one, compare across speedsJeremy Magland 102if (failed) {
103 console.log(`${failed} check(s) failed`);
104 throw new Error("checks failed");
105}