import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { CanvasPlot, drawLine, readTheme, type PointerInfo, type Scales, type Theme } from "./CanvasPlot.tsx"; import { bandLevels, bandpass, detectSegment, energyBand, smoothLog, spectrogram, type Analysis, type AnalysisSettings, type Segment } from "../analysis/analyze.ts"; import type { RecordingMeta } from "../storage/db.ts"; import { play, stop as stopPlay, usePlayhead } from "../audio/player.ts"; import { db10, fmtHz, fmtSec, getAnalysis, getAudio } from "../model.ts"; import { magma } from "../colormap.ts"; interface Props { meta: RecordingMeta; settings: AnalysisSettings; onUpdate: (m: RecordingMeta) => void; } const SMOOTHING: [string, number][] = [ ["none", 0], ["1/24 octave", 1 / 24], ["1/12 octave", 1 / 12], ["1/6 octave", 1 / 6], ["1/3 octave", 1 / 3], ]; export function TearView({ meta, settings, onUpdate }: Props) { const [x, setX] = useState(null); const [analysis, setAnalysis] = useState(null); const fs = meta.sampleRate; const dur = meta.length / fs; const [seg, setSeg] = useState(meta.segment); const playhead = usePlayhead(meta.id); useEffect(() => { let live = true; setX(null); getAudio(meta.id).then((a) => live && setX(a)); return () => { live = false; stopPlay(); }; }, [meta.id]); useEffect(() => setSeg(meta.segment), [meta.segment]); useEffect(() => { let live = true; getAnalysis(meta, settings).then((a) => live && setAnalysis(a)); return () => { live = false; }; }, [meta, settings]); const { energyLow, energyHigh } = settings; const bandLabel = `${fmtKHz(energyLow)}–${fmtKHz(energyHigh)} kHz`; const levels = useMemo(() => (x ? bandLevels(x, fs, { lo: energyLow, hi: energyHigh }, 0.005) : null), [x, fs, energyLow, energyHigh]); const spec = useMemo(() => (x ? spectrogram(x, fs) : null), [x, fs]); const specImage = useMemo(() => (spec ? spectrogramImage(spec) : null), [spec]); const mainColor = (th: Theme) => th.series[0]; const commitSeg = (s: Segment | null) => { setSeg(s); onUpdate({ ...meta, segment: s, segmentManual: true }); }; // ---------- shared time view (level, waveform, spectrogram) ---------- const [view, setView] = useState<[number, number]>([0, dur]); useEffect(() => setView([0, meta.length / meta.sampleRate]), [meta.id, meta.length, meta.sampleRate]); const clampView = (a: number, b: number): [number, number] => { const w = Math.min(dur, Math.max(b - a, 0.002)); let s = Math.max(0, a); if (s + w > dur) s = dur - w; return [s, s + w]; }; const zoom = (f: number, around = (view[0] + view[1]) / 2) => setView(clampView(around - (around - view[0]) * f, around + (view[1] - around) * f)); const fitTear = () => { if (!seg) return; const m = Math.max(0.05, 0.08 * (seg.end - seg.start)); setView(clampView(seg.start - m, seg.end + m)); }; // ---------- selecting the tear range (on any of the three plots) ---------- const drag = useRef<{ kind: "start" | "end" | "new"; anchor: number; px0: number; before: Segment | null } | null>(null); const edgeAt = (p: PointerInfo): "start" | "end" | null => { if (!seg) return null; const ds = Math.abs(p.px - p.scales.x(seg.start)); const de = Math.abs(p.px - p.scales.x(seg.end)); if (Math.min(ds, de) > 8) return null; return ds <= de ? "start" : "end"; }; const clampT = (t: number) => Math.min(Math.max(t, 0), dur); const timeHandlers = { onPointer: (type: "down" | "move" | "up", p: PointerInfo) => { if (type === "down") { drag.current = { kind: edgeAt(p) ?? "new", anchor: clampT(p.xv), px0: p.px, before: seg }; } else if (type === "move" && drag.current) { const d = drag.current; const t = clampT(p.xv); if (d.kind === "new") { if (Math.abs(p.px - d.px0) > 3) setSeg({ start: Math.min(d.anchor, t), end: Math.max(d.anchor, t) }); } else if (seg) { // dragging an edge past the other one swaps them const other = d.kind === "start" ? seg.end : seg.start; setSeg({ start: Math.min(t, other), end: Math.max(t, other) }); if ((d.kind === "start" && t > other) || (d.kind === "end" && t < other)) d.kind = d.kind === "start" ? "end" : "start"; } } else if (type === "up" && drag.current) { const d = drag.current; drag.current = null; if (d.kind === "new" && Math.abs(p.px - d.px0) <= 3) return; // a plain click changes nothing if (seg && seg.end - seg.start >= 0.005) commitSeg(seg); else setSeg(d.before); } }, // pinch (or ctrl + scroll) zooms, sideways two-finger scroll moves along; plain scrolling scrolls the page onWheel: (p: PointerInfo, ev: WheelEvent) => { if (ev.ctrlKey) { zoom(Math.exp(ev.deltaY * 0.01), Math.min(Math.max(p.xv, view[0]), view[1])); return true; } if (Math.abs(ev.deltaX) > Math.abs(ev.deltaY)) { const shift = (ev.deltaX / (p.scales.right - p.scales.left)) * (view[1] - view[0]); setView(clampView(view[0] + shift, view[1] + shift)); return true; } return false; }, onDoubleClick: () => setView([0, dur]), cursor: (p: PointerInfo) => (edgeAt(p) ? "ew-resize" : "crosshair"), }; // shading (or dimming, on the spectrogram), edges with grab handles, playhead const drawSelection = (ctx: CanvasRenderingContext2D, s: Scales, th: Theme, onImage: boolean) => { const ink = onImage ? "#ffffff" : th.ink; if (seg) { const a = s.x(seg.start); const b = s.x(seg.end); if (onImage) { ctx.fillStyle = "rgba(0,0,0,0.45)"; ctx.fillRect(s.left, s.top, a - s.left, s.bottom - s.top); ctx.fillRect(b, s.top, s.right - b, s.bottom - s.top); } for (const px of [a, b]) { ctx.strokeStyle = ink; ctx.lineWidth = 2; ctx.beginPath(); ctx.moveTo(px, s.top); ctx.lineTo(px, s.bottom); ctx.stroke(); ctx.fillStyle = ink; ctx.beginPath(); ctx.roundRect(px - 4, (s.top + s.bottom) / 2 - 12, 8, 24, 3); ctx.fill(); } } if (playhead !== null) { ctx.strokeStyle = ink; ctx.lineWidth = 2; ctx.setLineDash([3, 3]); ctx.beginPath(); ctx.moveTo(s.x(playhead), s.top); ctx.lineTo(s.x(playhead), s.bottom); ctx.stroke(); ctx.setLineDash([]); } }; const shadeSeg = (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => { if (!seg) return; ctx.fillStyle = th.seg; ctx.fillRect(s.x(seg.start), s.top, s.x(seg.end) - s.x(seg.start), s.bottom - s.top); }; // ---------- level in the analysis band ---------- const levelRange = useMemo<[number, number]>(() => { if (!levels) return [-100, 0]; const dbs = Array.from(levels.power, (p) => db10(p)).sort((a, b) => a - b); const lo = dbs[Math.floor(dbs.length * 0.01)] ?? -100; return [Math.max(-140, Math.floor((lo - 6) / 10) * 10), 0]; }, [levels]); const drawLevel = useCallback( (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => { shadeSeg(ctx, s, th); if (levels) { const { frameSec, power } = levels; const i0 = Math.max(0, Math.floor(view[0] / frameSec) - 1); const i1 = Math.min(power.length, Math.ceil(view[1] / frameSec) + 1); const step = Math.max(1, Math.floor((i1 - i0) / ((s.right - s.left) * 2))); const xs: number[] = []; const ys: number[] = []; for (let i = i0; i < i1; i += step) { let m = 0; for (let j = i; j < Math.min(i + step, i1); j++) m = Math.max(m, power[j]); xs.push((i + step / 2) * frameSec); ys.push(db10(m)); } drawLine(ctx, s, xs, ys, mainColor(th), 1.5); } drawSelection(ctx, s, th, false); }, // eslint-disable-next-line react-hooks/exhaustive-deps [levels, view, seg, playhead], ); // ---------- waveform (raw or band-passed) ---------- const [filtered, setFilteredState] = useState(() => { try { return localStorage.getItem("rsa-filter-wave") !== "0"; // filtered unless turned off } catch { return true; } }); const setFiltered = (v: boolean) => { setFilteredState(v); try { localStorage.setItem("rsa-filter-wave", v ? "1" : "0"); } catch { /* ignore */ } }; const xf = useMemo(() => (x && filtered ? bandpass(x, fs, { lo: energyLow, hi: energyHigh }) : null), [x, fs, filtered, energyLow, energyHigh]); const wave = filtered ? xf : x; const waveMax = useMemo(() => { if (!wave) return 1; let m = 0; for (let i = 0; i < wave.length; i++) m = Math.max(m, Math.abs(wave[i])); return Math.max(m * 1.05, 1e-6); }, [wave]); const drawWave = useCallback( (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => { shadeSeg(ctx, s, th); if (wave) { const color = mainColor(th); const a = Math.max(0, Math.floor(view[0] * fs)); const b = Math.min(wave.length, Math.ceil(view[1] * fs)); const px = s.right - s.left; const perPx = (b - a) / px; if (perPx < 2) { const xs: number[] = []; const ys: number[] = []; for (let i = Math.max(0, a - 1); i < Math.min(wave.length, b + 1); i++) { xs.push(i / fs); ys.push(wave[i]); } drawLine(ctx, s, xs, ys, color, 1.5); if (perPx < 0.15) { ctx.fillStyle = color; for (let i = 0; i < xs.length; i++) ctx.fillRect(s.x(xs[i]) - 1.5, s.y(ys[i]) - 1.5, 3, 3); } } else { ctx.fillStyle = color; for (let c = 0; c < px; c++) { const i0 = a + Math.floor(c * perPx); const i1 = Math.min(b, a + Math.floor((c + 1) * perPx)); let lo = Infinity; let hi = -Infinity; for (let i = i0; i < i1; i++) { const v = wave[i]; if (v < lo) lo = v; if (v > hi) hi = v; } if (lo > hi) continue; const y0 = s.y(hi); ctx.fillRect(s.left + c, y0, 1, Math.max(1, s.y(lo) - y0)); } } } drawSelection(ctx, s, th, false); }, // eslint-disable-next-line react-hooks/exhaustive-deps [wave, view, fs, seg, playhead], ); // ---------- spectrogram ---------- const drawSpec = useCallback( (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => { if (spec && specImage) { const c0 = (view[0] - spec.t0) / spec.dt; const c1 = (view[1] - spec.t0) / spec.dt; ctx.imageSmoothingEnabled = c1 - c0 < s.right - s.left; const sx0 = Math.max(0, c0); const sx1 = Math.min(spec.cols, c1); const dx0 = s.x(spec.t0 + sx0 * spec.dt); const dx1 = s.x(spec.t0 + sx1 * spec.dt); if (sx1 > sx0) ctx.drawImage(specImage, sx0, 0, sx1 - sx0, spec.bins, dx0, s.top, dx1 - dx0, s.bottom - s.top); } // analysis band edges ctx.strokeStyle = "rgba(255,255,255,0.7)"; ctx.lineWidth = 1; ctx.setLineDash([6, 4]); ctx.beginPath(); for (const f of [energyLow, energyHigh]) { if (f >= fs / 2) continue; ctx.moveTo(s.left, s.y(f)); ctx.lineTo(s.right, s.y(f)); } ctx.stroke(); ctx.setLineDash([]); drawSelection(ctx, s, th, true); }, // eslint-disable-next-line react-hooks/exhaustive-deps [spec, specImage, view, seg, playhead, energyLow, energyHigh], ); // ---------- spectrum ---------- const [smoothing, setSmoothing] = useState(1 / 12); const fLo = 20; const fHi = fs / 2; const specLines = useMemo(() => { if (!analysis) return null; const tear = smoothLog(analysis.freqs, analysis.esd, fLo, fHi, smoothing); const bg = analysis.noiseEsd ? smoothLog(analysis.freqs, analysis.noiseEsd, fLo, fHi, smoothing) : null; return { f: tear.f, tear: tear.v.map(db10), bg: bg ? bg.v.map(db10) : null }; }, [analysis, smoothing, fHi]); const specRange = useMemo<[number, number]>(() => { if (!specLines) return [-160, -60]; const top = Math.max(...specLines.tear.filter(Number.isFinite)); return [Math.floor((top - 70) / 10) * 10, Math.ceil((top + 3) / 10) * 10]; }, [specLines]); const drawSpectrum = useCallback( (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => { if (!specLines) return; // the analysis band ctx.fillStyle = th.seg; const bl = s.x(settings.energyLow); const bh = s.x(Math.min(settings.energyHigh, fHi)); ctx.fillRect(bl, s.top, bh - bl, s.bottom - s.top); if (specLines.bg) drawLine(ctx, s, specLines.f, specLines.bg, th.muted, 2, [5, 4]); drawLine(ctx, s, specLines.f, specLines.tear, mainColor(th), 2); }, // eslint-disable-next-line react-hooks/exhaustive-deps [specLines, settings, fHi], ); const specHover = (p: PointerInfo) => { if (!specLines) return null; let best = 0; 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; const lines = [fmtHz(specLines.f[best]), `tear: ${specLines.tear[best].toFixed(1)} dB`]; if (specLines.bg) lines.push(`background: ${specLines.bg[best].toFixed(1)} dB`); return { lines, x: specLines.f[best], y: specLines.tear[best] }; }; const a = analysis; const warnings: string[] = []; if (!seg) warnings.push("No tear was found automatically. Drag across the plots below to mark it."); 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.`); 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."); else if (a && a.snrDb < 10) 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.`); 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."); const th = readTheme(document.documentElement); return ( <> {warnings.map((w) => (
⚠ {w}
))}

