d8b88deRecord tab organised around five fixed speeds, one tear eachJeremy Magland 1import { useCallback, useEffect, useMemo, useRef, useState } from "react";
2import { CanvasPlot, drawLine, readTheme, type PointerInfo, type Scales, type Theme } from "./CanvasPlot.tsx";
8bf83cfMeasure energy and find the tear in a 15–20 kHz bandJeremy Magland 3import { bandLevels, detectSegment, energyBand, smoothLog, spectrogram, type Analysis, type AnalysisSettings, type Segment } from "../analysis/analyze.ts";
d8b88deRecord tab organised around five fixed speeds, one tear eachJeremy Magland 4import type { RecordingMeta } from "../storage/db.ts";
5import { play, stop as stopPlay, usePlayhead } from "../audio/player.ts";
09371b0Open-ended samples instead of fixed speedsJeremy Magland 6import { db10, fmtHz, fmtSec, getAnalysis, getAudio } from "../model.ts";
d8b88deRecord tab organised around five fixed speeds, one tear eachJeremy Magland 7import { magma } from "../colormap.ts";
9interface Props {
10 meta: RecordingMeta;
11 settings: AnalysisSettings;
12 onUpdate: (m: RecordingMeta) => void;
13}
15const SMOOTHING: [string, number][] = [
16 ["none", 0],
17 ["1/24 octave", 1 / 24],
18 ["1/12 octave", 1 / 12],
19 ["1/6 octave", 1 / 6],
20 ["1/3 octave", 1 / 3],
21];
23export function TearView({ meta, settings, onUpdate }: Props) {
24 const [x, setX] = useState<Float32Array | null>(null);
25 const [analysis, setAnalysis] = useState<Analysis | null>(null);
26 const fs = meta.sampleRate;
27 const dur = meta.length / fs;
28 const [seg, setSeg] = useState<Segment | null>(meta.segment);
29 const playhead = usePlayhead(meta.id);
31 useEffect(() => {
32 let live = true;
33 setX(null);
34 getAudio(meta.id).then((a) => live && setX(a));
35 return () => {
36 live = false;
37 stopPlay();
38 };
39 }, [meta.id]);
41 useEffect(() => setSeg(meta.segment), [meta.segment]);
43 useEffect(() => {
44 let live = true;
45 getAnalysis(meta, settings).then((a) => live && setAnalysis(a));
46 return () => {
47 live = false;
48 };
49 }, [meta, settings]);
8bf83cfMeasure energy and find the tear in a 15–20 kHz bandJeremy Magland 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]);
d8b88deRecord tab organised around five fixed speeds, one tear eachJeremy Magland 54 const spec = useMemo(() => (x ? spectrogram(x, fs) : null), [x, fs]);
55 const specImage = useMemo(() => (spec ? spectrogramImage(spec) : null), [spec]);
09371b0Open-ended samples instead of fixed speedsJeremy Magland 56 const mainColor = (th: Theme) => th.series[0];
58 const commitSeg = (s: Segment | null) => {
59 setSeg(s);
60 onUpdate({ ...meta, segment: s, segmentManual: true });
61 };
63 // ---------- tear range (whole recording) ----------
64 const drag = useRef<{ kind: "start" | "end" | "new"; anchor: number; px0: number; before: Segment | null } | null>(null);
65 const edgeAt = (p: PointerInfo): "start" | "end" | null => {
66 if (!seg) return null;
67 const ds = Math.abs(p.px - p.scales.x(seg.start));
68 const de = Math.abs(p.px - p.scales.x(seg.end));
69 if (Math.min(ds, de) > 8) return null;
70 return ds <= de ? "start" : "end";
71 };
72 const clampT = (t: number) => Math.min(Math.max(t, 0), dur);
73 const rangeHandlers = {
74 onPointer: (type: "down" | "move" | "up", p: PointerInfo) => {
75 if (type === "down") {
76 drag.current = { kind: edgeAt(p) ?? "new", anchor: clampT(p.xv), px0: p.px, before: seg };
77 } else if (type === "move" && drag.current) {
78 const d = drag.current;
79 const t = clampT(p.xv);
80 if (d.kind === "new") {
81 if (Math.abs(p.px - d.px0) > 3) setSeg({ start: Math.min(d.anchor, t), end: Math.max(d.anchor, t) });
82 } else if (seg) {
83 // dragging an edge past the other one swaps them
84 const other = d.kind === "start" ? seg.end : seg.start;
85 setSeg({ start: Math.min(t, other), end: Math.max(t, other) });
86 if ((d.kind === "start" && t > other) || (d.kind === "end" && t < other)) d.kind = d.kind === "start" ? "end" : "start";
87 }
88 } else if (type === "up" && drag.current) {
89 const d = drag.current;
90 drag.current = null;
91 if (d.kind === "new" && Math.abs(p.px - d.px0) <= 3) return; // a plain click changes nothing
92 if (seg && seg.end - seg.start >= 0.01) commitSeg(seg);
93 else setSeg(d.before);
94 }
95 },
96 cursor: (p: PointerInfo) => (edgeAt(p) ? "ew-resize" : "crosshair"),
97 };
99 const levelRange = useMemo<[number, number]>(() => {
100 if (!levels) return [-100, 0];
101 const dbs = Array.from(levels.power, (p) => db10(p)).sort((a, b) => a - b);
102 const lo = dbs[Math.floor(dbs.length * 0.01)] ?? -100;
103 return [Math.max(-140, Math.floor((lo - 6) / 10) * 10), 0];
104 }, [levels]);
106 const drawPlayhead = (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
107 if (playhead === null) return;
108 ctx.strokeStyle = th.ink;
109 ctx.lineWidth = 2;
110 ctx.beginPath();
111 ctx.moveTo(s.x(playhead), s.top);
112 ctx.lineTo(s.x(playhead), s.bottom);
113 ctx.stroke();
114 };
116 const drawRange = useCallback(
117 (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
118 if (seg) {
119 const a = s.x(seg.start);
120 const b = s.x(seg.end);
121 ctx.fillStyle = th.seg;
122 ctx.fillRect(a, s.top, b - a, s.bottom - s.top);
123 }
124 if (levels) {
125 const { frameSec, power } = levels;
126 const perPx = Math.max(1, Math.floor(power.length / ((s.right - s.left) * 2)));
127 const xs: number[] = [];
128 const ys: number[] = [];
129 for (let i = 0; i < power.length; i += perPx) {
130 let m = 0;
131 for (let j = i; j < Math.min(i + perPx, power.length); j++) m = Math.max(m, power[j]);
132 xs.push((i + perPx / 2) * frameSec);
133 ys.push(db10(m));
134 }
135 drawLine(ctx, s, xs, ys, mainColor(th), 1.5);
136 }
137 if (seg) {
138 // edges with grab handles
139 for (const t of [seg.start, seg.end]) {
140 const px = s.x(t);
141 ctx.strokeStyle = th.ink;
142 ctx.lineWidth = 2;
143 ctx.beginPath();
144 ctx.moveTo(px, s.top);
145 ctx.lineTo(px, s.bottom);
146 ctx.stroke();
147 ctx.fillStyle = th.ink;
148 ctx.beginPath();
149 ctx.roundRect(px - 4, (s.top + s.bottom) / 2 - 12, 8, 24, 3);
150 ctx.fill();
151 }
152 }
153 drawPlayhead(ctx, s, th);
154 },
155 // eslint-disable-next-line react-hooks/exhaustive-deps
159 // ---------- close-up ----------
160 const fit = useCallback(
161 (s: Segment | null): [number, number] => {
162 if (!s) return [0, dur];
163 const m = Math.max(0.05, 0.08 * (s.end - s.start));
164 return [Math.max(0, s.start - m), Math.min(dur, s.end + m)];
165 },
166 [dur],
167 );
168 const [view, setView] = useState<[number, number]>(() => fit(meta.segment));
169 useEffect(() => setView(fit(meta.segment)), [meta.id, meta.segment, fit]);
170 const clampView = (a: number, b: number): [number, number] => {
171 const w = Math.min(dur, Math.max(b - a, 0.002));
172 let s = Math.max(0, a);
173 if (s + w > dur) s = dur - w;
174 return [s, s + w];
175 };
176 const zoom = (f: number, around = (view[0] + view[1]) / 2) => setView(clampView(around - (around - view[0]) * f, around + (view[1] - around) * f));
177 const pan = useRef<{ px0: number; view0: [number, number] } | null>(null);
178 const closeHandlers = {
179 onPointer: (type: "down" | "move" | "up", p: PointerInfo) => {
180 if (type === "down") pan.current = { px0: p.px, view0: view };
181 else if (type === "move" && pan.current) {
182 const d = pan.current;
183 const dt = ((p.px - d.px0) / (p.scales.right - p.scales.left)) * (d.view0[1] - d.view0[0]);
184 setView(clampView(d.view0[0] - dt, d.view0[1] - dt));
185 } else pan.current = null;
186 },
187 // pinch on a trackpad (or ctrl + scroll) zooms; plain scrolling scrolls the page
188 onWheel: (p: PointerInfo, ev: WheelEvent) => {
189 if (!ev.ctrlKey) return false;
190 zoom(Math.exp(ev.deltaY * 0.01), Math.min(Math.max(p.xv, view[0]), view[1]));
191 return true;
192 },
193 onDoubleClick: () => setView(fit(seg)),
194 cursor: () => "grab",
195 };
197 const drawEdges = (ctx: CanvasRenderingContext2D, s: Scales, color: string) => {
198 if (!seg) return;
199 ctx.strokeStyle = color;
200 ctx.lineWidth = 1.5;
201 ctx.setLineDash([5, 4]);
202 ctx.beginPath();
203 for (const t of [seg.start, seg.end]) {
204 ctx.moveTo(s.x(t), s.top);
205 ctx.lineTo(s.x(t), s.bottom);
206 }
207 ctx.stroke();
208 ctx.setLineDash([]);
209 };
211 const waveMax = useMemo(() => {
212 if (!x) return 1;
213 let m = 0;
214 for (let i = 0; i < x.length; i++) m = Math.max(m, Math.abs(x[i]));
215 return Math.max(m * 1.05, 1e-4);
216 }, [x]);
218 const drawWave = useCallback(
219 (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
220 if (x) {
221 const color = mainColor(th);
222 const a = Math.max(0, Math.floor(view[0] * fs));
223 const b = Math.min(x.length, Math.ceil(view[1] * fs));
224 const px = s.right - s.left;
225 const perPx = (b - a) / px;
226 if (perPx < 2) {
227 const xs: number[] = [];
228 const ys: number[] = [];
229 for (let i = Math.max(0, a - 1); i < Math.min(x.length, b + 1); i++) {
230 xs.push(i / fs);
231 ys.push(x[i]);
232 }
233 drawLine(ctx, s, xs, ys, color, 1.5);
234 if (perPx < 0.15) {
235 ctx.fillStyle = color;
236 for (let i = 0; i < xs.length; i++) ctx.fillRect(s.x(xs[i]) - 1.5, s.y(ys[i]) - 1.5, 3, 3);
237 }
238 } else {
239 ctx.fillStyle = color;
240 for (let c = 0; c < px; c++) {
241 const i0 = a + Math.floor(c * perPx);
242 const i1 = Math.min(b, a + Math.floor((c + 1) * perPx));
243 let lo = Infinity;
244 let hi = -Infinity;
245 for (let i = i0; i < i1; i++) {
246 const v = x[i];
247 if (v < lo) lo = v;
248 if (v > hi) hi = v;
249 }
250 if (lo > hi) continue;
251 const y0 = s.y(hi);
252 ctx.fillRect(s.left + c, y0, 1, Math.max(1, s.y(lo) - y0));
253 }
254 }
255 }
256 drawEdges(ctx, s, th.ink2);
257 drawPlayhead(ctx, s, th);
258 },
259 // eslint-disable-next-line react-hooks/exhaustive-deps
263 const drawSpec = useCallback(
264 (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
265 if (spec && specImage) {
266 const c0 = (view[0] - spec.t0) / spec.dt;
267 const c1 = (view[1] - spec.t0) / spec.dt;
268 ctx.imageSmoothingEnabled = c1 - c0 < s.right - s.left;
269 const sx0 = Math.max(0, c0);
270 const sx1 = Math.min(spec.cols, c1);
271 const dx0 = s.x(spec.t0 + sx0 * spec.dt);
272 const dx1 = s.x(spec.t0 + sx1 * spec.dt);
273 if (sx1 > sx0) ctx.drawImage(specImage, sx0, 0, sx1 - sx0, spec.bins, dx0, s.top, dx1 - dx0, s.bottom - s.top);
274 }
275 drawEdges(ctx, s, "#ffffff");
276 if (playhead !== null) {
277 ctx.strokeStyle = "#ffffff";
278 ctx.lineWidth = 2;
279 ctx.beginPath();
280 ctx.moveTo(s.x(playhead), s.top);
281 ctx.lineTo(s.x(playhead), s.bottom);
282 ctx.stroke();
283 }
284 void th;
285 },
286 // eslint-disable-next-line react-hooks/exhaustive-deps
287 [spec, specImage, view, seg, playhead],
288 );
290 // ---------- spectrum ----------
291 const [smoothing, setSmoothing] = useState(1 / 12);
292 const fLo = 20;
293 const fHi = fs / 2;
294 const specLines = useMemo(() => {
295 if (!analysis) return null;
296 const tear = smoothLog(analysis.freqs, analysis.esd, fLo, fHi, smoothing);
297 const bg = analysis.noiseEsd ? smoothLog(analysis.freqs, analysis.noiseEsd, fLo, fHi, smoothing) : null;
298 return { f: tear.f, tear: tear.v.map(db10), bg: bg ? bg.v.map(db10) : null };
299 }, [analysis, smoothing, fHi]);
300 const specRange = useMemo<[number, number]>(() => {
301 if (!specLines) return [-160, -60];
302 const top = Math.max(...specLines.tear.filter(Number.isFinite));
303 return [Math.floor((top - 70) / 10) * 10, Math.ceil((top + 3) / 10) * 10];
304 }, [specLines]);
305 const drawSpectrum = useCallback(
306 (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
307 if (!specLines) return;
d8b88deRecord tab organised around five fixed speeds, one tear eachJeremy Magland 309 ctx.fillStyle = th.seg;
8bf83cfMeasure energy and find the tear in a 15–20 kHz bandJeremy Magland 310 const bl = s.x(settings.energyLow);
311 const bh = s.x(Math.min(settings.energyHigh, fHi));
312 ctx.fillRect(bl, s.top, bh - bl, s.bottom - s.top);
d8b88deRecord tab organised around five fixed speeds, one tear eachJeremy Magland 313 if (specLines.bg) drawLine(ctx, s, specLines.f, specLines.bg, th.muted, 2, [5, 4]);
314 drawLine(ctx, s, specLines.f, specLines.tear, mainColor(th), 2);
315 },
316 // eslint-disable-next-line react-hooks/exhaustive-deps
319 const specHover = (p: PointerInfo) => {
320 if (!specLines) return null;
321 let best = 0;
322 for (let i = 1; i < specLines.f.length; i++) if (Math.abs(Math.log(specLines.f[i] / p.xv)) < Math.abs(Math.log(specLines.f[best] / p.xv))) best = i;
323 const lines = [fmtHz(specLines.f[best]), `tear: ${specLines.tear[best].toFixed(1)} dB`];
324 if (specLines.bg) lines.push(`background: ${specLines.bg[best].toFixed(1)} dB`);
325 return { lines, x: specLines.f[best], y: specLines.tear[best] };
326 };
328 const a = analysis;
329 const warnings: string[] = [];
330 if (!seg) warnings.push("No tear was found automatically. Drag across the plot below to mark it.");
331 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.`);
332 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.");
8bf83cfMeasure energy and find the tear in a 15–20 kHz bandJeremy Magland 333 else if (a && a.snrDb < 10)
334 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.`);
d8b88deRecord tab organised around five fixed speeds, one tear eachJeremy Magland 335 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.");
337 const th = readTheme(document.documentElement);
339 return (
340 <>
341 {warnings.map((w) => (
342 <div key={w} className="warn">
343 ⚠ {w}
344 </div>
345 ))}
347 <section className="card">
348 <div className="plot-head">
349 <div>
350 <h3>Tear range</h3>
8bf83cfMeasure energy and find the tear in a 15–20 kHz bandJeremy Magland 351 <p className="caption">
352 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
353 adjust it. Everything below uses only this range.
354 </p>
356 <div className="toolbar">
357 <button className="primary" disabled={!x || !seg} onClick={() => x && seg && play(meta.id, x, fs, seg.start, seg.end)}>
358 ▶ Play tear
359 </button>
360 <button disabled={!x} onClick={() => x && play(meta.id, x, fs, 0, dur)}>
361 ▶ Play whole recording
362 </button>
363 <button disabled={playhead === null} onClick={stopPlay}>
364 ■ Stop
365 </button>
366 </div>
367 </div>
368 <CanvasPlot
369 height={150}
370 xRange={[0, dur]}
371 yRange={levelRange}
372 xLabel="time (s)"
8bf83cfMeasure energy and find the tear in a 15–20 kHz bandJeremy Magland 373 yLabel={`level ${bandLabel} (dBFS)`}
d8b88deRecord tab organised around five fixed speeds, one tear eachJeremy Magland 374 draw={drawRange}
375 hover={(p) => {
376 const lines = [`${p.xv.toFixed(2)} s`];
377 if (levels) {
378 const i = Math.floor(p.xv / levels.frameSec);
379 if (i >= 0 && i < levels.power.length) lines.push(`${db10(levels.power[i]).toFixed(1)} dBFS`);
380 }
381 return { lines };
382 }}
383 ariaLabel="Sound level over the whole recording, with the tear range"
384 {...rangeHandlers}
385 />
386 <RangeInputs seg={seg} dur={dur} onCommit={commitSeg} />
387 <div className="range-row">
388 <span className="muted small">{meta.segmentManual ? "Range set by hand." : "Range found automatically."}</span>
389 <button
390 disabled={!x}
391 onClick={() => {
392 if (!x) return;
8bf83cfMeasure energy and find the tear in a 15–20 kHz bandJeremy Magland 393 const band = energyBand(settings);
394 const s = detectSegment(x, fs, band);
8bf83cfMeasure energy and find the tear in a 15–20 kHz bandJeremy Magland 396 onUpdate({ ...meta, segment: s, segmentManual: false, detectBand: band });
398 >
399 Find tear automatically
400 </button>
401 </div>
402 </section>
404 <section className="card">
405 <h3>Results</h3>
8bf83cfMeasure energy and find the tear in a 15–20 kHz bandJeremy Magland 406 <Stats a={a} settings={settings} bandLabel={bandLabel} />
409 <section className="card">
410 <div className="plot-head">
411 <div>
412 <h3>Close-up</h3>
413 <p className="caption">Drag to move along. Pinch (or ctrl + scroll) to zoom. Dashed lines mark the tear range.</p>
414 </div>
415 <div className="toolbar">
416 <button onClick={() => zoom(0.5)} aria-label="Zoom in">
417 + Zoom in
418 </button>
419 <button onClick={() => zoom(2)} aria-label="Zoom out">
420 − Zoom out
421 </button>
422 <button onClick={() => setView(fit(seg))}>Fit tear</button>
423 <button onClick={() => setView([0, dur])}>Whole recording</button>
424 </div>
425 </div>
426 <CanvasPlot
427 height={160}
428 xRange={view}
429 yRange={[-waveMax, waveMax]}
430 xLabel="time (s)"
431 yLabel="waveform"
432 hideXTicks
433 draw={drawWave}
434 hover={(p) => ({ lines: [`${p.xv.toFixed(4)} s`] })}
435 ariaLabel="Waveform close-up"
436 {...closeHandlers}
437 />
438 <CanvasPlot
439 height={230}
440 xRange={view}
441 yRange={[0, fs / 2]}
442 xLabel="time (s)"
443 yLabel="frequency (Hz)"
444 draw={drawSpec}
445 hover={(p) => ({ lines: [`${p.xv.toFixed(3)} s`, fmtHz(p.yv)] })}
446 ariaLabel="Spectrogram close-up"
447 {...closeHandlers}
448 />
449 <p className="caption">
450 Showing {fmtSec(view[0])}–{fmtSec(view[1])}. Spectrogram: 1024-point windows; brighter is louder, spanning the top 90 dB of this recording.
451 </p>
452 </section>
454 <section className="card">
455 <div className="plot-head">
456 <div>
457 <h3>Frequency makeup of the tear</h3>
458 <p className="caption">How the tear's sound energy is spread over frequency, compared with the background noise alone.</p>
459 </div>
460 <label className="toolbar">
461 smoothing
462 <select value={smoothing} onChange={(e) => setSmoothing(+e.target.value)}>
463 {SMOOTHING.map(([n, v]) => (
464 <option key={n} value={v}>
465 {n}
466 </option>
467 ))}
468 </select>
469 </label>
470 </div>
471 <CanvasPlot
472 height={300}
473 xRange={[fLo, fHi]}
474 xLog
475 yRange={specRange}
476 xLabel="frequency (Hz)"
477 yLabel="energy density (dB re FS²·s/Hz)"
478 draw={drawSpectrum}
479 hover={specHover}
480 ariaLabel="Energy spectral density of the tear"
481 />
482 <div className="legend">
483 <span>
09371b0Open-ended samples instead of fixed speedsJeremy Magland 484 <i className="swatch" style={{ background: th.series[0] }} /> tear
486 <span>
487 <i className="swatch dashed" /> background alone, over the same duration
488 </span>
489 <span>
8bf83cfMeasure energy and find the tear in a 15–20 kHz bandJeremy Magland 490 <i className="swatch shade" /> energy band ({bandLabel})
492 </div>
493 </section>
494 </>
495 );
496}
498function RangeInputs({ seg, dur, onCommit }: { seg: Segment | null; dur: number; onCommit: (s: Segment) => void }) {
499 const [a, setA] = useState("");
500 const [b, setB] = useState("");
501 useEffect(() => {
502 setA(seg ? seg.start.toFixed(3) : "");
503 setB(seg ? seg.end.toFixed(3) : "");
504 }, [seg]);
505 const commit = () => {
506 const s = Math.min(Math.max(+a, 0), dur);
507 const e = Math.min(Math.max(+b, 0), dur);
508 if (Number.isFinite(s) && Number.isFinite(e) && e - s >= 0.01 && (!seg || s !== seg.start || e !== seg.end)) onCommit({ start: s, end: e });
509 else {
510 setA(seg ? seg.start.toFixed(3) : "");
511 setB(seg ? seg.end.toFixed(3) : "");
512 }
513 };
514 const key = (e: React.KeyboardEvent<HTMLInputElement>) => e.key === "Enter" && (e.target as HTMLInputElement).blur();
515 return (
516 <div className="range-inputs">
517 <label>
518 Start
519 <input type="number" step="0.01" value={a} onChange={(e) => setA(e.target.value)} onBlur={commit} onKeyDown={key} /> s
520 </label>
521 <label>
522 End
523 <input type="number" step="0.01" value={b} onChange={(e) => setB(e.target.value)} onBlur={commit} onKeyDown={key} /> s
524 </label>
525 <span>
526 Duration <b>{seg ? fmtSec(seg.end - seg.start) : "–"}</b>
527 </span>
528 </div>
529 );
530}
8bf83cfMeasure energy and find the tear in a 15–20 kHz bandJeremy Magland 532function fmtKHz(hz: number) {
533 return `${+(hz / 1000).toFixed(2)}`;
534}
536function Stats({ a, settings, bandLabel }: { a: Analysis | null; settings: AnalysisSettings; bandLabel: string }) {
d8b88deRecord tab organised around five fixed speeds, one tear eachJeremy Magland 537 if (!a) return <p className="muted">No tear range.</p>;
538 const items: [string, string, string?][] = [
539 ["Tear duration", fmtSec(a.duration)],
540 ["Speed", `${a.speedInPerSec.toFixed(2)} in/s`, `${settings.sheetLengthIn} in ÷ duration`],
8bf83cfMeasure energy and find the tear in a 15–20 kHz bandJeremy Magland 541 ["Sound energy", Number.isFinite(db10(a.energy)) && a.energy > 0 ? `${db10(a.energy).toFixed(1)} dB` : "–", `${bandLabel}, background removed (relative units)`],
542 ["Mean power", a.energy > 0 ? `${db10(a.energy / a.duration).toFixed(1)} dBFS` : "–", `${bandLabel}, energy ÷ duration`],
d8b88deRecord tab organised around five fixed speeds, one tear eachJeremy Magland 543 ["Peak", `${a.peakDbfs.toFixed(1)} dBFS`, a.nearClip ? `${a.nearClip} samples near clipping` : "no clipping"],
544 [
545 "Above background",
546 Number.isFinite(a.snrDb) ? `${a.snrDb.toFixed(1)} dB` : "–",
8bf83cfMeasure energy and find the tear in a 15–20 kHz bandJeremy Magland 547 a.backgroundDbfs !== null ? `${bandLabel}; background ${a.backgroundDbfs.toFixed(1)} dBFS` : "no background estimate",
549 ];
550 return (
551 <div className="stats">
552 {items.map(([k, v, sub]) => (
553 <div key={k} className="stat">
554 <div className="stat-k">{k}</div>
555 <div className="stat-v">{v}</div>
556 {sub && <div className="stat-sub">{sub}</div>}
557 </div>
558 ))}
559 </div>
560 );
561}
563function spectrogramImage(spec: ReturnType<typeof spectrogram>): HTMLCanvasElement {
564 const c = document.createElement("canvas");
565 c.width = spec.cols;
566 c.height = spec.bins;
567 const ctx = c.getContext("2d")!;
568 const img = ctx.createImageData(spec.cols, spec.bins);
569 const top = spec.maxDb;
570 const range = 90;
571 for (let col = 0; col < spec.cols; col++) {
572 for (let k = 0; k < spec.bins; k++) {
573 const v = (spec.db[col * spec.bins + k] - (top - range)) / range;
574 const [r, g, b] = magma(Math.min(1, Math.max(0, v)));
575 const o = ((spec.bins - 1 - k) * spec.cols + col) * 4;
576 img.data[o] = r;
577 img.data[o + 1] = g;
578 img.data[o + 2] = b;
579 img.data[o + 3] = 255;
580 }
581 }
582 ctx.putImageData(img, 0, 0);
583 return c;
584}