1import { useCallback, useEffect, useMemo, useRef, useState } from "react";
2import { CanvasPlot, drawLine, readTheme, type PointerInfo, type Scales, type Theme } from "./CanvasPlot.tsx";
3import { bandLevels, bandpass, DETECT_VERSION, detectTear, energyBand, smoothLog, spectrogram, type Analysis, type AnalysisSettings, type Segment } from "../analysis/analyze.ts";
4import type { RecordingMeta } from "../storage/db.ts";
5import { play, stop as stopPlay, usePlayhead } from "../audio/player.ts";
6import { db10, fmtHz, fmtSec, getAnalysis, getAudio } from "../model.ts";
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]);
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]);
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);
58 const spec = useMemo(() => (x ? spectrogram(x, fs) : null), [x, fs]);
59 const specImage = useMemo(() => (spec ? spectrogramImage(spec) : null), [spec]);
60 const mainColor = (th: Theme) => th.series[0];
62 const commitSeg = (s: Segment | null) => {
63 setSeg(s);
64 onUpdate({ ...meta, segment: s, segmentManual: true });
65 };
67 // ---------- shared time view (level, waveform, spectrogram) ----------
68 const [view, setView] = useState<[number, number]>([0, dur]);
69 useEffect(() => setView([0, meta.length / meta.sampleRate]), [meta.id, meta.length, meta.sampleRate]);
70 const clampView = (a: number, b: number): [number, number] => {
71 const w = Math.min(dur, Math.max(b - a, 0.002));
72 let s = Math.max(0, a);
73 if (s + w > dur) s = dur - w;
74 return [s, s + w];
75 };
76 const zoom = (f: number, around = (view[0] + view[1]) / 2) => setView(clampView(around - (around - view[0]) * f, around + (view[1] - around) * f));
77 const fitTear = () => {
78 if (!seg) return;
79 const m = Math.max(0.05, 0.08 * (seg.end - seg.start));
80 setView(clampView(seg.start - m, seg.end + m));
81 };
83 // ---------- selecting the tear range (on any of the three plots) ----------
84 const drag = useRef<{ kind: "start" | "end" | "new"; anchor: number; px0: number; before: Segment | null } | null>(null);
85 const edgeAt = (p: PointerInfo): "start" | "end" | null => {
86 if (!seg) return null;
87 const ds = Math.abs(p.px - p.scales.x(seg.start));
88 const de = Math.abs(p.px - p.scales.x(seg.end));
89 if (Math.min(ds, de) > 8) return null;
90 return ds <= de ? "start" : "end";
91 };
92 const clampT = (t: number) => Math.min(Math.max(t, 0), dur);
93 const timeHandlers = {
94 onPointer: (type: "down" | "move" | "up", p: PointerInfo) => {
95 if (type === "down") {
96 drag.current = { kind: edgeAt(p) ?? "new", anchor: clampT(p.xv), px0: p.px, before: seg };
97 } else if (type === "move" && drag.current) {
98 const d = drag.current;
99 const t = clampT(p.xv);
100 if (d.kind === "new") {
101 if (Math.abs(p.px - d.px0) > 3) setSeg({ start: Math.min(d.anchor, t), end: Math.max(d.anchor, t) });
102 } else if (seg) {
103 // dragging an edge past the other one swaps them
104 const other = d.kind === "start" ? seg.end : seg.start;
105 setSeg({ start: Math.min(t, other), end: Math.max(t, other) });
106 if ((d.kind === "start" && t > other) || (d.kind === "end" && t < other)) d.kind = d.kind === "start" ? "end" : "start";
107 }
108 } else if (type === "up" && drag.current) {
109 const d = drag.current;
110 drag.current = null;
111 if (d.kind === "new" && Math.abs(p.px - d.px0) <= 3) return; // a plain click changes nothing
112 if (seg && seg.end - seg.start >= 0.005) commitSeg(seg);
113 else setSeg(d.before);
114 }
115 },
116 // pinch (or ctrl + scroll) zooms, sideways two-finger scroll moves along; plain scrolling scrolls the page
117 onWheel: (p: PointerInfo, ev: WheelEvent) => {
118 if (ev.ctrlKey) {
119 zoom(Math.exp(ev.deltaY * 0.01), Math.min(Math.max(p.xv, view[0]), view[1]));
120 return true;
121 }
122 if (Math.abs(ev.deltaX) > Math.abs(ev.deltaY)) {
123 const shift = (ev.deltaX / (p.scales.right - p.scales.left)) * (view[1] - view[0]);
124 setView(clampView(view[0] + shift, view[1] + shift));
125 return true;
126 }
127 return false;
128 },
129 onDoubleClick: () => setView([0, dur]),
130 cursor: (p: PointerInfo) => (edgeAt(p) ? "ew-resize" : "crosshair"),
131 };
133 // shading (or dimming, on the spectrogram), edges with grab handles, playhead
134 const drawSelection = (ctx: CanvasRenderingContext2D, s: Scales, th: Theme, onImage: boolean) => {
135 const ink = onImage ? "#ffffff" : th.ink;
136 if (seg) {
137 const a = s.x(seg.start);
138 const b = s.x(seg.end);
139 if (onImage) {
140 ctx.fillStyle = "rgba(0,0,0,0.45)";
141 ctx.fillRect(s.left, s.top, a - s.left, s.bottom - s.top);
142 ctx.fillRect(b, s.top, s.right - b, s.bottom - s.top);
143 }
144 for (const px of [a, b]) {
145 ctx.strokeStyle = ink;
146 ctx.lineWidth = 2;
147 ctx.beginPath();
148 ctx.moveTo(px, s.top);
149 ctx.lineTo(px, s.bottom);
150 ctx.stroke();
151 ctx.fillStyle = ink;
152 ctx.beginPath();
153 ctx.roundRect(px - 4, (s.top + s.bottom) / 2 - 12, 8, 24, 3);
154 ctx.fill();
155 }
156 }
157 if (playhead !== null) {
158 ctx.strokeStyle = ink;
159 ctx.lineWidth = 2;
160 ctx.setLineDash([3, 3]);
161 ctx.beginPath();
162 ctx.moveTo(s.x(playhead), s.top);
163 ctx.lineTo(s.x(playhead), s.bottom);
164 ctx.stroke();
165 ctx.setLineDash([]);
166 }
167 };
168 const shadeSeg = (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
169 if (!seg) return;
170 ctx.fillStyle = th.seg;
171 ctx.fillRect(s.x(seg.start), s.top, s.x(seg.end) - s.x(seg.start), s.bottom - s.top);
172 };
174 // ---------- level in the analysis band ----------
175 const levelRange = useMemo<[number, number]>(() => {
176 if (!levels) return [-100, 0];
177 const dbs = Array.from(levels.power, (p) => db10(p)).sort((a, b) => a - b);
178 const lo = dbs[Math.floor(dbs.length * 0.01)] ?? -100;
179 return [Math.max(-140, Math.floor((lo - 6) / 10) * 10), 0];
180 }, [levels]);
182 const drawLevel = useCallback(
183 (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
184 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 }
201 if (levels) {
202 const { frameSec, power } = levels;
203 const i0 = Math.max(0, Math.floor(view[0] / frameSec) - 1);
204 const i1 = Math.min(power.length, Math.ceil(view[1] / frameSec) + 1);
205 const step = Math.max(1, Math.floor((i1 - i0) / ((s.right - s.left) * 2)));
206 const xs: number[] = [];
207 const ys: number[] = [];
208 for (let i = i0; i < i1; i += step) {
209 let m = 0;
210 for (let j = i; j < Math.min(i + step, i1); j++) m = Math.max(m, power[j]);
211 xs.push((i + step / 2) * frameSec);
212 ys.push(db10(m));
213 }
214 drawLine(ctx, s, xs, ys, mainColor(th), 1.5);
215 }
216 drawSelection(ctx, s, th, false);
217 },
218 // eslint-disable-next-line react-hooks/exhaustive-deps
219 [levels, view, seg, playhead, detection],
220 );
222 // ---------- waveform (raw or band-passed) ----------
223 const [filtered, setFilteredState] = useState(() => {
224 try {
225 return localStorage.getItem("rsa-filter-wave") !== "0"; // filtered unless turned off
226 } catch {
227 return true;
228 }
229 });
230 const setFiltered = (v: boolean) => {
231 setFilteredState(v);
232 try {
233 localStorage.setItem("rsa-filter-wave", v ? "1" : "0");
234 } catch {
235 /* ignore */
236 }
237 };
238 const wave = filtered ? xf : x;
240 const waveMax = useMemo(() => {
241 if (!wave) return 1;
242 let m = 0;
243 for (let i = 0; i < wave.length; i++) m = Math.max(m, Math.abs(wave[i]));
244 return Math.max(m * 1.05, 1e-6);
245 }, [wave]);
247 const drawWave = useCallback(
248 (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
249 shadeSeg(ctx, s, th);
250 if (wave) {
251 const color = mainColor(th);
252 const a = Math.max(0, Math.floor(view[0] * fs));
253 const b = Math.min(wave.length, Math.ceil(view[1] * fs));
254 const px = s.right - s.left;
255 const perPx = (b - a) / px;
256 if (perPx < 2) {
257 const xs: number[] = [];
258 const ys: number[] = [];
259 for (let i = Math.max(0, a - 1); i < Math.min(wave.length, b + 1); i++) {
260 xs.push(i / fs);
261 ys.push(wave[i]);
262 }
263 drawLine(ctx, s, xs, ys, color, 1.5);
264 if (perPx < 0.15) {
265 ctx.fillStyle = color;
266 for (let i = 0; i < xs.length; i++) ctx.fillRect(s.x(xs[i]) - 1.5, s.y(ys[i]) - 1.5, 3, 3);
267 }
268 } else {
269 ctx.fillStyle = color;
270 for (let c = 0; c < px; c++) {
271 const i0 = a + Math.floor(c * perPx);
272 const i1 = Math.min(b, a + Math.floor((c + 1) * perPx));
273 let lo = Infinity;
274 let hi = -Infinity;
275 for (let i = i0; i < i1; i++) {
276 const v = wave[i];
277 if (v < lo) lo = v;
278 if (v > hi) hi = v;
279 }
280 if (lo > hi) continue;
281 const y0 = s.y(hi);
282 ctx.fillRect(s.left + c, y0, 1, Math.max(1, s.y(lo) - y0));
283 }
284 }
285 }
286 drawSelection(ctx, s, th, false);
287 },
288 // eslint-disable-next-line react-hooks/exhaustive-deps
289 [wave, view, fs, seg, playhead],
290 );
292 // ---------- spectrogram ----------
293 const drawSpec = useCallback(
294 (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
295 if (spec && specImage) {
296 const c0 = (view[0] - spec.t0) / spec.dt;
297 const c1 = (view[1] - spec.t0) / spec.dt;
298 ctx.imageSmoothingEnabled = c1 - c0 < s.right - s.left;
299 const sx0 = Math.max(0, c0);
300 const sx1 = Math.min(spec.cols, c1);
301 const dx0 = s.x(spec.t0 + sx0 * spec.dt);
302 const dx1 = s.x(spec.t0 + sx1 * spec.dt);
303 if (sx1 > sx0) ctx.drawImage(specImage, sx0, 0, sx1 - sx0, spec.bins, dx0, s.top, dx1 - dx0, s.bottom - s.top);
304 }
305 // analysis band edges
306 ctx.strokeStyle = "rgba(255,255,255,0.7)";
307 ctx.lineWidth = 1;
308 ctx.setLineDash([6, 4]);
309 ctx.beginPath();
310 for (const f of [energyLow, energyHigh]) {
311 if (f >= fs / 2) continue;
312 ctx.moveTo(s.left, s.y(f));
313 ctx.lineTo(s.right, s.y(f));
314 }
315 ctx.stroke();
316 ctx.setLineDash([]);
317 drawSelection(ctx, s, th, true);
318 },
319 // eslint-disable-next-line react-hooks/exhaustive-deps
320 [spec, specImage, view, seg, playhead, energyLow, energyHigh],
321 );
323 // ---------- spectrum ----------
324 const [smoothing, setSmoothing] = useState(1 / 12);
325 const fLo = 20;
326 const fHi = fs / 2;
327 const specLines = useMemo(() => {
328 if (!analysis) return null;
329 const tear = smoothLog(analysis.freqs, analysis.esd, fLo, fHi, smoothing);
330 const bg = analysis.noiseEsd ? smoothLog(analysis.freqs, analysis.noiseEsd, fLo, fHi, smoothing) : null;
331 return { f: tear.f, tear: tear.v.map(db10), bg: bg ? bg.v.map(db10) : null };
332 }, [analysis, smoothing, fHi]);
333 const specRange = useMemo<[number, number]>(() => {
334 if (!specLines) return [-160, -60];
335 const top = Math.max(...specLines.tear.filter(Number.isFinite));
336 return [Math.floor((top - 70) / 10) * 10, Math.ceil((top + 3) / 10) * 10];
337 }, [specLines]);
338 const drawSpectrum = useCallback(
339 (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
340 if (!specLines) return;
341 // the analysis band
342 ctx.fillStyle = th.seg;
343 const bl = s.x(settings.energyLow);
344 const bh = s.x(Math.min(settings.energyHigh, fHi));
345 ctx.fillRect(bl, s.top, bh - bl, s.bottom - s.top);
346 if (specLines.bg) drawLine(ctx, s, specLines.f, specLines.bg, th.muted, 2, [5, 4]);
347 drawLine(ctx, s, specLines.f, specLines.tear, mainColor(th), 2);
348 },
349 // eslint-disable-next-line react-hooks/exhaustive-deps
350 [specLines, settings, fHi],
351 );
352 const specHover = (p: PointerInfo) => {
353 if (!specLines) return null;
354 let best = 0;
355 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;
356 const lines = [fmtHz(specLines.f[best]), `tear: ${specLines.tear[best].toFixed(1)} dB`];
357 if (specLines.bg) lines.push(`background: ${specLines.bg[best].toFixed(1)} dB`);
358 return { lines, x: specLines.f[best], y: specLines.tear[best] };
359 };
361 const a = analysis;
362 const warnings: string[] = [];
363 if (!seg) warnings.push("No tear was found automatically. Drag across the plots below to mark it.");
364 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.`);
365 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.");
366 else if (a && a.snrDb < 10)
367 warnings.push(`In the analysis 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.`);
368 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.");
370 const th = readTheme(document.documentElement);
372 return (
373 <>
374 {warnings.map((w) => (
375 <div key={w} className="warn">
376 ⚠ {w}
377 </div>
378 ))}
380 <section className="card">
381 <div className="plot-head">
382 <div>
383 <h3>Tear range</h3>
384 <p className="caption">
385 Drag across any of the three plots to mark where the tear is; drag a dark edge to adjust it. Everything else on this page uses only this range.
386 </p>
387 </div>
388 <div className="toolbar">
389 <button className="primary" disabled={!x || !seg} onClick={() => x && seg && play(meta.id, x, fs, seg.start, seg.end)}>
390 ▶ Play tear
391 </button>
392 <button disabled={!x} onClick={() => x && play(meta.id, x, fs, 0, dur)}>
393 ▶ Play whole recording
394 </button>
395 <button disabled={playhead === null} onClick={stopPlay}>
396 ■ Stop
397 </button>
398 </div>
399 </div>
400 <div className="plot-head">
401 <div className="toolbar">
402 <button onClick={() => zoom(0.5)}>+ Zoom in</button>
403 <button onClick={() => zoom(2)}>− Zoom out</button>
404 <button disabled={!seg} onClick={fitTear}>
405 Fit tear
406 </button>
407 <button onClick={() => setView([0, dur])}>Whole recording</button>
408 <span className="muted small">
409 Showing {fmtSec(view[0])}–{fmtSec(view[1])}. Pinch to zoom, two-finger swipe sideways to move along.
410 </span>
411 </div>
412 </div>
413 <CanvasPlot
414 height={130}
415 xRange={view}
416 yRange={levelRange}
417 xLabel="time (s)"
418 yLabel={`level ${bandLabel}`}
419 hideXTicks
420 draw={drawLevel}
421 hover={(p) => {
422 const lines = [`${p.xv.toFixed(3)} s`];
423 if (levels) {
424 const i = Math.floor(p.xv / levels.frameSec);
425 if (i >= 0 && i < levels.power.length) lines.push(`${db10(levels.power[i]).toFixed(1)} dBFS in ${bandLabel}`);
426 }
427 return { lines };
428 }}
429 ariaLabel={`Sound level in ${bandLabel} over time, with the tear range`}
430 {...timeHandlers}
431 />
432 <CanvasPlot
433 height={150}
434 xRange={view}
435 yRange={[-waveMax, waveMax]}
436 xLabel="time (s)"
437 yLabel={filtered ? `waveform ${bandLabel}` : "waveform"}
438 hideXTicks
439 draw={drawWave}
440 hover={(p) => ({ lines: [`${p.xv.toFixed(4)} s`] })}
441 ariaLabel="Waveform, with the tear range"
442 {...timeHandlers}
443 />
444 <CanvasPlot
445 height={220}
446 xRange={view}
447 yRange={[0, fs / 2]}
448 xLabel="time (s)"
449 yLabel="frequency (Hz)"
450 draw={drawSpec}
451 hover={(p) => ({ lines: [`${p.xv.toFixed(3)} s`, fmtHz(p.yv)] })}
452 ariaLabel="Spectrogram, with the tear range"
453 {...timeHandlers}
454 />
455 <div className="range-row">
456 <label className="toolbar">
457 <input type="checkbox" checked={filtered} onChange={(e) => setFiltered(e.target.checked)} /> Show the waveform filtered to the analysis band ({bandLabel})
458 </label>
459 <span className="muted small">Spectrogram: brighter is louder; dashed lines mark the analysis band.</span>
460 </div>
461 <RangeInputs seg={seg} dur={dur} onCommit={commitSeg} />
462 <div className="range-row">
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>
468 <button
469 disabled={!detection}
470 onClick={() => {
471 if (!detection) return;
472 setSeg(detection.segment);
473 onUpdate({ ...meta, segment: detection.segment, segmentManual: false, detectBand: energyBand(settings), detectVersion: DETECT_VERSION });
474 }}
475 >
476 Find tear automatically
477 </button>
478 </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 )}
501 </section>
503 <section className="card">
504 <h3>Results</h3>
505 <Stats a={a} settings={settings} bandLabel={bandLabel} />
506 </section>
508 <section className="card">
509 <div className="plot-head">
510 <div>
511 <h3>Frequency makeup of the tear</h3>
512 <p className="caption">How the tear's sound energy is spread over frequency, compared with the background noise alone.</p>
513 </div>
514 <label className="toolbar">
515 smoothing
516 <select value={smoothing} onChange={(e) => setSmoothing(+e.target.value)}>
517 {SMOOTHING.map(([n, v]) => (
518 <option key={n} value={v}>
519 {n}
520 </option>
521 ))}
522 </select>
523 </label>
524 </div>
525 <CanvasPlot
526 height={300}
527 xRange={[fLo, fHi]}
528 xLog
529 yRange={specRange}
530 xLabel="frequency (Hz)"
531 yLabel="energy density (dB re FS²·s/Hz)"
532 draw={drawSpectrum}
533 hover={specHover}
534 ariaLabel="Energy spectral density of the tear"
535 />
536 <div className="legend">
537 <span>
538 <i className="swatch" style={{ background: th.series[0] }} /> tear
539 </span>
540 <span>
541 <i className="swatch dashed" /> background alone, over the same duration
542 </span>
543 <span>
544 <i className="swatch shade" /> analysis band ({bandLabel})
545 </span>
546 </div>
547 </section>
548 </>
549 );
550}
552function RangeInputs({ seg, dur, onCommit }: { seg: Segment | null; dur: number; onCommit: (s: Segment) => void }) {
553 const [a, setA] = useState("");
554 const [b, setB] = useState("");
555 useEffect(() => {
556 setA(seg ? seg.start.toFixed(3) : "");
557 setB(seg ? seg.end.toFixed(3) : "");
558 }, [seg]);
559 const commit = () => {
560 const s = Math.min(Math.max(+a, 0), dur);
561 const e = Math.min(Math.max(+b, 0), dur);
562 if (Number.isFinite(s) && Number.isFinite(e) && e - s >= 0.01 && (!seg || s !== seg.start || e !== seg.end)) onCommit({ start: s, end: e });
563 else {
564 setA(seg ? seg.start.toFixed(3) : "");
565 setB(seg ? seg.end.toFixed(3) : "");
566 }
567 };
568 const key = (e: React.KeyboardEvent<HTMLInputElement>) => e.key === "Enter" && (e.target as HTMLInputElement).blur();
569 return (
570 <div className="range-inputs">
571 <label>
572 Start
573 <input type="number" step="0.01" value={a} onChange={(e) => setA(e.target.value)} onBlur={commit} onKeyDown={key} /> s
574 </label>
575 <label>
576 End
577 <input type="number" step="0.01" value={b} onChange={(e) => setB(e.target.value)} onBlur={commit} onKeyDown={key} /> s
578 </label>
579 <span>
580 Duration <b>{seg ? fmtSec(seg.end - seg.start) : "–"}</b>
581 </span>
582 </div>
583 );
584}
586function fmtKHz(hz: number) {
587 return `${+(hz / 1000).toFixed(2)}`;
588}
590function Stats({ a, settings, bandLabel }: { a: Analysis | null; settings: AnalysisSettings; bandLabel: string }) {
591 if (!a) return <p className="muted">No tear range.</p>;
592 const items: [string, string, string?][] = [
593 ["Tear duration", fmtSec(a.duration)],
594 ["Speed", `${a.speedInPerSec.toFixed(2)} in/s`, `${settings.sheetLengthIn} in ÷ duration`],
595 ["Sound energy", Number.isFinite(db10(a.energy)) && a.energy > 0 ? `${db10(a.energy).toFixed(1)} dB` : "–", `${bandLabel}, background removed (relative units)`],
596 ["Mean power", a.energy > 0 ? `${db10(a.energy / a.duration).toFixed(1)} dBFS` : "–", `${bandLabel}, energy ÷ duration`],
597 ["Peak", `${a.peakDbfs.toFixed(1)} dBFS`, a.nearClip ? `${a.nearClip} samples near clipping` : "no clipping"],
598 [
599 "Above background",
600 Number.isFinite(a.snrDb) ? `${a.snrDb.toFixed(1)} dB` : "–",
601 a.backgroundDbfs !== null ? `${bandLabel}; background ${a.backgroundDbfs.toFixed(1)} dBFS` : "no background estimate",
602 ],
603 ];
604 return (
605 <div className="stats">
606 {items.map(([k, v, sub]) => (
607 <div key={k} className="stat">
608 <div className="stat-k">{k}</div>
609 <div className="stat-v">{v}</div>
610 {sub && <div className="stat-sub">{sub}</div>}
611 </div>
612 ))}
613 </div>
614 );
615}
617function spectrogramImage(spec: ReturnType<typeof spectrogram>): HTMLCanvasElement {
618 const c = document.createElement("canvas");
619 c.width = spec.cols;
620 c.height = spec.bins;
621 const ctx = c.getContext("2d")!;
622 const img = ctx.createImageData(spec.cols, spec.bins);
623 const top = spec.maxDb;
624 const range = 90;
625 for (let col = 0; col < spec.cols; col++) {
626 for (let k = 0; k < spec.bins; k++) {
627 const v = (spec.db[col * spec.bins + k] - (top - range)) / range;
628 const [r, g, b] = magma(Math.min(1, Math.max(0, v)));
629 const o = ((spec.bins - 1 - k) * spec.cols + col) * 4;
630 img.data[o] = r;
631 img.data[o + 1] = g;
632 img.data[o + 2] = b;
633 img.data[o + 3] = 255;
634 }
635 }
636 ctx.putImageData(img, 0, 0);
637 return c;
638}