/ magland / rip-sound-analyzer
Sign in
magland / rip-sound-analyzer
rip-sound-analyzer / src / components / RecordingView.tsx
550 lines · 20.9 KBBlameHistoryRaw
1import { useCallback, useEffect, useMemo, useRef, useState } from "react";
2import { CanvasPlot, drawLine, readTheme, type PointerInfo, type Scales, type Theme } from "./CanvasPlot.tsx";
3import { detectSegment, frameLevels, smoothLog, spectrogram, type Analysis, type AnalysisSettings, type Segment } from "../analysis/analyze.ts";
4import type { RecordingMeta } from "../storage/db.ts";
5import { encodeWavFloat32 } from "../audio/wav.ts";
6import { colorFor, db10, download, fmtDate, fmtHz, fmtSec, getAnalysis, getAudio, groupStyle, PRESET_LABELS, safeName } from "../model.ts";
7import { magma } from "../colormap.ts";
9interface Props {
10 meta: RecordingMeta;
11 all: RecordingMeta[];
12 settings: AnalysisSettings;
13 onUpdate: (m: RecordingMeta) => void;
14 onDelete: (m: RecordingMeta) => void;
17const SMOOTHING: [string, number][] = [
18 ["none", 0],
19 ["1/24 octave", 1 / 24],
20 ["1/12 octave", 1 / 12],
21 ["1/6 octave", 1 / 6],
22 ["1/3 octave", 1 / 3],
23];
25let playCtx: AudioContext | null = null;
26let playing: AudioBufferSourceNode | null = null;
28function play(x: Float32Array, fs: number, a: number, b: number) {
29 stopPlay();
30 playCtx ??= new AudioContext();
31 const s = Math.max(0, Math.floor(a * fs));
32 const e = Math.min(x.length, Math.ceil(b * fs));
33 const buf = playCtx.createBuffer(1, Math.max(1, e - s), fs);
34 buf.copyToChannel(x.subarray(s, e) as Float32Array<ArrayBuffer>, 0);
35 const src = playCtx.createBufferSource();
36 src.buffer = buf;
37 src.connect(playCtx.destination);
38 src.start();
39 playing = src;
42function stopPlay() {
43 try {
44 playing?.stop();
45 } catch {
46 /* already stopped */
47 }
48 playing = null;
51export function RecordingView({ meta, all, settings, onUpdate, onDelete }: Props) {
52 const [x, setX] = useState<Float32Array | null>(null);
53 const [analysis, setAnalysis] = useState<Analysis | null>(null);
54 const dur = meta.length / meta.sampleRate;
55 const [view, setView] = useState<[number, number]>([0, dur]);
56 const [seg, setSeg] = useState<Segment | null>(meta.segment);
57 const [smoothing, setSmoothing] = useState(1 / 12);
58 const [notes, setNotes] = useState(meta.notes);
59 const [label, setLabel] = useState(meta.label);
61 useEffect(() => {
62 let live = true;
63 setX(null);
64 setView([0, meta.length / meta.sampleRate]);
65 setNotes(meta.notes);
66 setLabel(meta.label);
67 getAudio(meta.id).then((a) => live && setX(a));
68 return () => {
69 live = false;
70 stopPlay();
71 };
72 }, [meta.id, meta.length, meta.sampleRate, meta.notes, meta.label]);
74 useEffect(() => setSeg(meta.segment), [meta.segment]);
76 useEffect(() => {
77 let live = true;
78 setAnalysis(null);
79 getAnalysis(meta, settings).then((a) => live && setAnalysis(a));
80 return () => {
81 live = false;
82 };
83 }, [meta, settings]);
85 const fs = meta.sampleRate;
86 const levels = useMemo(() => (x ? frameLevels(x, fs, 0.005) : null), [x, fs]);
87 const spec = useMemo(() => (x ? spectrogram(x, fs) : null), [x, fs]);
88 const specImage = useMemo(() => (spec ? spectrogramImage(spec) : null), [spec]);
90 const commitSeg = (s: Segment | null) => {
91 onUpdate({ ...meta, segment: s, segmentManual: true });
92 };
94 // ---------- shared time-axis interaction ----------
95 const drag = useRef<{ kind: "start" | "end" | "pan"; px0: number; view0: [number, number] } | null>(null);
96 const edgeAt = (p: PointerInfo): "start" | "end" | null => {
97 if (!seg) return null;
98 if (Math.abs(p.px - p.scales.x(seg.start)) < 7) return "start";
99 if (Math.abs(p.px - p.scales.x(seg.end)) < 7) return "end";
100 return null;
101 };
102 const clampView = (a: number, b: number): [number, number] => {
103 const w = Math.min(dur, Math.max(b - a, 0.002));
104 let s = Math.max(0, a);
105 if (s + w > dur) s = dur - w;
106 return [s, s + w];
107 };
108 const timeHandlers = {
109 onWheel: (p: PointerInfo, ev: WheelEvent) => {
110 if (Math.abs(ev.deltaX) > Math.abs(ev.deltaY)) {
111 const shift = (ev.deltaX / (p.scales.right - p.scales.left)) * (view[1] - view[0]);
112 setView(clampView(view[0] + shift, view[1] + shift));
113 return;
114 }
115 const f = Math.exp(ev.deltaY * 0.0025);
116 const t = Math.min(Math.max(p.xv, view[0]), view[1]);
117 setView(clampView(t - (t - view[0]) * f, t + (view[1] - t) * f));
118 },
119 onPointer: (type: "down" | "move" | "up", p: PointerInfo) => {
120 if (type === "down") {
121 drag.current = { kind: edgeAt(p) ?? "pan", px0: p.px, view0: view };
122 } else if (type === "move" && drag.current) {
123 const d = drag.current;
124 if (d.kind === "pan") {
125 const dt = ((p.px - d.px0) / (p.scales.right - p.scales.left)) * (d.view0[1] - d.view0[0]);
126 setView(clampView(d.view0[0] - dt, d.view0[1] - dt));
127 } else if (seg) {
128 const t = Math.min(Math.max(p.xv, 0), dur);
129 setSeg(d.kind === "start" ? { start: Math.min(t, seg.end - 0.005), end: seg.end } : { start: seg.start, end: Math.max(t, seg.start + 0.005) });
130 }
131 } else if (type === "up") {
132 if (drag.current && drag.current.kind !== "pan" && seg) commitSeg(seg);
133 drag.current = null;
134 }
135 },
136 onDoubleClick: () => setView([0, dur]),
137 cursor: (p: PointerInfo) => (edgeAt(p) ? "ew-resize" : "grab"),
138 };
140 const drawSeg = useCallback(
141 (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
142 if (!seg) return;
143 const a = s.x(seg.start);
144 const b = s.x(seg.end);
145 ctx.fillStyle = th.seg;
146 ctx.fillRect(a, s.top, b - a, s.bottom - s.top);
147 ctx.strokeStyle = th.ink2;
148 ctx.lineWidth = 1.5;
149 ctx.beginPath();
150 ctx.moveTo(a, s.top);
151 ctx.lineTo(a, s.bottom);
152 ctx.moveTo(b, s.top);
153 ctx.lineTo(b, s.bottom);
154 ctx.stroke();
155 },
156 [seg],
157 );
159 const { slot } = groupStyle(meta.label, all);
160 const mainColor = (th: Theme) => colorFor(slot, th.series, th.ink2);
162 const levelRange = useMemo<[number, number]>(() => {
163 if (!levels) return [-100, 0];
164 const dbs = Array.from(levels.power, (p) => db10(p)).sort((a, b) => a - b);
165 const lo = dbs[Math.floor(dbs.length * 0.01)] ?? -100;
166 return [Math.max(-140, Math.floor((lo - 6) / 10) * 10), 0];
167 }, [levels]);
169 const drawLevel = useCallback(
170 (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
171 drawSeg(ctx, s, th);
172 if (!levels) return;
173 const { frameSec, power } = levels;
174 const i0 = Math.max(0, Math.floor(view[0] / frameSec) - 1);
175 const i1 = Math.min(power.length, Math.ceil(view[1] / frameSec) + 1);
176 const step = Math.max(1, Math.floor((i1 - i0) / ((s.right - s.left) * 2)));
177 const xs: number[] = [];
178 const ys: number[] = [];
179 for (let i = i0; i < i1; i += step) {
180 let m = 0;
181 for (let j = i; j < Math.min(i + step, i1); j++) m = Math.max(m, power[j]);
182 xs.push((i + step / 2) * frameSec);
183 ys.push(db10(m));
184 }
185 drawLine(ctx, s, xs, ys, mainColor(th), 1.5);
186 },
187 // eslint-disable-next-line react-hooks/exhaustive-deps
188 [levels, view, drawSeg, slot],
189 );
191 const waveMax = useMemo(() => {
192 if (!x) return 1;
193 let m = 0;
194 for (let i = 0; i < x.length; i++) m = Math.max(m, Math.abs(x[i]));
195 return Math.max(m * 1.05, 1e-4);
196 }, [x]);
198 const drawWave = useCallback(
199 (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
200 drawSeg(ctx, s, th);
201 if (!x) return;
202 const color = mainColor(th);
203 const a = Math.max(0, Math.floor(view[0] * fs));
204 const b = Math.min(x.length, Math.ceil(view[1] * fs));
205 const px = s.right - s.left;
206 const perPx = (b - a) / px;
207 if (perPx < 2) {
208 const xs: number[] = [];
209 const ys: number[] = [];
210 for (let i = Math.max(0, a - 1); i < Math.min(x.length, b + 1); i++) {
211 xs.push(i / fs);
212 ys.push(x[i]);
213 }
214 drawLine(ctx, s, xs, ys, color, 1.5);
215 if (perPx < 0.15) {
216 ctx.fillStyle = color;
217 for (let i = 0; i < xs.length; i++) ctx.fillRect(s.x(xs[i]) - 1.5, s.y(ys[i]) - 1.5, 3, 3);
218 }
219 return;
220 }
221 ctx.fillStyle = color;
222 for (let c = 0; c < px; c++) {
223 const i0 = a + Math.floor(c * perPx);
224 const i1 = Math.min(b, a + Math.floor((c + 1) * perPx));
225 let lo = Infinity;
226 let hi = -Infinity;
227 for (let i = i0; i < i1; i++) {
228 const v = x[i];
229 if (v < lo) lo = v;
230 if (v > hi) hi = v;
231 }
232 if (lo > hi) continue;
233 const y0 = s.y(hi);
234 const y1 = s.y(lo);
235 ctx.fillRect(s.left + c, y0, 1, Math.max(1, y1 - y0));
236 }
237 },
238 // eslint-disable-next-line react-hooks/exhaustive-deps
239 [x, view, fs, drawSeg, slot],
240 );
242 const drawSpec = useCallback(
243 (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
244 if (spec && specImage) {
245 const c0 = (view[0] - spec.t0) / spec.dt;
246 const c1 = (view[1] - spec.t0) / spec.dt;
247 ctx.imageSmoothingEnabled = c1 - c0 < s.right - s.left;
248 const sx0 = Math.max(0, c0);
249 const sx1 = Math.min(spec.cols, c1);
250 const dx0 = s.x(spec.t0 + sx0 * spec.dt);
251 const dx1 = s.x(spec.t0 + sx1 * spec.dt);
252 if (sx1 > sx0) ctx.drawImage(specImage, sx0, 0, sx1 - sx0, spec.bins, dx0, s.top, dx1 - dx0, s.bottom - s.top);
253 }
254 if (seg) {
255 ctx.strokeStyle = th.surface;
256 ctx.lineWidth = 1.5;
257 ctx.setLineDash([4, 3]);
258 ctx.beginPath();
259 for (const t of [seg.start, seg.end]) {
260 ctx.moveTo(s.x(t), s.top);
261 ctx.lineTo(s.x(t), s.bottom);
262 }
263 ctx.stroke();
264 ctx.setLineDash([]);
265 }
266 },
267 [spec, specImage, view, seg],
268 );
270 // ---------- spectrum ----------
271 const fLo = 20;
272 const fHi = fs / 2;
273 const specLines = useMemo(() => {
274 if (!analysis) return null;
275 const tear = smoothLog(analysis.freqs, analysis.esd, fLo, fHi, smoothing);
276 const bg = analysis.noiseEsd ? smoothLog(analysis.freqs, analysis.noiseEsd, fLo, fHi, smoothing) : null;
277 return { f: tear.f, tear: tear.v.map(db10), bg: bg ? bg.v.map(db10) : null };
278 }, [analysis, smoothing, fHi]);
279 const specRange = useMemo<[number, number]>(() => {
280 if (!specLines) return [-160, -60];
281 const top = Math.max(...specLines.tear.filter(Number.isFinite));
282 return [Math.floor((top - 80) / 10) * 10, Math.ceil((top + 3) / 10) * 10];
283 }, [specLines]);
285 const drawSpectrum = useCallback(
286 (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
287 if (!specLines) return;
288 // grey out what lies outside the analysis band
289 ctx.fillStyle = th.seg;
290 const bl = s.x(settings.bandLow);
291 const bh = s.x(Math.min(settings.bandHigh, fHi));
292 ctx.fillRect(s.left, s.top, bl - s.left, s.bottom - s.top);
293 ctx.fillRect(bh, s.top, s.right - bh, s.bottom - s.top);
294 if (specLines.bg) drawLine(ctx, s, specLines.f, specLines.bg, th.muted, 2, [5, 4]);
295 drawLine(ctx, s, specLines.f, specLines.tear, mainColor(th), 2);
296 },
297 // eslint-disable-next-line react-hooks/exhaustive-deps
298 [specLines, settings, fHi, slot],
299 );
301 const specHover = (p: PointerInfo) => {
302 if (!specLines) return null;
303 let best = 0;
304 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;
305 const lines = [fmtHz(specLines.f[best]), `tear: ${specLines.tear[best].toFixed(1)} dB`];
306 if (specLines.bg) lines.push(`background: ${specLines.bg[best].toFixed(1)} dB`);
307 return { lines, x: specLines.f[best], y: specLines.tear[best] };
308 };
310 const timeHover = (p: PointerInfo) => {
311 const lines = [`${p.xv.toFixed(p.xv < 10 ? 3 : 2)} s`];
312 if (levels) {
313 const i = Math.floor(p.xv / levels.frameSec);
314 if (i >= 0 && i < levels.power.length) lines.push(`level: ${db10(levels.power[i]).toFixed(1)} dBFS (5 ms RMS)`);
315 }
316 return { lines };
317 };
319 // ---------- actions ----------
320 const saveNotes = () => notes !== meta.notes && onUpdate({ ...meta, notes });
321 const saveLabel = (l: string) => {
322 setLabel(l);
323 if (l.trim() && l !== meta.label) onUpdate({ ...meta, label: l.trim() });
324 };
325 const autoDetect = () => {
326 if (!x) return;
327 const s = detectSegment(x, fs);
328 onUpdate({ ...meta, segment: s, segmentManual: false });
329 };
330 const exportWav = () => {
331 if (!x) return;
332 const d = new Date(meta.createdAt).toISOString().replace(/[:]/g, "-").slice(0, 19);
333 download(encodeWavFloat32(x, fs), `${d}_${safeName(meta.label)}_${meta.id.slice(0, 6)}.wav`);
334 };
336 const a = analysis;
337 const warnings: string[] = [];
338 if (!seg) warnings.push("No tear was found automatically. Zoom so the tear fills the view and press “Use visible range as tear”.");
339 if (a && a.nearClip > 0) warnings.push(`${a.nearClip} samples in the tear are at or near full scale (clipping). The energy is underestimated and the spectrum is distorted.`);
340 if (a && !a.noiseEsd) warnings.push("Not enough quiet audio before or after the tear to estimate the background, so nothing was subtracted.");
341 else if (a && a.snrDb < 10) warnings.push(`The tear is only ${a.snrDb.toFixed(1)} dB above the background in the analysis band; the energy estimate is sensitive to the background subtraction.`);
342 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.");
344 return (
345 <div className="recview">
346 <section className="card">
347 <div className="rv-head">
348 <div className="rv-title">
349 <input
350 className="label-edit"
351 list="known-labels"
352 value={label}
353 onChange={(e) => setLabel(e.target.value)}
354 onBlur={(e) => saveLabel(e.target.value)}
355 onKeyDown={(e) => e.key === "Enter" && (e.target as HTMLInputElement).blur()}
356 aria-label="Speed label"
357 />
358 <select value="" onChange={(e) => e.target.value && saveLabel(e.target.value)} aria-label="Choose a preset label">
359 <option value="">preset…</option>
360 {PRESET_LABELS.map((l) => (
361 <option key={l}>{l}</option>
362 ))}
363 </select>
364 <span className={`badge ${meta.source}`}>{meta.source === "mic" ? "microphone" : meta.source}</span>
365 <span className="muted">
366 {fmtDate(meta.createdAt)} · {fmtSec(dur)} · {fs} Hz{meta.fileName ? ` · ${meta.fileName}` : ""}
367 </span>
368 </div>
369 <div className="rv-actions">
370 <button disabled={!x || !seg} onClick={() => x && seg && play(x, fs, seg.start, seg.end)}>
371 ▶ Play tear
372 </button>
373 <button disabled={!x} onClick={() => x && play(x, fs, 0, dur)}>
374 ▶ Play all
375 </button>
376 <button onClick={stopPlay}>■</button>
377 <button disabled={!x} onClick={exportWav}>
378 Download WAV
379 </button>
380 <button className="danger" onClick={() => onDelete(meta)}>
381 Delete
382 </button>
383 </div>
384 </div>
385 <textarea
386 className="notes"
387 placeholder="Notes (paper type, how it was torn, anything unusual)"
388 value={notes}
389 onChange={(e) => setNotes(e.target.value)}
390 onBlur={saveNotes}
391 rows={1}
392 />
393 {warnings.map((w) => (
394 <div key={w} className="warn">
395 ⚠ {w}
396 </div>
397 ))}
398 <Stats a={a} settings={settings} manual={meta.segmentManual} />
399 </section>
401 <section className="card">
402 <div className="plot-head">
403 <h3>Over time</h3>
404 <div className="toolbar">
405 <span className="hint">Scroll to zoom, drag to pan, drag the edges of the shaded tear to adjust it, double-click to reset.</span>
406 <button disabled={!seg} onClick={() => seg && setView(clampView(seg.start - 0.1 * (seg.end - seg.start), seg.end + 0.1 * (seg.end - seg.start)))}>
407 Zoom to tear
408 </button>
409 <button onClick={() => setView([0, dur])}>Full</button>
410 <button onClick={() => commitSeg({ start: view[0], end: view[1] })}>Use visible range as tear</button>
411 <button disabled={!x} onClick={autoDetect} title="Re-run automatic tear detection">
412 Auto-detect tear
413 </button>
414 </div>
415 </div>
416 <CanvasPlot
417 height={150}
418 xRange={view}
419 yRange={levelRange}
420 xLabel="time (s)"
421 yLabel="level (dBFS)"
422 hideXTicks
423 draw={drawLevel}
424 hover={timeHover}
425 ariaLabel="Sound level over time"
426 {...timeHandlers}
427 />
428 <CanvasPlot
429 height={150}
430 xRange={view}
431 yRange={[-waveMax, waveMax]}
432 xLabel="time (s)"
433 yLabel="waveform"
434 hideXTicks
435 draw={drawWave}
436 hover={(p) => ({ lines: [`${p.xv.toFixed(4)} s`] })}
437 ariaLabel="Waveform"
438 {...timeHandlers}
439 />
440 <CanvasPlot
441 height={220}
442 xRange={view}
443 yRange={[0, fs / 2]}
444 xLabel="time (s)"
445 yLabel="frequency (Hz)"
446 draw={drawSpec}
447 hover={(p) => ({ lines: [`${p.xv.toFixed(3)} s`, fmtHz(p.yv)] })}
448 ariaLabel="Spectrogram"
449 {...timeHandlers}
450 />
451 <p className="caption">
452 Level is the RMS over 5 ms windows. Spectrogram: 1024-point Hann windows, colour spans the top 90 dB of this recording.
453 </p>
454 </section>
456 <section className="card">
457 <div className="plot-head">
458 <h3>Frequency makeup of the tear</h3>
459 <label className="toolbar">
460 smoothing
461 <select value={smoothing} onChange={(e) => setSmoothing(+e.target.value)}>
462 {SMOOTHING.map(([n, v]) => (
463 <option key={n} value={v}>
464 {n}
465 </option>
466 ))}
467 </select>
468 </label>
469 </div>
470 <CanvasPlot
471 height={300}
472 xRange={[fLo, fHi]}
473 xLog
474 yRange={specRange}
475 xLabel="frequency (Hz)"
476 yLabel="energy density (dB re FS²·s/Hz)"
477 draw={drawSpectrum}
478 hover={specHover}
479 ariaLabel="Energy spectral density of the tear"
480 />
481 <div className="legend">
482 <span>
483 <i className="swatch" style={{ background: readThemeColor(slot) }} /> tear (energy spectral density)
484 </span>
485 <span>
486 <i className="swatch dashed" /> background alone over the same duration
487 </span>
488 <span>
489 <i className="swatch shade" /> outside the analysis band ({fmtHz(settings.bandLow)}–{fmtHz(settings.bandHigh)})
490 </span>
491 </div>
492 </section>
493 </div>
494 );
497function readThemeColor(slot: number | null) {
498 const th = readTheme(document.documentElement);
499 return colorFor(slot, th.series, th.ink2);
502function Stats({ a, settings, manual }: { a: Analysis | null; settings: AnalysisSettings; manual: boolean }) {
503 if (!a) return null;
504 const items: [string, string, string?][] = [
505 ["Tear duration", fmtSec(a.duration), manual ? "set by hand" : "auto-detected"],
506 ["Speed", `${a.speedInPerSec.toFixed(2)} in/s`, `${settings.sheetLengthIn} in ÷ duration`],
507 ["Sound energy", `${db10(a.energy).toFixed(1)} dB`, "re FS²·s, in band, background removed"],
508 ["Mean power", `${db10(a.energy / a.duration).toFixed(1)} dBFS`, "energy ÷ duration"],
509 ["Median frequency", fmtHz(a.medianFreq), "half the energy above, half below"],
510 ["Centroid", fmtHz(a.centroid), "energy-weighted mean frequency"],
511 ["10–90% of energy", `${fmtHz(a.f10)} – ${fmtHz(a.f90)}`],
512 ["Peak", `${a.peakDbfs.toFixed(1)} dBFS`, a.nearClip ? `${a.nearClip} samples near clipping` : "no clipping"],
513 ["Above background", Number.isFinite(a.snrDb) ? `${a.snrDb.toFixed(1)} dB` : "–", a.backgroundDbfs !== null ? `background ${a.backgroundDbfs.toFixed(1)} dBFS, from ${a.noiseSeconds.toFixed(1)} s` : "no background estimate"],
514 ];
515 return (
516 <div className="stats">
517 {items.map(([k, v, sub]) => (
518 <div key={k} className="stat">
519 <div className="stat-k">{k}</div>
520 <div className="stat-v">{v}</div>
521 {sub && <div className="stat-sub">{sub}</div>}
522 </div>
523 ))}
524 </div>
525 );
528function spectrogramImage(spec: ReturnType<typeof spectrogram>): HTMLCanvasElement {
529 const c = document.createElement("canvas");
530 c.width = spec.cols;
531 c.height = spec.bins;
532 const ctx = c.getContext("2d")!;
533 const img = ctx.createImageData(spec.cols, spec.bins);
534 const top = spec.maxDb;
535 const range = 90;
536 for (let col = 0; col < spec.cols; col++) {
537 for (let k = 0; k < spec.bins; k++) {
538 const v = (spec.db[col * spec.bins + k] - (top - range)) / range;
539 const [r, g, b] = magma(Math.min(1, Math.max(0, v)));
540 const row = spec.bins - 1 - k;
541 const o = (row * spec.cols + col) * 4;
542 img.data[o] = r;
543 img.data[o + 1] = g;
544 img.data[o + 2] = b;
545 img.data[o + 3] = 255;
546 }
547 }
548 ctx.putImageData(img, 0, 0);
549 return c;
↑↓ move↵openescclose