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