Tear range

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.

Showing {fmtSec(view[0])}–{fmtSec(view[1])}. Pinch to zoom, two-finger swipe sideways to move along.
{ const lines = [`${p.xv.toFixed(3)} s`]; if (levels) { const i = Math.floor(p.xv / levels.frameSec); if (i >= 0 && i < levels.power.length) lines.push(`${db10(levels.power[i]).toFixed(1)} dBFS in ${bandLabel}`); } return { lines }; }} ariaLabel={`Sound level in ${bandLabel} over time, with the tear range`} {...timeHandlers} /> ({ lines: [`${p.xv.toFixed(4)} s`] })} ariaLabel="Waveform, with the tear range" {...timeHandlers} /> ({ lines: [`${p.xv.toFixed(3)} s`, fmtHz(p.yv)] })} ariaLabel="Spectrogram, with the tear range" {...timeHandlers} />
Spectrogram: brighter is louder; dashed lines mark the analysis band.
{meta.segmentManual ? "Range set by hand." : `Range found automatically from the level in ${bandLabel}.`}

Results

Frequency makeup of the tear

How the tear's sound energy is spread over frequency, compared with the background noise alone.

tear background alone, over the same duration analysis band ({bandLabel})
); } function RangeInputs({ seg, dur, onCommit }: { seg: Segment | null; dur: number; onCommit: (s: Segment) => void }) { const [a, setA] = useState(""); const [b, setB] = useState(""); useEffect(() => { setA(seg ? seg.start.toFixed(3) : ""); setB(seg ? seg.end.toFixed(3) : ""); }, [seg]); const commit = () => { const s = Math.min(Math.max(+a, 0), dur); const e = Math.min(Math.max(+b, 0), dur); if (Number.isFinite(s) && Number.isFinite(e) && e - s >= 0.01 && (!seg || s !== seg.start || e !== seg.end)) onCommit({ start: s, end: e }); else { setA(seg ? seg.start.toFixed(3) : ""); setB(seg ? seg.end.toFixed(3) : ""); } }; const key = (e: React.KeyboardEvent) => e.key === "Enter" && (e.target as HTMLInputElement).blur(); return (
Duration {seg ? fmtSec(seg.end - seg.start) : "–"}
); } function fmtKHz(hz: number) { return `${+(hz / 1000).toFixed(2)}`; } function Stats({ a, settings, bandLabel }: { a: Analysis | null; settings: AnalysisSettings; bandLabel: string }) { if (!a) return

No tear range.

; const items: [string, string, string?][] = [ ["Tear duration", fmtSec(a.duration)], ["Speed", `${a.speedInPerSec.toFixed(2)} in/s`, `${settings.sheetLengthIn} in ÷ duration`], ["Sound energy", Number.isFinite(db10(a.energy)) && a.energy > 0 ? `${db10(a.energy).toFixed(1)} dB` : "–", `${bandLabel}, background removed (relative units)`], ["Mean power", a.energy > 0 ? `${db10(a.energy / a.duration).toFixed(1)} dBFS` : "–", `${bandLabel}, energy ÷ duration`], ["Peak", `${a.peakDbfs.toFixed(1)} dBFS`, a.nearClip ? `${a.nearClip} samples near clipping` : "no clipping"], [ "Above background", Number.isFinite(a.snrDb) ? `${a.snrDb.toFixed(1)} dB` : "–", a.backgroundDbfs !== null ? `${bandLabel}; background ${a.backgroundDbfs.toFixed(1)} dBFS` : "no background estimate", ], ]; return (
{items.map(([k, v, sub]) => (
{k}
{v}
{sub &&
{sub}
}
))}
); } function spectrogramImage(spec: ReturnType): HTMLCanvasElement { const c = document.createElement("canvas"); c.width = spec.cols; c.height = spec.bins; const ctx = c.getContext("2d")!; const img = ctx.createImageData(spec.cols, spec.bins); const top = spec.maxDb; const range = 90; for (let col = 0; col < spec.cols; col++) { for (let k = 0; k < spec.bins; k++) { const v = (spec.db[col * spec.bins + k] - (top - range)) / range; const [r, g, b] = magma(Math.min(1, Math.max(0, v))); const o = ((spec.bins - 1 - k) * spec.cols + col) * 4; img.data[o] = r; img.data[o + 1] = g; img.data[o + 2] = b; img.data[o + 3] = 255; } } ctx.putImageData(img, 0, 0); return c; }