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