Measure energy and find the tear in a 15–20 kHz band
Lower frequencies carry most of the background noise. Energy, automatic
tear detection, the level-over-time plot and the background comparison
now use a configurable energy band (default 15–20 kHz); median frequency,
centroid and spectrum comparison keep a separate wider spectrum band.
Automatically found ranges are re-detected when the energy band changes.
10 changed files+211−74
README.mdmodified+2−0View file
@@ -31,6 +31,8 @@ Open the printed localhost URL in Chrome. Everything runs in the browser; record
3131 - **Frequency makeup**: the tear's energy spectrum against the background.
3232 - **Compare**: energy vs tear duration, median frequency / centroid / mean power vs duration, spectra of all speeds overlaid (optionally shape only), a table and CSV export.
3333
34+Two frequency bands (set under Analysis settings): the **energy band**, default 15–20 kHz, is used for total energy, finding the tear, the level-over-time plot and the background comparison, because lower frequencies carry much more room and handling noise. The **spectrum band**, default 100 Hz–20 kHz, is used for median frequency, centroid and comparing spectrum shapes.
35+
3436 The “What this can tell you” tab in the app explains the method and its limits.
3537
3638 ## Layout
scripts/check-analysis.tsmodified+20−3View file
@@ -1,5 +1,5 @@
11 // Sanity checks for the analysis, run with `npm test`.
2-import { analyze, detectSegment, DEFAULT_SETTINGS } from "../src/analysis/analyze.ts";
2+import { analyze, detectSegment, DEFAULT_SETTINGS, energyBand, bandLevels } from "../src/analysis/analyze.ts";
33 import { syntheticTear } from "../src/audio/synthetic.ts";
44 import { decodeWav, encodeWavFloat32 } from "../src/audio/wav.ts";
55
@@ -22,15 +22,32 @@ const fs = 48000;
2222 let e = 0;
2323 for (const v of x) e += v * v;
2424 e /= fs;
25- const a = analyze(x, fs, { start: 0, end: 2 }, { ...DEFAULT_SETTINGS, bandLow: 0, bandHigh: fs / 2 });
25+ const a = analyze(x, fs, { start: 0, end: 2 }, { ...DEFAULT_SETTINGS, energyLow: 0, energyHigh: fs / 2 });
2626 check("Parseval (energy of white noise)", Math.abs(a.energyRaw / e - 1) < 0.02, `${a.energyRaw.toExponential(3)} vs ${e.toExponential(3)}`);
2727 }
2828
29+// Band levels: white noise in 15–20 kHz carries 5/24 of the power
30+{
31+ const x = new Float32Array(fs);
32+ let s = 11;
33+ for (let i = 0; i < x.length; i++) {
34+ s = (s * 1103515245 + 12345) & 0x7fffffff;
35+ x[i] = (s / 0x7fffffff - 0.5) * 0.2;
36+ }
37+ let p = 0;
38+ for (const v of x) p += v * v;
39+ p /= x.length;
40+ const lv = bandLevels(x, fs, { lo: 15000, hi: 20000 });
41+ const mid = lv.power.slice(10, -10);
42+ const mean = mid.reduce((a, v) => a + v, 0) / mid.length;
43+ check("band level of white noise", Math.abs(mean / (p * 5 / 24) - 1) < 0.05, `${(mean / p).toFixed(4)} vs ${(5 / 24).toFixed(4)}`);
44+}
45+
2946 // Synthetic tears: same clicks at different durations
3047 const results: { T: number; energyDb: number; median: number; seg: [number, number] }[] = [];
3148 for (const T of [0.3, 1, 3, 10]) {
3249 const x = syntheticTear({ tearSeconds: T, seed: 3 });
33- const seg = detectSegment(x, fs);
50+ const seg = detectSegment(x, fs, energyBand(DEFAULT_SETTINGS));
3451 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");
3552 if (!seg) continue;
3653 const a = analyze(x, fs, seg, DEFAULT_SETTINGS);
src/App.tsxmodified+48−12View 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 { detectSegment } from "./analysis/analyze.ts";
7+import { DEFAULT_SETTINGS, detectSegment, energyBand } from "./analysis/analyze.ts";
88 import type { CaptureInfo } from "./audio/recorder.ts";
99 import { encodeWavFloat32 } from "./audio/wav.ts";
1010 import { deleteRecording, listRecordings, newId, saveRecording, updateMeta, type RecordingMeta } from "./storage/db.ts";
@@ -60,6 +60,28 @@ export function App() {
6060 storeSettings(s);
6161 };
6262
63+ // Ranges found automatically follow the energy band: re-detect them when it changes.
64+ // Ranges set by hand are left alone.
65+ const { energyLow, energyHigh } = settings;
66+ useEffect(() => {
67+ if (!loaded) return;
68+ let live = true;
69+ (async () => {
70+ for (const m of recs) {
71+ if (m.segmentManual || m.detectBand?.lo === energyLow && m.detectBand?.hi === energyHigh) continue;
72+ const x = await getAudio(m.id);
73+ if (!live) return;
74+ const band = { lo: energyLow, hi: energyHigh };
75+ const updated = { ...m, segment: detectSegment(x, m.sampleRate, band), detectBand: band };
76+ await updateMeta(updated);
77+ setRecs((r) => r.map((q) => (q.id === m.id ? updated : q)));
78+ }
79+ })();
80+ return () => {
81+ live = false;
82+ };
83+ }, [loaded, recs, energyLow, energyHigh]);
84+
6385 const onDone = async (speed: Speed, x: Float32Array, fs: number, info: CaptureInfo | null, fileName?: string) => {
6486 const meta: RecordingMeta = {
6587 id: newId(),
@@ -71,8 +93,9 @@ export function App() {
7193 fileName,
7294 sampleRate: fs,
7395 length: x.length,
74- segment: detectSegment(x, fs),
96+ segment: detectSegment(x, fs, energyBand(settings)),
7597 segmentManual: false,
98+ detectBand: energyBand(settings),
7699 capture: info ?? undefined,
77100 };
78101 await saveRecording(meta, x);
@@ -258,16 +281,29 @@ function SettingsPanel({ settings, setSettings }: { settings: AnalysisSettings;
258281 );
259282 return (
260283 <div className="settings card">
261- {field("bandLow", "Analysis band from", "Hz")}
262- {field("bandHigh", "to", "Hz")}
263- {field("sheetLengthIn", "Tear length", "in")}
264- <button className="primary" disabled={!changed || d.bandHigh <= d.bandLow || d.sheetLengthIn <= 0} onClick={() => setSettings(d)}>
265- Apply
266- </button>
267- <button onClick={() => setD({ bandLow: 100, bandHigh: 20000, sheetLengthIn: 11 })}>Defaults</button>
268- <span className="muted small">
269- Energy and frequency statistics only count sound inside the band. Low frequencies are mostly handling noise and room rumble; the built-in mic records little above ~20 kHz.
270- </span>
284+ <div className="settings-row">
285+ <b>Energy band</b>
286+ {field("energyLow", "from", "Hz")}
287+ {field("energyHigh", "to", "Hz")}
288+ <span className="muted small">Used for total energy, finding the tear, the level-over-time plot and the background comparison.</span>
289+ </div>
290+ <div className="settings-row">
291+ <b>Spectrum band</b>
292+ {field("shapeLow", "from", "Hz")}
293+ {field("shapeHigh", "to", "Hz")}
294+ <span className="muted small">Used for median frequency, centroid and comparing spectrum shapes.</span>
295+ </div>
296+ <div className="settings-row">
297+ {field("sheetLengthIn", "Tear length", "in")}
298+ <button
299+ className="primary"
300+ disabled={!changed || d.energyHigh <= d.energyLow || d.shapeHigh <= d.shapeLow || d.sheetLengthIn <= 0}
301+ onClick={() => setSettings(d)}
302+ >
303+ Apply
304+ </button>
305+ <button onClick={() => setD({ ...DEFAULT_SETTINGS })}>Defaults</button>
306+ </div>
271307 </div>
272308 );
273309 }
src/analysis/analyze.tsmodified+65−21View file
@@ -6,17 +6,31 @@ export interface Segment {
66 }
77
88 export interface AnalysisSettings {
9- bandLow: number; // Hz
10- bandHigh: number; // Hz
9+ // Energy band: total energy, tear detection, level over time and the background comparison.
10+ // High frequencies, where the tear stands far above room and handling noise.
11+ energyLow: number; // Hz
12+ energyHigh: number; // Hz
13+ // Spectrum band: where median frequency and centroid are computed and spectra are compared.
14+ shapeLow: number; // Hz
15+ shapeHigh: number; // Hz
1116 sheetLengthIn: number; // length of the tear, inches
1217 }
1318
1419 export const DEFAULT_SETTINGS: AnalysisSettings = {
15- bandLow: 100,
16- bandHigh: 20000,
20+ energyLow: 15000,
21+ energyHigh: 20000,
22+ shapeLow: 100,
23+ shapeHigh: 20000,
1724 sheetLengthIn: 11,
1825 };
1926
27+export interface Band {
28+ lo: number;
29+ hi: number;
30+}
31+
32+export const energyBand = (s: AnalysisSettings): Band => ({ lo: s.energyLow, hi: s.energyHigh });
33+
2034 export const NFFT = 2048;
2135
2236 // ---------- level over time ----------
@@ -46,13 +60,40 @@ function percentile(values: ArrayLike<number>, p: number): number {
4660 return a[Math.min(a.length - 1, Math.max(0, Math.floor(p * (a.length - 1))))];
4761 }
4862
49-// Finds the tear: the most energetic stretch of sound well above the background.
50-// Short gaps (< 0.6 s) inside the tear are bridged. Returns null if nothing stands out.
51-export function detectSegment(x: Float32Array, fs: number): Segment | null {
52- const { frameSec, power } = frameLevels(x, fs, 0.01);
63+// Mean-square level within a frequency band, from short Hann-windowed FFT frames
64+// (512 samples) centred every `hopSec`. Calibrated so white noise gives its in-band power.
65+export function bandLevels(x: Float32Array, fs: number, band: Band, hopSec = 0.005): Levels {
66+ const n = 512;
67+ const hop = Math.max(1, Math.round(hopSec * fs));
68+ const count = Math.max(1, Math.ceil(x.length / hop));
69+ const w = hann(n);
70+ let u = 0;
71+ for (let i = 0; i < n; i++) u += w[i] * w[i];
72+ const df = fs / n;
73+ const kLo = Math.max(1, Math.ceil(band.lo / df));
74+ const kHi = Math.min(n / 2, Math.floor(Math.min(band.hi, fs / 2) / df));
75+ const re = new Float64Array(n);
76+ const im = new Float64Array(n);
77+ const power = new Float64Array(count);
78+ for (let f = 0; f < count; f++) {
79+ const c = Math.round((f + 0.5) * hop) - n / 2;
80+ im.fill(0);
81+ for (let i = 0; i < n; i++) re[i] = (x[c + i] ?? 0) * w[i];
82+ fft(re, im);
83+ let p = 0;
84+ for (let k = kLo; k <= kHi; k++) p += re[k] * re[k] + im[k] * im[k];
85+ power[f] = (2 * p) / (fs * u) * df;
86+ }
87+ return { frameSec: hop / fs, power };
88+}
89+
90+// Finds the tear from the level in the given band: the most energetic stretch well above
91+// the background, bridging gaps under 0.6 s. Returns null if nothing stands out.
92+export function detectSegment(x: Float32Array, fs: number, band: Band): Segment | null {
93+ const { frameSec, power } = bandLevels(x, fs, band, 0.005);
5394 const m = power.length;
54- if (m < 10) return null;
55- const smoothN = 5; // 50 ms moving average
95+ if (m < 20) return null;
96+ const smoothN = Math.max(1, Math.round(0.05 / frameSec)); // 50 ms moving average
5697 const s = new Float64Array(m);
5798 let acc = 0;
5899 for (let i = 0; i < m; i++) {
@@ -60,7 +101,7 @@ export function detectSegment(x: Float32Array, fs: number): Segment | null {
60101 if (i >= smoothN) acc -= power[i - smoothN];
61102 s[i] = acc / Math.min(i + 1, smoothN);
62103 }
63- const noise = Math.max(percentile(s, 0.1), 1e-14);
104+ const noise = Math.max(percentile(s, 0.1), 1e-20);
64105 const thresh = noise * 10 ** (12 / 10);
65106 const maxGap = Math.round(0.6 / frameSec);
66107 const regions: { a: number; b: number; e: number }[] = [];
@@ -83,8 +124,8 @@ export function detectSegment(x: Float32Array, fs: number): Segment | null {
83124 }
84125 regions.sort((u, v) => v.e - u.e);
85126 const best = regions[0];
86- // smoothing shifts the onset earlier by up to one window; trim back to raw frames above threshold
87- let a = best.a;
127+ // the moving average smears the edges; trim back to frames that are themselves above threshold
128+ let a = Math.max(0, best.a - smoothN);
88129 let b = best.b;
89130 while (a < b && power[a] <= thresh) a++;
90131 while (b > a && power[b] <= thresh) b--;
@@ -165,17 +206,18 @@ export interface Analysis {
165206 noiseEsd: Float64Array | null; // background PSD × segment duration (what background alone would contribute)
166207 netEsd: Float64Array; // max(esd - noiseEsd, 0)
167208 noiseSeconds: number; // how much background audio the noise estimate is based on
168- energyRaw: number; // in band, FS^2·s
209+ energyRaw: number; // in the energy band, FS^2·s
169210 energyNoise: number;
170211 energy: number; // energyRaw - energyNoise
212+ shapeEnergy: number; // background-subtracted energy in the spectrum band (for normalising shapes)
171213 snrDb: number; // 10 log10(energyRaw / energyNoise)
172- centroid: number; // Hz, of net ESD in band
214+ centroid: number; // Hz, of net ESD in the spectrum band
173215 medianFreq: number;
174216 f10: number;
175217 f90: number;
176218 peakDbfs: number; // in the segment
177219 nearClip: number; // samples with |x| >= 0.99 in the segment
178- backgroundDbfs: number | null; // RMS level of background in band
220+ backgroundDbfs: number | null; // RMS level of background in the energy band
179221 }
180222
181223 export function analyze(
@@ -215,8 +257,8 @@ export function analyze(
215257 let noiseEsd: Float64Array | null = null;
216258 if (noisePs.length >= 3) noiseEsd = medianOf(noisePs, nb).map((v) => v * duration);
217259
218- const kLo = Math.max(1, Math.ceil(settings.bandLow / df));
219- const kHi = Math.min(nb - 1, Math.floor(Math.min(settings.bandHigh, fs / 2) / df));
260+ const bins = (lo: number, hi: number) => [Math.max(1, Math.ceil(lo / df)), Math.min(nb - 1, Math.floor(Math.min(hi, fs / 2) / df))];
261+ const [kLo, kHi] = bins(settings.energyLow, settings.energyHigh);
220262 const netEsd = new Float64Array(nb);
221263 let energyRaw = 0;
222264 let energyNoise = 0;
@@ -229,19 +271,20 @@ export function analyze(
229271 }
230272 const energy = energyRaw - energyNoise;
231273
274+ const [sLo, sHi] = bins(settings.shapeLow, settings.shapeHigh);
232275 let tot = 0;
233276 let mom = 0;
234- for (let k = kLo; k <= kHi; k++) {
277+ for (let k = sLo; k <= sHi; k++) {
235278 tot += netEsd[k];
236279 mom += netEsd[k] * freqs[k];
237280 }
238281 const quantile = (q: number) => {
239282 let c = 0;
240- for (let k = kLo; k <= kHi; k++) {
283+ for (let k = sLo; k <= sHi; k++) {
241284 c += netEsd[k];
242285 if (c >= q * tot) return freqs[k];
243286 }
244- return freqs[kHi];
287+ return freqs[sHi];
245288 };
246289
247290 let peak = 0;
@@ -273,6 +316,7 @@ export function analyze(
273316 energyRaw,
274317 energyNoise,
275318 energy,
319+ shapeEnergy: tot * df,
276320 snrDb: noiseEsd ? 10 * Math.log10(energyRaw / Math.max(energyNoise, 1e-30)) : Infinity,
277321 centroid: tot > 0 ? mom / tot : NaN,
278322 medianFreq: tot > 0 ? quantile(0.5) : NaN,
src/components/About.tsxmodified+8−6View file
@@ -18,7 +18,7 @@ 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 (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, not from the label.
21+ <b>Tear segment</b>: found automatically as the loudest stretch well above the background in the energy 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, not from the label.
2222 </li>
2323 <li>
2424 <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
@@ -29,8 +29,10 @@ export function About({ settings }: { settings: AnalysisSettings }) {
2929 dominate), scaled to the tear's duration and subtracted.
3030 </li>
3131 <li>
32- <b>Sound energy</b>: the background-subtracted spectrum summed over {fmtHz(settings.bandLow)} – {fmtHz(settings.bandHigh)}. <b>Median frequency</b> and{" "}
33- <b>centroid</b> describe where that energy sits.
32+ <b>Sound energy</b>: the background-subtracted spectrum summed over the <b>energy band</b>, {fmtHz(settings.energyLow)} –{" "}
33+ {fmtHz(settings.energyHigh)}. Lower frequencies carry much more room and handling noise, so energy, the automatic tear range and the level-over-time
34+ plot all use only this band. <b>Median frequency</b> and <b>centroid</b> describe where the energy sits within the wider <b>spectrum band</b>,{" "}
35+ {fmtHz(settings.shapeLow)} – {fmtHz(settings.shapeHigh)}. Both bands can be changed under Analysis settings.
3436 </li>
3537 </ul>
3638
@@ -42,7 +44,7 @@ export function About({ settings }: { settings: AnalysisSettings }) {
4244 is bigger than many of the effects you may be looking for.
4345 </li>
4446 <li>
45- <b>The mic colours the sound.</b> A laptop microphone has its own frequency response and records little above about 20 kHz. Spectra show the sound as
47+ <b>The mic colours the sound.</b> A laptop microphone has its own frequency response and records little above about 20 kHz, so the top of the energy band is near the limit of what it captures. Spectra show the sound as
4648 that mic hears it. That is fine for comparing speeds against each other, but not for absolute spectra.
4749 </li>
4850 <li>
@@ -53,8 +55,8 @@ export function About({ settings }: { settings: AnalysisSettings }) {
5355 look at the spread before reading anything into a difference between speeds.
5456 </li>
5557 <li>
56- <b>Not just the tear.</b> Hand and paper movement, the sheet flapping and the room all add sound. The band setting excludes the lowest frequencies,
57- where most of this lives, but cannot remove it entirely.
58+ <b>Not just the tear.</b> Hand and paper movement, the sheet flapping and the room all add sound. Most of this is at low frequencies, which is why energy is measured
59+ in a high band, but the band cannot remove it entirely.
5860 </li>
5961 <li>
6062 <b>Same energy ≠ same clicks.</b> Equal energy and equal spectra are what identical clicks predict, but other explanations could produce them too.
src/components/CompareView.tsxmodified+20−12View file
@@ -53,6 +53,7 @@ export function CompareView({ recs, settings, onOpen }: Props) {
5353 };
5454 }, [recs, settings]);
5555
56+ const bandLabel = `${+(settings.energyLow / 1000).toFixed(2)}–${+(settings.energyHigh / 1000).toFixed(2)} kHz`;
5657 const missing = SPEEDS.filter((s) => !recs.some((r) => r.label === s.id));
5758 const unusable = recs.filter((m) => !rows.some((r) => r.meta.id === m.id));
5859
@@ -68,11 +69,11 @@ export function CompareView({ recs, settings, onOpen }: Props) {
6869 </div>
6970 )}
7071
71- <Summary rows={rows} />
72+ <Summary rows={rows} bandLabel={bandLabel} />
7273
7374 <div className="grid2">
7475 <section className="card">
75- <h3>Total sound energy vs tear duration</h3>
76+ <h3>Total sound energy ({bandLabel}) vs tear duration</h3>
7677 <p className="caption">If every tear contains the same clicks, the points should lie on a flat line.</p>
7778 <Scatter rows={rows} y={energyOf} yFmt={fmtDb} yLabel="energy (dB, relative)" onOpen={onOpen} unit="dB" minSpan={10} />
7879 </section>
@@ -116,7 +117,7 @@ export function CompareView({ recs, settings, onOpen }: Props) {
116117 <p className="caption">
117118 Energy spectrum of each tear, background removed.
118119 {normalize
119- ? " Each curve is divided by its total energy, so only the shape is compared."
120+ ? " Each curve is divided by its total energy over the plotted range, so only the shape is compared."
120121 : " If tears at all speeds contain the same clicks, the curves should lie on top of each other."}
121122 </p>
122123 <SpectraOverlay rows={rows} normalize={normalize} smoothing={smoothing} settings={settings} />
@@ -137,7 +138,7 @@ export function CompareView({ recs, settings, onOpen }: Props) {
137138
138139 // ---------- summary ----------
139140
140-function Summary({ rows }: { rows: Row[] }) {
141+function Summary({ rows, bandLabel }: { rows: Row[]; bandLabel: string }) {
141142 if (rows.length < 2) return <div className="card muted">Record at least two speeds to compare them.</div>;
142143 const lx = rows.map((r) => Math.log10(r.a.duration));
143144 const e = rows.map((r) => db10(r.a.energy));
@@ -152,7 +153,7 @@ function Summary({ rows }: { rows: Row[] }) {
152153 <div className="q">
153154 <div className="q-title">Same total energy at every speed?</div>
154155 <div>
155- Across {rows.length} speeds the energy varies over a range of <b>{eRange.toFixed(1)} dB</b>.
156+ Across {rows.length} speeds the energy in {bandLabel} varies over a range of <b>{eRange.toFixed(1)} dB</b>.
156157 {fe && (
157158 <>
158159 {" "}
@@ -280,13 +281,13 @@ function Scatter({
280281
281282 function SpectraOverlay({ rows, normalize, smoothing, settings }: { rows: Row[]; normalize: boolean; smoothing: number; settings: AnalysisSettings }) {
282283 const fsMin = rows.length ? Math.min(...rows.map((r) => r.a.fs)) : 48000;
283- const fLo = Math.max(20, settings.bandLow);
284- const fHi = Math.min(settings.bandHigh, fsMin / 2);
284+ const fLo = Math.max(20, settings.shapeLow);
285+ const fHi = Math.min(settings.shapeHigh, fsMin / 2);
285286
286287 const lines = useMemo(
287288 () =>
288289 rows.map((r) => {
289- const scale = normalize ? 1 / r.a.energy : 1;
290+ const scale = normalize ? 1 / r.a.shapeEnergy : 1;
290291 const sm = smoothLog(r.a.freqs, r.a.netEsd.map((v) => v * scale), fLo, fHi, smoothing);
291292 return { label: r.meta.label, f: sm.f, db: sm.v.map((v) => (v > 0 ? 10 * Math.log10(v) : NaN)) };
292293 }),
@@ -302,12 +303,19 @@ function SpectraOverlay({ rows, normalize, smoothing, settings }: { rows: Row[];
302303
303304 const draw = useCallback(
304305 (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
306+ if (!normalize) {
307+ // mark the energy band
308+ ctx.fillStyle = th.seg;
309+ const bl = s.x(Math.max(settings.energyLow, fLo));
310+ const bh = s.x(Math.min(settings.energyHigh, fHi));
311+ if (bh > bl) ctx.fillRect(bl, s.top, bh - bl, s.bottom - s.top);
312+ }
305313 for (const l of lines) {
306314 const st = speedStyle(l.label);
307315 drawLine(ctx, s, l.f, l.db, colorFor(st.slot, th.series, th.muted), 2);
308316 }
309317 },
310- [lines],
318+ [lines, normalize, settings, fLo, fHi],
311319 );
312320
313321 return (
@@ -329,7 +337,7 @@ function SpectraOverlay({ rows, normalize, smoothing, settings }: { rows: Row[];
329337 }}
330338 ariaLabel="Energy spectra of the tears, overlaid"
331339 />
332- <Legend rows={rows} lines />
340+ <Legend rows={rows} lines extra={normalize ? undefined : "shaded: energy band"} />
333341 </>
334342 );
335343 }
@@ -424,7 +432,7 @@ function exportCsv(rows: Row[], settings: AnalysisSettings) {
424432 const head = [
425433 "speed", "recorded", "source", "sample_rate", "tear_start_s", "tear_end_s", "range_set_by_hand", "duration_s", "speed_in_per_s",
426434 "energy_db", "energy_raw_db", "background_db", "above_background_db", "median_hz", "centroid_hz", "f10_hz", "f90_hz", "peak_dbfs", "near_clip_samples",
427- "band_low_hz", "band_high_hz", "sheet_length_in",
435+ "energy_band_low_hz", "energy_band_high_hz", "spectrum_band_low_hz", "spectrum_band_high_hz", "sheet_length_in",
428436 ];
429437 const q = (v: unknown) => {
430438 const s = String(v ?? "");
@@ -437,7 +445,7 @@ function exportCsv(rows: Row[], settings: AnalysisSettings) {
437445 m.label, new Date(m.createdAt).toISOString(), m.source, m.sampleRate, a.segment.start.toFixed(4), a.segment.end.toFixed(4), m.segmentManual,
438446 a.duration.toFixed(4), a.speedInPerSec.toFixed(4), db10(a.energy).toFixed(3), db10(a.energyRaw).toFixed(3), db10(a.energyNoise).toFixed(3),
439447 a.snrDb.toFixed(2), a.medianFreq.toFixed(1), a.centroid.toFixed(1), a.f10.toFixed(1), a.f90.toFixed(1), a.peakDbfs.toFixed(2), a.nearClip,
440- settings.bandLow, settings.bandHigh, settings.sheetLengthIn,
448+ settings.energyLow, settings.energyHigh, settings.shapeLow, settings.shapeHigh, settings.sheetLengthIn,
441449 ]
442450 .map(q)
443451 .join(","),
src/components/TearView.tsxmodified+31−19View 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 { detectSegment, frameLevels, smoothLog, spectrogram, type Analysis, type AnalysisSettings, type Segment } from "../analysis/analyze.ts";
3+import { bandLevels, detectSegment, 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 { colorFor, db10, fmtHz, fmtSec, getAnalysis, getAudio, speedStyle } from "../model.ts";
@@ -48,7 +48,9 @@ export function TearView({ meta, settings, onUpdate }: Props) {
4848 };
4949 }, [meta, settings]);
5050
51- const levels = useMemo(() => (x ? frameLevels(x, fs, 0.005) : null), [x, fs]);
51+ const { energyLow, energyHigh } = settings;
52+ const bandLabel = `${fmtKHz(energyLow)}–${fmtKHz(energyHigh)} kHz`;
53+ const levels = useMemo(() => (x ? bandLevels(x, fs, { lo: energyLow, hi: energyHigh }, 0.005) : null), [x, fs, energyLow, energyHigh]);
5254 const spec = useMemo(() => (x ? spectrogram(x, fs) : null), [x, fs]);
5355 const specImage = useMemo(() => (spec ? spectrogramImage(spec) : null), [spec]);
5456 const { slot } = speedStyle(meta.label);
@@ -304,11 +306,11 @@ export function TearView({ meta, settings, onUpdate }: Props) {
304306 const drawSpectrum = useCallback(
305307 (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
306308 if (!specLines) return;
309+ // the energy band
307310 ctx.fillStyle = th.seg;
308- const bl = s.x(settings.bandLow);
309- const bh = s.x(Math.min(settings.bandHigh, fHi));
310- ctx.fillRect(s.left, s.top, bl - s.left, s.bottom - s.top);
311- ctx.fillRect(bh, s.top, s.right - bh, s.bottom - s.top);
311+ const bl = s.x(settings.energyLow);
312+ const bh = s.x(Math.min(settings.energyHigh, fHi));
313+ ctx.fillRect(bl, s.top, bh - bl, s.bottom - s.top);
312314 if (specLines.bg) drawLine(ctx, s, specLines.f, specLines.bg, th.muted, 2, [5, 4]);
313315 drawLine(ctx, s, specLines.f, specLines.tear, mainColor(th), 2);
314316 },
@@ -329,7 +331,8 @@ export function TearView({ meta, settings, onUpdate }: Props) {
329331 if (!seg) warnings.push("No tear was found automatically. Drag across the plot below to mark it.");
330332 if (a && a.nearClip > 0) warnings.push(`${a.nearClip} samples in the tear are at or near full scale (clipping). The energy is underestimated; consider re-recording further from the microphone.`);
331333 if (a && !a.noiseEsd) warnings.push("There is not enough quiet before or after the tear to measure the background, so nothing was subtracted. Leave about a second of quiet at each end.");
332- else if (a && a.snrDb < 10) warnings.push(`The tear is only ${a.snrDb.toFixed(1)} dB above the background, so the energy depends on how well the background is estimated.`);
334+ else if (a && a.snrDb < 10)
335+ warnings.push(`In the energy band (${bandLabel}) the tear is only ${a.snrDb.toFixed(1)} dB above the background, so the energy depends on how well the background is estimated.`);
333336 if (seg && (seg.start < 0.05 || seg.end > dur - 0.05)) warnings.push("The tear touches the start or end of the recording and may be cut off.");
334337
335338 const th = readTheme(document.documentElement);
@@ -346,7 +349,10 @@ export function TearView({ meta, settings, onUpdate }: Props) {
346349 <div className="plot-head">
347350 <div>
348351 <h3>Tear range</h3>
349- <p className="caption">Drag across the plot to mark where the tear is. Drag a dark edge to adjust it. Everything below uses only this range.</p>
352+ <p className="caption">
353+ Sound level in the energy band ({bandLabel}) over the whole recording. Drag across the plot to mark where the tear is. Drag a dark edge to
354+ adjust it. Everything below uses only this range.
355+ </p>
350356 </div>
351357 <div className="toolbar">
352358 <button className="primary" disabled={!x || !seg} onClick={() => x && seg && play(meta.id, x, fs, seg.start, seg.end)}>
@@ -365,7 +371,7 @@ export function TearView({ meta, settings, onUpdate }: Props) {
365371 xRange={[0, dur]}
366372 yRange={levelRange}
367373 xLabel="time (s)"
368- yLabel="level (dBFS)"
374+ yLabel={`level ${bandLabel} (dBFS)`}
369375 draw={drawRange}
370376 hover={(p) => {
371377 const lines = [`${p.xv.toFixed(2)} s`];
@@ -385,9 +391,10 @@ export function TearView({ meta, settings, onUpdate }: Props) {
385391 disabled={!x}
386392 onClick={() => {
387393 if (!x) return;
388- const s = detectSegment(x, fs);
394+ const band = energyBand(settings);
395+ const s = detectSegment(x, fs, band);
389396 setSeg(s);
390- onUpdate({ ...meta, segment: s, segmentManual: false });
397+ onUpdate({ ...meta, segment: s, segmentManual: false, detectBand: band });
391398 }}
392399 >
393400 Find tear automatically
@@ -397,7 +404,7 @@ export function TearView({ meta, settings, onUpdate }: Props) {
397404
398405 <section className="card">
399406 <h3>Results</h3>
400- <Stats a={a} settings={settings} />
407+ <Stats a={a} settings={settings} bandLabel={bandLabel} />
401408 </section>
402409
403410 <section className="card">
@@ -481,7 +488,7 @@ export function TearView({ meta, settings, onUpdate }: Props) {
481488 <i className="swatch dashed" /> background alone, over the same duration
482489 </span>
483490 <span>
484- <i className="swatch shade" /> outside the analysis band ({fmtHz(settings.bandLow)}–{fmtHz(settings.bandHigh)})
491+ <i className="swatch shade" /> energy band ({bandLabel})
485492 </span>
486493 </div>
487494 </section>
@@ -523,20 +530,25 @@ function RangeInputs({ seg, dur, onCommit }: { seg: Segment | null; dur: number;
523530 );
524531 }
525532
526-function Stats({ a, settings }: { a: Analysis | null; settings: AnalysisSettings }) {
533+function fmtKHz(hz: number) {
534+ return `${+(hz / 1000).toFixed(2)}`;
535+}
536+
537+function Stats({ a, settings, bandLabel }: { a: Analysis | null; settings: AnalysisSettings; bandLabel: string }) {
538+ const shape = `${fmtHz(settings.shapeLow)}–${fmtHz(settings.shapeHigh)}`;
527539 if (!a) return <p className="muted">No tear range.</p>;
528540 const items: [string, string, string?][] = [
529541 ["Tear duration", fmtSec(a.duration)],
530542 ["Speed", `${a.speedInPerSec.toFixed(2)} in/s`, `${settings.sheetLengthIn} in ÷ duration`],
531- ["Sound energy", `${db10(a.energy).toFixed(1)} dB`, "background removed (relative units)"],
532- ["Median frequency", fmtHz(a.medianFreq), "half the energy above, half below"],
533- ["Centroid", fmtHz(a.centroid), "energy-weighted mean frequency"],
534- ["Mean power", `${db10(a.energy / a.duration).toFixed(1)} dBFS`, "energy ÷ duration"],
543+ ["Sound energy", Number.isFinite(db10(a.energy)) && a.energy > 0 ? `${db10(a.energy).toFixed(1)} dB` : "–", `${bandLabel}, background removed (relative units)`],
544+ ["Median frequency", fmtHz(a.medianFreq), `half the energy above, half below (${shape})`],
545+ ["Centroid", fmtHz(a.centroid), `energy-weighted mean frequency (${shape})`],
546+ ["Mean power", a.energy > 0 ? `${db10(a.energy / a.duration).toFixed(1)} dBFS` : "–", `${bandLabel}, energy ÷ duration`],
535547 ["Peak", `${a.peakDbfs.toFixed(1)} dBFS`, a.nearClip ? `${a.nearClip} samples near clipping` : "no clipping"],
536548 [
537549 "Above background",
538550 Number.isFinite(a.snrDb) ? `${a.snrDb.toFixed(1)} dB` : "–",
539- a.backgroundDbfs !== null ? `background ${a.backgroundDbfs.toFixed(1)} dBFS` : "no background estimate",
551+ a.backgroundDbfs !== null ? `${bandLabel}; background ${a.backgroundDbfs.toFixed(1)} dBFS` : "no background estimate",
540552 ],
541553 ];
542554 return (
src/model.tsmodified+1−1View file
@@ -35,7 +35,7 @@ export function colorFor(slot: number | null, series: string[], muted: string) {
3535
3636 // ---------- settings ----------
3737
38-const SETTINGS_KEY = "rsa-settings";
38+const SETTINGS_KEY = "rsa-settings-v2";
3939
4040 export function loadSettings(): AnalysisSettings {
4141 try {
src/storage/db.tsmodified+1−0View file
@@ -16,6 +16,7 @@ export interface RecordingMeta {
1616 length: number; // samples
1717 segment: Segment | null; // the tear, in seconds
1818 segmentManual: boolean;
19+ detectBand?: { lo: number; hi: number }; // band the automatic range was found in
1920 capture?: CaptureInfo;
2021 }
2122
src/styles.cssmodified+15−0View file
@@ -775,3 +775,18 @@ button.link {
775775 .plot-head .caption {
776776 margin: 2px 0 0;
777777 }
778+
779+.settings {
780+ flex-direction: column;
781+ align-items: stretch;
782+ gap: 10px;
783+}
784+.settings-row {
785+ display: flex;
786+ flex-wrap: wrap;
787+ gap: 10px;
788+ align-items: center;
789+}
790+.settings-row > b {
791+ min-width: 110px;
792+}