1// Sanity checks for the analysis, run with `npm test`.
2import { analyze, detectSegment, detectTear, DEFAULT_SETTINGS, energyBand, bandLevels, bandpass, smoothLog } from "../src/analysis/analyze.ts";
3import { syntheticTear } from "../src/audio/synthetic.ts";
4import { decodeWav, encodeWavFloat32 } from "../src/audio/wav.ts";
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;
27 const a = analyze(x, fs, { start: 0, end: 2 }, { ...DEFAULT_SETTINGS, energyLow: 0, energyHigh: fs / 2 });
28 check("Parseval (energy of white noise)", Math.abs(a.energyRaw / e - 1) < 0.02, `${a.energyRaw.toExponential(3)} vs ${e.toExponential(3)}`);
29}
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}
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}
58// A single click counts in full wherever it sits in the range, even right at an edge
59{
60 const errs: number[] = [];
61 for (const off of [0.001, 0.005, 0.01, 0.0213, 0.5, 0.5107, 1.0, 1.995]) {
62 const x = new Float32Array(fs * 4);
63 let r = 1;
64 let prev = 0;
65 const o = Math.round((1 + off) * fs);
66 for (let i = 0; i < 96; i++) {
67 r = (r * 1103515245 + 12345) & 0x7fffffff;
68 const g = r / 0x7fffffff - 0.5;
69 x[o + i] = (g - prev) * Math.exp(-i / 12);
70 prev = g;
71 }
72 let e = 0;
73 for (const v of x) e += v * v;
74 const a = analyze(x, fs, { start: 1, end: 3 }, { ...DEFAULT_SETTINGS, energyLow: 0, energyHigh: fs / 2 });
75 errs.push(Math.abs(10 * Math.log10(a.energyRaw / (e / fs))));
76 }
77 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`);
78}
80// Synthetic tears: same clicks at different durations
81const results: { T: number; energyDb: number; shapeDb: number[] }[] = [];
82for (const T of [0.3, 1, 3, 10]) {
83 const x = syntheticTear({ tearSeconds: T, seed: 3 });
84 const seg = detectSegment(x, fs, energyBand(DEFAULT_SETTINGS));
85 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");
86 if (!seg) continue;
87 const a = analyze(x, fs, seg, DEFAULT_SETTINGS);
88 const shape = smoothLog(a.freqs, a.netEsd.map((v) => v / a.energy), 1000, 20000, 1 / 3).v.map((v) => 10 * Math.log10(v));
89 results.push({ T, energyDb: 10 * Math.log10(a.energy), shapeDb: shape });
90 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`);
91}
92const es = results.map((r) => r.energyDb);
93check("synthetic energy independent of duration (range < 1 dB)", Math.max(...es) - Math.min(...es) < 1);
94let worst = 0;
95for (const r of results) r.shapeDb.forEach((v, i) => (worst = Math.max(worst, Math.abs(v - results[0].shapeDb[i]))));
96check("synthetic spectrum shape independent of duration (1/3 octave, 1–20 kHz, within 1.5 dB)", worst < 1.5, `worst ${worst.toFixed(2)} dB`);
98// Harder cases for finding the tear. `quiet(sec)` is background only; `clicksAt` adds a tear's
99// clicks (no background) starting at a given time.
100{
101 const band = energyBand(DEFAULT_SETTINGS);
102 const quiet = (sec: number, seed = 9, db = -75) => syntheticTear({ tearSeconds: 0, clicks: 0, quietSeconds: sec / 2, seed, backgroundDbfs: db });
103 const clicksAt = (x: Float32Array, t0: number, T: number, clicks: number, seed: number, gain = 1) => {
104 const c = syntheticTear({ tearSeconds: T, clicks, quietSeconds: 0, seed, backgroundDbfs: -400 });
105 const o = Math.round(t0 * fs);
106 for (let i = 0; i < c.length && o + i < x.length; i++) x[o + i] += gain * c[i];
107 };
108 // a key press: a loud ~8 ms broadband burst
109 const keyAt = (x: Float32Array, t0: number, amp: number, seed: number) => {
110 let r = seed;
111 const o = Math.round(t0 * fs);
112 for (let i = 0; i < Math.round(0.008 * fs); i++) {
113 r = (r * 1103515245 + 12345) & 0x7fffffff;
114 x[o + i] += amp * (r / 0x7fffffff - 0.5) * Math.exp(-i / (0.002 * fs));
115 }
116 };
117 const near = (seg: { start: number; end: number } | null, a: number, b: number, tol: number) =>
118 !!seg && Math.abs(seg.start - a) < tol && Math.abs(seg.end - b) < tol;
119 const show = (seg: { start: number; end: number } | null) => (seg ? `${seg.start.toFixed(3)}–${seg.end.toFixed(3)}` : "none");
120 const captured = (x: Float32Array, seg: { start: number; end: number } | null, a: number, b: number) => {
121 if (!seg) return -Infinity;
122 const got = analyze(x, fs, seg, DEFAULT_SETTINGS).energy;
123 const want = analyze(x, fs, { start: a - 0.05, end: b + 0.05 }, DEFAULT_SETTINGS).energy;
124 return 10 * Math.log10(got / want);
125 };
127 {
128 const x = syntheticTear({ tearSeconds: 8, quietSeconds: 0.15, seed: 4 });
129 const seg = detectSegment(x, fs, band);
130 check("tear filling almost the whole recording", near(seg, 0.15, 8.15, 0.03), show(seg));
131 }
132 {
133 // a slow, sparse tear: 150 clicks over 10 s, and a 0.4 s pause in the middle
134 const x = quiet(12.4);
135 clicksAt(x, 1, 5, 75, 21);
136 clicksAt(x, 6.4, 5, 75, 22);
137 const seg = detectSegment(x, fs, band);
138 const db = captured(x, seg, 1, 11.4);
139 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`);
140 }
141 {
142 // key presses (press and release) before and after the tear are left out
143 const x = quiet(5);
144 keyAt(x, 0.45, 0.4, 1);
145 keyAt(x, 0.56, 0.3, 2);
146 clicksAt(x, 1, 3, 4000, 23);
147 keyAt(x, 4.35, 0.4, 3);
148 const d = detectTear(x, fs, band);
149 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(", ")}`);
150 }
151 {
152 // a fast tear is shorter than a key press is loud; the tear still has more energy
153 const x = quiet(3);
154 keyAt(x, 0.6, 0.4, 4);
155 clicksAt(x, 1, 0.15, 4000, 24);
156 const seg = detectSegment(x, fs, band);
157 check("very fast tear next to a key press", near(seg, 1, 1.15, 0.03), show(seg));
158 }
159 {
160 // strong low-frequency noise (hum and rumble) does not matter
161 const clean = syntheticTear({ tearSeconds: 2, seed: 5 });
162 const x = clean.slice();
163 let r = 0;
164 for (let i = 0; i < x.length; i++) {
165 r = 0.999 * r + 0.02 * (Math.random() - 0.5);
166 x[i] += 0.3 * Math.sin((2 * Math.PI * 100 * i) / fs) + r;
167 }
168 const seg = detectSegment(x, fs, band);
169 const db = seg ? 10 * Math.log10(analyze(x, fs, seg, DEFAULT_SETTINGS).energy / analyze(clean, fs, seg, DEFAULT_SETTINGS).energy) : NaN;
170 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`);
171 }
172 {
173 // a quiet tear over a noisier background (20 dB less signal than usual)
174 const x = quiet(4, 10, -65);
175 clicksAt(x, 1, 2, 4000, 25, 0.1);
176 const seg = detectSegment(x, fs, band);
177 const db = captured(x, seg, 1, 3);
178 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`);
179 }
180 {
181 const x = quiet(3);
182 check("background alone: no tear found", detectSegment(x, fs, band) === null);
183 }
184}
186// WAV round trip
187{
188 const x = syntheticTear({ tearSeconds: 0.5 });
189 const blob = encodeWavFloat32(x, fs);
190 const d = decodeWav(await blob.arrayBuffer());
191 check("WAV float32 round trip", !!d && d.sampleRate === fs && d.samples.length === x.length && d.samples.every((v, i) => v === x[i]));
192}
194// Dataset export/import round trip
195{
196 const audio = new Map<string, Float32Array>();
197 const recs: RecordingMeta[] = [0.4, 2].map((T, i) => {
198 const x = syntheticTear({ tearSeconds: T, seed: i });
199 const id = `id-${i}`;
200 audio.set(id, x);
201 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 };
202 });
203 const blob = await exportDataset(recs, DEFAULT_SETTINGS, async (id) => audio.get(id)!);
204 const ds = await readDataset(new File([blob], "d.zip"));
205 const same =
206 ds.samples.length === 2 &&
207 ds.samples.every(({ meta, audio: x }, i) => JSON.stringify(meta) === JSON.stringify(recs[i]) && x.every((v, j) => v === audio.get(meta.id)![j])) &&
208 JSON.stringify(ds.settings) === JSON.stringify(DEFAULT_SETTINGS);
209 check("dataset export/import round trip", same);
210}
212if (failed) {
213 console.log(`${failed} check(s) failed`);
214 throw new Error("checks failed");
215}