/ magland / rip-sound-analyzer
Sign in
magland / rip-sound-analyzer
Find the tear from clicks in the filtered waveform; count every click's energy in full
The automatic range now comes from the waveform filtered to the analysis band: peaks above 6x the background RMS are clicks, clicks less than 1 s apart form a sound, the most energetic sound is the tear, and short separate sounds at its ends (key presses) are left out. Left-out sounds are shown on the level plot and listed with an Include button; the background level is drawn as a dashed line. Ranges found by the old finder are found again once. The tear's spectrum is now one FFT of the whole range instead of an average of Hann-windowed frames, which counted a click near the range edges for up to 30 dB less and varied by about 2 dB even inside it. Also fixes a duplicate React key on the sample page. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Jeremy Magland <jmagland@flatironinstitute.org> committed commit 18eb8cd07720 parent 4bbed09 Browse files
8 changed files+357−71
README.mdmodified+2−2View file
@@ -25,7 +25,7 @@ Open the printed localhost URL in Chrome. Everything runs in the browser; record
2525 ## What it does
2626
2727 - **Record**: a list of samples, each one tear at whatever speed you choose, sorted slowest first by measured tear duration. Add a new sample, re-record or delete one, and give it an optional name and notes. Capture is raw: Chrome's echo cancellation, noise suppression and auto gain are off, and samples come straight from the audio graph via an AudioWorklet at the mic's own sample rate (32-bit float, no compression). For each sample:
28- - **Tear range**: level in the analysis band, waveform (filtered to the analysis band by default, or raw) and spectrogram on one zoomable time axis. The range is found automatically; drag across any of the three plots to mark it again, drag its edges, or type start/end times. Play the tear (with a moving playhead) or the whole recording.
28+ - **Tear range**: level in the analysis band, waveform (filtered to the analysis band by default, or raw) and spectrogram on one zoomable time axis. The range is found automatically from the clicks in the filtered waveform (short separate sounds such as key presses are left out and listed, with a button to take them in); drag across any of the three plots to mark it again, drag its edges, or type start/end times. Play the tear (with a moving playhead) or the whole recording.
2929 - **Results**: duration, speed, energy, mean power, peak/clipping, level above background.
3030 - **Frequency makeup**: the tear's energy spectrum against the background.
3131 - **Export / import**: “Export dataset” saves every sample and the analysis settings to one .zip (`dataset.json` plus a 32-bit float WAV per sample). “Import dataset…” replaces everything in the browser with such a file, after confirming.
@@ -37,7 +37,7 @@ The “What this can tell you” tab in the app explains the method and its limi
3737
3838 ## Layout
3939
40-- `src/analysis/` – FFT, tear detection, Welch spectra, energy and spectral statistics
40+- `src/analysis/` – FFT, tear detection, spectra, energy
4141 - `src/audio/` – microphone capture, WAV encode/decode, synthetic tears
4242 - `src/storage/` – IndexedDB, dataset export/import (uncompressed zip)
4343 - `src/components/` – UI, including a small canvas plotting component
scripts/check-analysis.tsmodified+112−2View file
@@ -1,5 +1,5 @@
11 // Sanity checks for the analysis, run with `npm test`.
2-import { analyze, detectSegment, DEFAULT_SETTINGS, energyBand, bandLevels, bandpass, smoothLog } from "../src/analysis/analyze.ts";
2+import { analyze, detectSegment, detectTear, DEFAULT_SETTINGS, energyBand, bandLevels, bandpass, smoothLog } from "../src/analysis/analyze.ts";
33 import { syntheticTear } from "../src/audio/synthetic.ts";
44 import { decodeWav, encodeWavFloat32 } from "../src/audio/wav.ts";
55 import { exportDataset, readDataset } from "../src/storage/dataset.ts";
@@ -55,12 +55,34 @@ const fs = 48000;
5555 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)}`);
5656 }
5757
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+}
79+
5880 // Synthetic tears: same clicks at different durations
5981 const results: { T: number; energyDb: number; shapeDb: number[] }[] = [];
6082 for (const T of [0.3, 1, 3, 10]) {
6183 const x = syntheticTear({ tearSeconds: T, seed: 3 });
6284 const seg = detectSegment(x, fs, energyBand(DEFAULT_SETTINGS));
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");
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");
6486 if (!seg) continue;
6587 const a = analyze(x, fs, seg, DEFAULT_SETTINGS);
6688 const shape = smoothLog(a.freqs, a.netEsd.map((v) => v / a.energy), 1000, 20000, 1 / 3).v.map((v) => 10 * Math.log10(v));
@@ -73,6 +95,94 @@ let worst = 0;
7395 for (const r of results) r.shapeDb.forEach((v, i) => (worst = Math.max(worst, Math.abs(v - results[0].shapeDb[i]))));
7496 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`);
7597
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+ };
126+
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+}
185+
76186 // WAV round trip
77187 {
78188 const x = syntheticTear({ tearSeconds: 0.5 });
src/App.tsxmodified+8−7View file
@@ -4,7 +4,7 @@ import { TearView } from "./components/TearView.tsx";
44 import { CompareView } from "./components/CompareView.tsx";
55 import { About } from "./components/About.tsx";
66 import { readTheme } from "./components/CanvasPlot.tsx";
7-import { DEFAULT_SETTINGS, detectSegment, energyBand } from "./analysis/analyze.ts";
7+import { DEFAULT_SETTINGS, DETECT_VERSION, detectSegment, energyBand } from "./analysis/analyze.ts";
88 import type { CaptureInfo } from "./audio/recorder.ts";
99 import { encodeWavFloat32 } from "./audio/wav.ts";
1010 import { exportDataset, readDataset } from "./storage/dataset.ts";
@@ -55,19 +55,19 @@ export function App() {
5555 storeSettings(s);
5656 };
5757
58- // Ranges found automatically follow the analysis band: re-detect them when it changes.
59- // Ranges set by hand are left alone.
58+ // Ranges found automatically follow the analysis band and the finder: find them again when
59+ // either changes. Ranges set by hand are left alone.
6060 const { energyLow, energyHigh } = settings;
6161 useEffect(() => {
6262 if (!loaded) return;
6363 let live = true;
6464 (async () => {
6565 for (const m of recs) {
66- if (m.segmentManual || (m.detectBand?.lo === energyLow && m.detectBand?.hi === energyHigh)) continue;
66+ if (m.segmentManual || (m.detectBand?.lo === energyLow && m.detectBand?.hi === energyHigh && m.detectVersion === DETECT_VERSION)) continue;
6767 const x = await getAudio(m.id);
6868 if (!live) return;
6969 const band = { lo: energyLow, hi: energyHigh };
70- const updated = { ...m, segment: detectSegment(x, m.sampleRate, band), detectBand: band };
70+ const updated = { ...m, segment: detectSegment(x, m.sampleRate, band), detectBand: band, detectVersion: DETECT_VERSION };
7171 await updateMeta(updated);
7272 setRecs((r) => r.map((q) => (q.id === m.id ? updated : q)));
7373 }
@@ -93,6 +93,7 @@ export function App() {
9393 segment: detectSegment(x, fs, band),
9494 segmentManual: false,
9595 detectBand: band,
96+ detectVersion: DETECT_VERSION,
9697 capture: info ?? undefined,
9798 };
9899 await saveRecording(meta, x);
@@ -310,7 +311,7 @@ export function App() {
310311 </div>
311312 )}
312313 </div>
313- <NameField key={current.id} meta={current} onUpdate={onUpdate} />
314+ <NameField key={`name-${current.id}`} meta={current} onUpdate={onUpdate} />
314315
315316 {rerecording === current.id ? (
316317 <RecordPanel
@@ -320,7 +321,7 @@ export function App() {
320321 onCancel={() => setRerecording(null)}
321322 />
322323 ) : (
323- <TearView key={current.id} meta={current} settings={settings} onUpdate={onUpdate} />
324+ <TearView key={`tear-${current.id}`} meta={current} settings={settings} onUpdate={onUpdate} />
324325 )}
325326 </>
326327 )}
src/analysis/analyze.tsmodified+160−47View file
@@ -83,56 +83,153 @@ export function bandLevels(x: Float32Array, fs: number, band: Band, hopSec = 0.0
8383 return { frameSec: hop / fs, power };
8484 }
8585
86-// Finds the tear from the level in the given band: the most energetic stretch well above
87-// the background, bridging gaps under 0.6 s. Returns null if nothing stands out.
88-export function detectSegment(x: Float32Array, fs: number, band: Band): Segment | null {
89- const { frameSec, power } = bandLevels(x, fs, band, 0.005);
90- const m = power.length;
91- if (m < 20) return null;
92- const smoothN = Math.max(1, Math.round(0.05 / frameSec)); // 50 ms moving average
93- const s = new Float64Array(m);
94- let acc = 0;
95- for (let i = 0; i < m; i++) {
96- acc += power[i];
97- if (i >= smoothN) acc -= power[i - smoothN];
98- s[i] = acc / Math.min(i + 1, smoothN);
86+// ---------- finding the tear ----------
87+
88+// Bump when the detector changes, so ranges found by an older version are found again.
89+export const DETECT_VERSION = 2;
90+
91+export interface TearDetection {
92+ segment: Segment | null;
93+ sigma: number; // background RMS of the filtered waveform
94+ threshold: number; // |amplitude| of the filtered waveform that counts as a click
95+ leftOut: Segment[]; // other sounds above the threshold that were not taken as the tear
96+}
97+
98+const DETECT = {
99+ k: 6, // click threshold, in background RMS (Gaussian noise passes 6 sigma about once in 5e8 samples)
100+ blockSec: 0.01, // blocks for the background estimate
101+ mergeSec: 0.01, // crossings closer than this belong to one event
102+ tailSec: 0.005, // energy counted after an event's last crossing
103+ maxGapSec: 1, // quieter stretches up to this long stay inside one tear
104+ isoMinSec: 0.15, // a short sound at either end must be at least this far from the rest to be left out...
105+ isoFactor: 8, // ...and this many times the typical gap between the rest's events
106+ edgeMaxSec: 0.25, // only sounds shorter than this are left out from the ends
107+ preSec: 0.01, // margin before the first click
108+ postSec: 0.02, // margin after the last click (its decay)
109+};
110+
111+interface Ev {
112+ a: number; // first sample above threshold
113+ b: number; // last sample above threshold
114+ e: number; // energy above background
115+}
116+
117+function median(v: number[]): number {
118+ if (!v.length) return 0;
119+ const a = [...v].sort((p, q) => p - q);
120+ const m = a.length >> 1;
121+ return a.length % 2 ? a[m] : (a[m - 1] + a[m]) / 2;
122+}
123+
124+// Finds the tear from the clicks in the waveform filtered to the band. The background RMS
125+// is taken from the quietest 10 ms blocks; every stretch where the filtered waveform
126+// exceeds 6x that is a click event. Events closer than 1 s form one sound; the sound with
127+// the most energy is the tear. Short sounds at its ends that stand apart from the rest
128+// (a key press, a click of the trackpad) are left out. `xf` can pass in the filtered
129+// waveform if it is already at hand.
130+export function detectTear(x: Float32Array, fs: number, band: Band, xf?: Float32Array): TearDetection {
131+ const y = xf ?? bandpass(x, fs, band);
132+ const n = y.length;
133+ const none = (sigma = 0, threshold = 0): TearDetection => ({ segment: null, sigma, threshold, leftOut: [] });
134+ const bn = Math.max(16, Math.round(DETECT.blockSec * fs));
135+ const blocks = Math.floor(n / bn);
136+ if (blocks < 10) return none();
137+ const rms = new Float64Array(blocks);
138+ for (let k = 0; k < blocks; k++) {
139+ let s = 0;
140+ for (let i = k * bn; i < (k + 1) * bn; i++) s += y[i] * y[i];
141+ rms[k] = Math.sqrt(s / bn);
99142 }
100- const noise = Math.max(percentile(s, 0.1), 1e-20);
101- const thresh = noise * 10 ** (12 / 10);
102- const maxGap = Math.round(0.6 / frameSec);
103- const regions: { a: number; b: number; e: number }[] = [];
104- let cur: { a: number; b: number; e: number } | null = null;
105- for (let i = 0; i < m; i++) {
106- if (s[i] > thresh) {
107- if (cur && i - cur.b <= maxGap) cur.b = i;
108- else {
109- if (cur) regions.push(cur);
110- cur = { a: i, b: i, e: 0 };
111- }
143+ const sigma = Math.max(percentile(rms, 0.1), 1e-12);
144+ const thr = DETECT.k * sigma;
145+ const s2 = sigma * sigma;
146+
147+ // click events
148+ const merge = Math.round(DETECT.mergeSec * fs);
149+ const tail = Math.round(DETECT.tailSec * fs);
150+ const evs: Ev[] = [];
151+ let cur: Ev | null = null;
152+ for (let i = 0; i < n; i++) {
153+ if (Math.abs(y[i]) <= thr) continue;
154+ if (cur && i - cur.b <= merge) cur.b = i;
155+ else {
156+ if (cur) evs.push(cur);
157+ cur = { a: i, b: i, e: 0 };
112158 }
113159 }
114- if (cur) regions.push(cur);
115- if (!regions.length) return null;
116- for (const r of regions) {
160+ if (cur) evs.push(cur);
161+ if (!evs.length) return none(sigma, thr);
162+ for (const ev of evs) {
117163 let e = 0;
118- for (let i = r.a; i <= r.b; i++) e += Math.max(0, power[i] - noise);
119- r.e = e;
164+ const b = Math.min(n, ev.b + tail);
165+ for (let i = ev.a; i < b; i++) e += y[i] * y[i] - s2;
166+ ev.e = Math.max(0, e);
167+ }
168+
169+ // sounds: events chained by gaps up to maxGap; the most energetic one is the tear
170+ const maxGap = DETECT.maxGapSec * fs;
171+ const sounds: Ev[][] = [];
172+ for (const ev of evs) {
173+ const last = sounds[sounds.length - 1];
174+ if (last && ev.a - last[last.length - 1].b <= maxGap) last.push(ev);
175+ else sounds.push([ev]);
120176 }
121- regions.sort((u, v) => v.e - u.e);
122- const best = regions[0];
123- // the moving average smears the edges; trim back to frames that are themselves above threshold
124- let a = Math.max(0, best.a - smoothN);
125- let b = best.b;
126- while (a < b && power[a] <= thresh) a++;
127- while (b > a && power[b] <= thresh) b--;
128- const pad = 0.03;
129- const dur = x.length / fs;
177+ const energy = (g: Ev[]) => g.reduce((t, ev) => t + ev.e, 0);
178+ let best = 0;
179+ for (let i = 1; i < sounds.length; i++) if (energy(sounds[i]) > energy(sounds[best])) best = i;
180+ let tear = sounds[best];
181+ const leftOut: Ev[][] = sounds.filter((_, i) => i !== best);
182+
183+ // leave out short, separate sounds at either end. "Separate" is judged against the typical
184+ // spacing of clicks within the sound: the median of the gaps between events, where a
185+ // stretch of clicks that ran together counts as one 10 ms gap per 10 ms. A dense tear
186+ // then sets a short spacing however few events it was split into, and a sparse tear
187+ // sets the spacing of its own clicks.
188+ const spacing = (g: Ev[]) => {
189+ const gaps: number[] = [];
190+ g.forEach((ev, i) => {
191+ if (i > 0) gaps.push(ev.a - g[i - 1].b);
192+ for (let k = Math.floor((ev.b - ev.a) / merge); k > 0; k--) gaps.push(merge);
193+ });
194+ return median(gaps);
195+ };
196+ const split = (g: Ev[], fromEnd: boolean): [Ev[], Ev[]] | null => {
197+ const iso = Math.max(DETECT.isoMinSec * fs, DETECT.isoFactor * spacing(g));
198+ for (let j = 0; j < g.length - 1; j++) {
199+ const [edge, rest] = fromEnd ? [g.slice(g.length - 1 - j), g.slice(0, g.length - 1 - j)] : [g.slice(0, j + 1), g.slice(j + 1)];
200+ const span = edge[edge.length - 1].b - edge[0].a;
201+ if (span > DETECT.edgeMaxSec * fs) return null;
202+ const gap = fromEnd ? edge[0].a - rest[rest.length - 1].b : rest[0].a - edge[edge.length - 1].b;
203+ if (gap >= iso && energy(edge) < energy(rest)) return [edge, rest];
204+ }
205+ return null;
206+ };
207+ for (;;) {
208+ const lead = split(tear, false);
209+ const trail = split(tear, true);
210+ const pick = lead && trail ? (energy(lead[0]) <= energy(trail[0]) ? lead : trail) : (lead ?? trail);
211+ if (!pick) break;
212+ leftOut.push(pick[0]);
213+ tear = pick[1];
214+ }
215+
216+ const dur = n / fs;
217+ const toSeg = (g: Ev[]): Segment => ({
218+ start: Math.max(0, g[0].a / fs - DETECT.preSec),
219+ end: Math.min(dur, (g[g.length - 1].b + 1) / fs + DETECT.postSec),
220+ });
130221 return {
131- start: Math.max(0, a * frameSec - pad),
132- end: Math.min(dur, (b + 1) * frameSec + pad),
222+ segment: toSeg(tear),
223+ sigma,
224+ threshold: thr,
225+ leftOut: leftOut.map(toSeg).sort((p, q) => p.start - q.start),
133226 };
134227 }
135228
229+export function detectSegment(x: Float32Array, fs: number, band: Band): Segment | null {
230+ return detectTear(x, fs, band).segment;
231+}
232+
136233 // ---------- spectra ----------
137234
138235 // One-sided periodograms (FS^2/Hz) of Hann-windowed frames of x[a..b), hop = half frame.
@@ -169,10 +266,28 @@ function periodograms(x: Float32Array, fs: number, a: number, b: number, nfft: n
169266 return out;
170267 }
171268
172-function meanOf(ps: Float64Array[], nb: number): Float64Array {
269+// Energy spectral density (FS^2·s/Hz) of x[a..b) on the NFFT grid, from one FFT of the whole
270+// range (no window) whose fine bins are summed into the coarser NFFT bins. By Parseval the
271+// total is exactly the range's energy, and each click counts in full wherever it sits in the
272+// range. (Averaging windowed frames instead weights a click by where it falls under the
273+// windows: near the range edges it nearly vanishes, and even inside it varies by ±2 dB.)
274+function segmentEsd(x: Float32Array, fs: number, a: number, b: number, nfft: number): Float64Array {
275+ const nb = nfft / 2 + 1;
173276 const out = new Float64Array(nb);
174- for (const p of ps) for (let k = 0; k < nb; k++) out[k] += p[k];
175- for (let k = 0; k < nb; k++) out[k] /= ps.length;
277+ const len = b - a;
278+ if (len <= 0) return out;
279+ let n = nfft;
280+ while (n < len) n *= 2;
281+ const re = new Float64Array(n);
282+ const im = new Float64Array(n);
283+ for (let i = 0; i < len; i++) re[i] = x[a + i];
284+ fft(re, im);
285+ const per = n / nfft; // fine bins per coarse bin
286+ const df = fs / nfft;
287+ for (let j = 0; j <= n / 2; j++) {
288+ const v = ((j === 0 || j === n / 2 ? 1 : 2) * (re[j] * re[j] + im[j] * im[j])) / (n * fs);
289+ out[Math.min(nb - 1, Math.round(j / per))] += v / df;
290+ }
176291 return out;
177292 }
178293
@@ -227,9 +342,7 @@ export function analyze(
227342 const b = Math.min(x.length, Math.ceil(segment.end * fs));
228343 const duration = (b - a) / fs;
229344
230- const tearPs = periodograms(x, fs, a, b, nfft);
231- const psd = tearPs.length ? meanOf(tearPs, nb) : new Float64Array(nb);
232- const esd = psd.map((v) => v * duration);
345+ const esd = segmentEsd(x, fs, a, b, nfft);
233346
234347 // background: everything outside the segment, keeping clear of its edges and the file ends
235348 const margin = Math.round(0.05 * fs);
src/components/About.tsxmodified+8−3View file
@@ -18,11 +18,16 @@ export function About({ settings }: { settings: AnalysisSettings }) {
1818 <h2>What is measured</h2>
1919 <ul>
2020 <li>
21- <b>Tear segment</b>: found automatically as the loudest stretch well above the background in the analysis band (gaps under 0.6 s are bridged). Check it on the Record tab and adjust it if it is wrong. Duration and speed ({settings.sheetLengthIn} in ÷ duration) come from this segment.
21+ <b>Tear segment</b>: found automatically from the clicks in the waveform filtered to the analysis band. The background noise's RMS amplitude is
22+ taken from the quietest 10 ms stretches, and any peak above 6 times that counts as a click. Clicks less than 1 s apart make up one sound; the sound
23+ with the most energy is the tear, and it runs from its first click to its last (plus 10 ms before and 20 ms after). Short sounds at either end that
24+ stand well apart from the rest, such as a key press, are left out and listed, with a button to take them in. Check the range on the Record tab and
25+ adjust it if it is wrong. Duration and speed ({settings.sheetLengthIn} in ÷ duration) come from this segment.
2226 </li>
2327 <li>
24- <b>Energy spectral density</b> of the tear: Welch average of 2048-point Hann-windowed spectra over the segment, times its duration. Units are digital
25- full scale (FS² · s / Hz).
28+ <b>Energy spectral density</b> of the tear: one FFT of the whole segment, with no window, summed into 23 Hz bins (the grid of a 2048-point
29+ spectrum at 48 kHz). Every click counts in full wherever it falls in the segment, even right at its edges; averaging windowed frames would count
30+ clicks near the edges for less. Units are digital full scale (FS² · s / Hz).
2631 </li>
2732 <li>
2833 <b>Background</b>: the same spectrum measured on the quiet audio before and after the tear (median across windows, so a stray key click does not
src/components/TearView.tsxmodified+53−10View file
@@ -1,6 +1,6 @@
11 import { useCallback, useEffect, useMemo, useRef, useState } from "react";
22 import { CanvasPlot, drawLine, readTheme, type PointerInfo, type Scales, type Theme } from "./CanvasPlot.tsx";
3-import { bandLevels, bandpass, detectSegment, energyBand, smoothLog, spectrogram, type Analysis, type AnalysisSettings, type Segment } from "../analysis/analyze.ts";
3+import { bandLevels, bandpass, DETECT_VERSION, detectTear, energyBand, smoothLog, spectrogram, type Analysis, type AnalysisSettings, type Segment } from "../analysis/analyze.ts";
44 import type { RecordingMeta } from "../storage/db.ts";
55 import { play, stop as stopPlay, usePlayhead } from "../audio/player.ts";
66 import { db10, fmtHz, fmtSec, getAnalysis, getAudio } from "../model.ts";
@@ -51,6 +51,10 @@ export function TearView({ meta, settings, onUpdate }: Props) {
5151 const { energyLow, energyHigh } = settings;
5252 const bandLabel = `${fmtKHz(energyLow)}–${fmtKHz(energyHigh)} kHz`;
5353 const levels = useMemo(() => (x ? bandLevels(x, fs, { lo: energyLow, hi: energyHigh }, 0.005) : null), [x, fs, energyLow, energyHigh]);
54+ // the waveform filtered to the band, and what the automatic finder makes of it
55+ const xf = useMemo(() => (x ? bandpass(x, fs, { lo: energyLow, hi: energyHigh }) : null), [x, fs, energyLow, energyHigh]);
56+ const detection = useMemo(() => (x && xf ? detectTear(x, fs, { lo: energyLow, hi: energyHigh }, xf) : null), [x, xf, fs, energyLow, energyHigh]);
57+ const leftOut = (detection?.leftOut ?? []).filter((o) => !seg || o.end <= seg.start || o.start >= seg.end);
5458 const spec = useMemo(() => (x ? spectrogram(x, fs) : null), [x, fs]);
5559 const specImage = useMemo(() => (spec ? spectrogramImage(spec) : null), [spec]);
5660 const mainColor = (th: Theme) => th.series[0];
@@ -178,6 +182,22 @@ export function TearView({ meta, settings, onUpdate }: Props) {
178182 const drawLevel = useCallback(
179183 (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
180184 shadeSeg(ctx, s, th);
185+ if (detection) {
186+ // sounds the automatic finder left out, and the background level it measured
187+ ctx.fillStyle = th.grid;
188+ for (const o of leftOut) ctx.fillRect(s.x(o.start), s.top, Math.max(2, s.x(o.end) - s.x(o.start)), s.bottom - s.top);
189+ if (detection.sigma > 0) {
190+ const y = s.y(db10(detection.sigma * detection.sigma));
191+ ctx.strokeStyle = th.muted;
192+ ctx.lineWidth = 1;
193+ ctx.setLineDash([5, 4]);
194+ ctx.beginPath();
195+ ctx.moveTo(s.left, y);
196+ ctx.lineTo(s.right, y);
197+ ctx.stroke();
198+ ctx.setLineDash([]);
199+ }
200+ }
181201 if (levels) {
182202 const { frameSec, power } = levels;
183203 const i0 = Math.max(0, Math.floor(view[0] / frameSec) - 1);
@@ -196,7 +216,7 @@ export function TearView({ meta, settings, onUpdate }: Props) {
196216 drawSelection(ctx, s, th, false);
197217 },
198218 // eslint-disable-next-line react-hooks/exhaustive-deps
199- [levels, view, seg, playhead],
219+ [levels, view, seg, playhead, detection],
200220 );
201221
202222 // ---------- waveform (raw or band-passed) ----------
@@ -215,7 +235,6 @@ export function TearView({ meta, settings, onUpdate }: Props) {
215235 /* ignore */
216236 }
217237 };
218- const xf = useMemo(() => (x && filtered ? bandpass(x, fs, { lo: energyLow, hi: energyHigh }) : null), [x, fs, filtered, energyLow, energyHigh]);
219238 const wave = filtered ? xf : x;
220239
221240 const waveMax = useMemo(() => {
@@ -441,20 +460,44 @@ export function TearView({ meta, settings, onUpdate }: Props) {
441460 </div>
442461 <RangeInputs seg={seg} dur={dur} onCommit={commitSeg} />
443462 <div className="range-row">
444- <span className="muted small">{meta.segmentManual ? "Range set by hand." : `Range found automatically from the level in ${bandLabel}.`}</span>
463+ <span className="muted small">
464+ {meta.segmentManual
465+ ? "Range set by hand."
466+ : "Range found automatically: from the first to the last click of the tear in the filtered waveform. A click is any peak above 6 times the background noise's RMS amplitude; the dashed line on the level plot is the background."}
467+ </span>
445468 <button
446- disabled={!x}
469+ disabled={!detection}
447470 onClick={() => {
448- if (!x) return;
449- const band = energyBand(settings);
450- const s = detectSegment(x, fs, band);
451- setSeg(s);
452- onUpdate({ ...meta, segment: s, segmentManual: false, detectBand: band });
471+ if (!detection) return;
472+ setSeg(detection.segment);
473+ onUpdate({ ...meta, segment: detection.segment, segmentManual: false, detectBand: energyBand(settings), detectVersion: DETECT_VERSION });
453474 }}
454475 >
455476 Find tear automatically
456477 </button>
457478 </div>
479+ {leftOut.length > 0 && (
480+ <div className="range-row left-out">
481+ <span className="muted small">
482+ {leftOut.length === 1 ? "Another sound" : `${leftOut.length} other sounds`} above the background, outside the range (grey on the level plot)
483+ {meta.segmentManual ? ":" : ", taken as not part of the tear:"}
484+ </span>
485+ {leftOut.map((o) => (
486+ <span key={o.start} className="left-out-item">
487+ <span className="small">
488+ {o.start.toFixed(2)}–{o.end.toFixed(2)} s
489+ </span>
490+ <button
491+ className="small-button"
492+ title="Extend the range to take this sound in"
493+ onClick={() => commitSeg(seg ? { start: Math.min(seg.start, o.start), end: Math.max(seg.end, o.end) } : o)}
494+ >
495+ Include
496+ </button>
497+ </span>
498+ ))}
499+ </div>
500+ )}
458501 </section>
459502
460503 <section className="card">
src/storage/db.tsmodified+1−0View file
@@ -17,6 +17,7 @@ export interface RecordingMeta {
1717 segment: Segment | null; // the tear, in seconds
1818 segmentManual: boolean;
1919 detectBand?: { lo: number; hi: number }; // band the automatic range was found in
20+ detectVersion?: number; // version of the automatic finder that found it
2021 capture?: CaptureInfo;
2122 }
2223
src/styles.cssmodified+13−0View file
@@ -792,6 +792,19 @@ button.link {
792792 margin-top: 8px;
793793 flex-wrap: wrap;
794794 }
795+.range-row.left-out {
796+ justify-content: flex-start;
797+ gap: 8px 14px;
798+}
799+.left-out-item {
800+ display: inline-flex;
801+ align-items: center;
802+ gap: 6px;
803+}
804+button.small-button {
805+ padding: 2px 8px;
806+ font-size: 12px;
807+}
795808 .plot-head .caption {
796809 margin: 2px 0 0;
797810 }
↑↓ move↵openescclose