import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { CanvasPlot, drawLine, readTheme, type PointerInfo, type Scales, type Theme } from "./CanvasPlot.tsx"; import { bandLevels, 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 { colorFor, db10, fmtHz, fmtSec, getAnalysis, getAudio, speedStyle } 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 { slot } = speedStyle(meta.label); const mainColor = (th: Theme) => colorFor(slot, th.series, th.ink2); const commitSeg = (s: Segment | null) => { setSeg(s); onUpdate({ ...meta, segment: s, segmentManual: true }); }; // ---------- tear range (whole recording) ---------- 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 rangeHandlers = { 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.01) commitSeg(seg); else setSeg(d.before); } }, cursor: (p: PointerInfo) => (edgeAt(p) ? "ew-resize" : "crosshair"), }; 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 drawPlayhead = (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => { if (playhead === null) return; ctx.strokeStyle = th.ink; ctx.lineWidth = 2; ctx.beginPath(); ctx.moveTo(s.x(playhead), s.top); ctx.lineTo(s.x(playhead), s.bottom); ctx.stroke(); }; const drawRange = useCallback( (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => { if (seg) { const a = s.x(seg.start); const b = s.x(seg.end); ctx.fillStyle = th.seg; ctx.fillRect(a, s.top, b - a, s.bottom - s.top); } if (levels) { const { frameSec, power } = levels; const perPx = Math.max(1, Math.floor(power.length / ((s.right - s.left) * 2))); const xs: number[] = []; const ys: number[] = []; for (let i = 0; i < power.length; i += perPx) { let m = 0; for (let j = i; j < Math.min(i + perPx, power.length); j++) m = Math.max(m, power[j]); xs.push((i + perPx / 2) * frameSec); ys.push(db10(m)); } drawLine(ctx, s, xs, ys, mainColor(th), 1.5); } if (seg) { // edges with grab handles for (const t of [seg.start, seg.end]) { const px = s.x(t); ctx.strokeStyle = th.ink; ctx.lineWidth = 2; ctx.beginPath(); ctx.moveTo(px, s.top); ctx.lineTo(px, s.bottom); ctx.stroke(); ctx.fillStyle = th.ink; ctx.beginPath(); ctx.roundRect(px - 4, (s.top + s.bottom) / 2 - 12, 8, 24, 3); ctx.fill(); } } drawPlayhead(ctx, s, th); }, // eslint-disable-next-line react-hooks/exhaustive-deps [levels, seg, slot, playhead], ); // ---------- close-up ---------- const fit = useCallback( (s: Segment | null): [number, number] => { if (!s) return [0, dur]; const m = Math.max(0.05, 0.08 * (s.end - s.start)); return [Math.max(0, s.start - m), Math.min(dur, s.end + m)]; }, [dur], ); const [view, setView] = useState<[number, number]>(() => fit(meta.segment)); useEffect(() => setView(fit(meta.segment)), [meta.id, meta.segment, fit]); 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 pan = useRef<{ px0: number; view0: [number, number] } | null>(null); const closeHandlers = { onPointer: (type: "down" | "move" | "up", p: PointerInfo) => { if (type === "down") pan.current = { px0: p.px, view0: view }; else if (type === "move" && pan.current) { const d = pan.current; const dt = ((p.px - d.px0) / (p.scales.right - p.scales.left)) * (d.view0[1] - d.view0[0]); setView(clampView(d.view0[0] - dt, d.view0[1] - dt)); } else pan.current = null; }, // pinch on a trackpad (or ctrl + scroll) zooms; plain scrolling scrolls the page onWheel: (p: PointerInfo, ev: WheelEvent) => { if (!ev.ctrlKey) return false; zoom(Math.exp(ev.deltaY * 0.01), Math.min(Math.max(p.xv, view[0]), view[1])); return true; }, onDoubleClick: () => setView(fit(seg)), cursor: () => "grab", }; const drawEdges = (ctx: CanvasRenderingContext2D, s: Scales, color: string) => { if (!seg) return; ctx.strokeStyle = color; ctx.lineWidth = 1.5; ctx.setLineDash([5, 4]); ctx.beginPath(); for (const t of [seg.start, seg.end]) { ctx.moveTo(s.x(t), s.top); ctx.lineTo(s.x(t), s.bottom); } ctx.stroke(); ctx.setLineDash([]); }; const waveMax = useMemo(() => { if (!x) return 1; let m = 0; for (let i = 0; i < x.length; i++) m = Math.max(m, Math.abs(x[i])); return Math.max(m * 1.05, 1e-4); }, [x]); const drawWave = useCallback( (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => { if (x) { const color = mainColor(th); const a = Math.max(0, Math.floor(view[0] * fs)); const b = Math.min(x.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(x.length, b + 1); i++) { xs.push(i / fs); ys.push(x[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 = x[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)); } } } drawEdges(ctx, s, th.ink2); drawPlayhead(ctx, s, th); }, // eslint-disable-next-line react-hooks/exhaustive-deps [x, view, fs, seg, slot, playhead], ); 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); } drawEdges(ctx, s, "#ffffff"); if (playhead !== null) { ctx.strokeStyle = "#ffffff"; ctx.lineWidth = 2; ctx.beginPath(); ctx.moveTo(s.x(playhead), s.top); ctx.lineTo(s.x(playhead), s.bottom); ctx.stroke(); } void th; }, // eslint-disable-next-line react-hooks/exhaustive-deps [spec, specImage, view, seg, playhead], ); // ---------- 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 energy 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, slot], ); 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 plot 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 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.`); 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

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 adjust it. Everything below uses only this range.

{ const lines = [`${p.xv.toFixed(2)} 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`); } return { lines }; }} ariaLabel="Sound level over the whole recording, with the tear range" {...rangeHandlers} />
{meta.segmentManual ? "Range set by hand." : "Range found automatically."}

Results

Close-up

Drag to move along. Pinch (or ctrl + scroll) to zoom. Dashed lines mark the tear range.

({ lines: [`${p.xv.toFixed(4)} s`] })} ariaLabel="Waveform close-up" {...closeHandlers} /> ({ lines: [`${p.xv.toFixed(3)} s`, fmtHz(p.yv)] })} ariaLabel="Spectrogram close-up" {...closeHandlers} />

Showing {fmtSec(view[0])}–{fmtSec(view[1])}. Spectrogram: 1024-point windows; brighter is louder, spanning the top 90 dB of this recording.

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 energy 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; }