import { useCallback, useEffect, useMemo, useState } from "react"; import { CanvasPlot, drawLine, drawMarker, readTheme, type PointerInfo, type Scales, type Theme } from "./CanvasPlot.tsx"; import { smoothLog, type Analysis, type AnalysisSettings } from "../analysis/analyze.ts"; import type { RecordingMeta } from "../storage/db.ts"; import { db10, download, durationColor, fmtDate, fmtHz, fmtSec, getAnalysis, linearFit, sampleTitle } from "../model.ts"; interface Props { recs: RecordingMeta[]; // all samples, slowest first settings: AnalysisSettings; onOpen: (id: string) => void; } interface Row { meta: RecordingMeta; a: Analysis; } const powerOf = (a: Analysis) => db10(a.energy / a.duration); const fmtDbfs = (v: number) => `${v.toFixed(1)} dBFS`; const energyOf = (a: Analysis) => db10(a.energy); const rowName = (r: Row) => `${fmtSec(r.a.duration)} tear${r.meta.label ? ` · ${r.meta.label}` : ""}`; const fmtDb = (v: number) => `${v.toFixed(1)} dB`; export function CompareView({ recs, settings, onOpen }: Props) { const [rows, setRows] = useState([]); const [ready, setReady] = useState(false); const [normalize, setNormalize] = useState(false); const [smoothing, setSmoothing] = useState(1 / 6); useEffect(() => { let live = true; setReady(false); (async () => { const out: Row[] = []; for (const m of recs) { const a = await getAnalysis(m, settings); if (!live) return; if (a && a.energy > 0) out.push({ meta: m, a }); await new Promise((r) => setTimeout(r, 0)); } if (live) { setRows(out.sort((p, q) => q.a.duration - p.a.duration)); setReady(true); } })(); return () => { live = false; }; }, [recs, settings]); const bandLabel = `${+(settings.energyLow / 1000).toFixed(2)}–${+(settings.energyHigh / 1000).toFixed(2)} kHz`; const unusable = recs.filter((m) => !rows.some((r) => r.meta.id === m.id)); if (!recs.length) return
Nothing to compare yet. Record tears at a few different speeds on the Record tab.
; if (!ready) return
Analysing…
; return (
{unusable.length > 0 && (
Left out (no tear range or no sound above the background): {unusable.map((m) => m.label || `${sampleTitle(m)}, ${fmtDate(m.createdAt)}`).join("; ")}.
)}

Total sound energy ({bandLabel}) vs tear duration

If every tear contains the same clicks, the points should lie on a flat line.

Loudness ({bandLabel}) vs tear duration

Mean power over the tear. The same energy packed into less time should be 10 dB louder for every 10× shorter tear, as the dotted line shows.

Frequency makeup

Energy spectrum of each tear, background removed. {normalize ? " Each curve is divided by its energy in the analysis band (shaded), so the curves line up there and only differences in shape remain." : " If tears at all speeds contain the same clicks, the curves should lie on top of each other."}

Numbers

); } // ---------- summary ---------- function Summary({ rows, bandLabel }: { rows: Row[]; bandLabel: string }) { if (rows.length < 2) return
Record at least two samples at different speeds to compare them.
; const lx = rows.map((r) => Math.log10(r.a.duration)); const e = rows.map((r) => db10(r.a.energy)); const fe = linearFit(lx, e); const span = Math.max(...rows.map((r) => r.a.duration)) / Math.min(...rows.map((r) => r.a.duration)); const eRange = Math.max(...e) - Math.min(...e); return (

The two questions

Same total energy at every speed?
Across {rows.length} samples the energy in {bandLabel} varies over a range of {eRange.toFixed(1)} dB. {fe && ( <> {" "} The trend is {fmtSigned(fe.b)} dB per 10× longer tear (straight-line fit, ± {fe.seB.toFixed(2)} dB). )}
Same frequency makeup at every speed?
See the frequency plot below. If the curves for different speeds have the same shape (tick “compare shape only” to line them up), the frequency makeup is the same.

Tear durations span {span.toFixed(1)}×{span < 3 ? ", a narrow range, so trends will be hard to see" : ""}. A few tears at similar speeds show how much tears vary on their own; differences smaller than that variation don't mean anything. {fe ? "" : " A trend line needs at least three samples."}

); } function fmtSigned(v: number, digits = 2) { return `${v >= 0 ? "+" : "−"}${Math.abs(v).toFixed(digits)}`; } // ---------- scatter ---------- function Scatter({ rows, y, yFmt, yLabel, onOpen, unit, minSpan, expectSlope, }: { expectSlope?: number; // dB per 10× duration: draws the expected trend through the points' mean rows: Row[]; y: (a: Analysis) => number; yFmt: (v: number) => string; yLabel: string; onOpen: (id: string) => void; unit: string; minSpan: number; }) { const pts = useMemo(() => rows.map((r) => ({ r, x: r.a.duration, y: y(r.a) })).filter((p) => Number.isFinite(p.y)), [rows, y]); const xr = useMemo<[number, number]>(() => { if (!pts.length) return [0.1, 20]; const lo = Math.min(...pts.map((p) => p.x)); const hi = Math.max(...pts.map((p) => p.x)); return [Math.min(lo / 1.5, 0.2), Math.max(hi * 1.5, 15)]; }, [pts]); const yr = useMemo<[number, number]>(() => { if (!pts.length) return [0, 1]; const lo = Math.min(...pts.map((p) => p.y)); const hi = Math.max(...pts.map((p) => p.y)); // keep a minimum span so tiny differences are not blown up to fill the plot const mid = (lo + hi) / 2; const half = Math.max((hi - lo) * 0.6, minSpan / 2); return [mid - half, mid + half]; }, [pts, minSpan]); const fit = useMemo(() => linearFit(pts.map((p) => Math.log10(p.x)), pts.map((p) => p.y)), [pts]); const draw = useCallback( (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => { if (expectSlope !== undefined && pts.length) { const mx = pts.reduce((t, p) => t + Math.log10(p.x), 0) / pts.length; const my = pts.reduce((t, p) => t + p.y, 0) / pts.length; const yAt = (x: number) => my + expectSlope * (Math.log10(x) - mx); drawLine(ctx, s, [xr[0], xr[1]], [yAt(xr[0]), yAt(xr[1])], th.ink2, 1.5, [2, 4]); } if (fit) drawLine(ctx, s, [xr[0], xr[1]], [fit.a + fit.b * Math.log10(xr[0]), fit.a + fit.b * Math.log10(xr[1])], th.muted, 1.5, [6, 4]); for (const p of pts) drawMarker(ctx, s.x(p.x), s.y(p.y), "circle", durationColor(p.x, th), th.surface, 6); }, [pts, fit, xr, expectSlope], ); const near = (p: PointerInfo) => { let best: (typeof pts)[number] | null = null; let bd = 14 * 14; for (const q of pts) { const d = (p.scales.x(q.x) - p.px) ** 2 + (p.scales.y(q.y) - p.py) ** 2; if (d < bd) { bd = d; best = q; } } return best; }; return ( <> { const q = near(p); if (!q) return null; return { lines: [rowName(q.r), `${yFmt(q.y)} · ${q.r.a.speedInPerSec.toFixed(2)} in/s`, "click to open"], x: q.x, y: q.y }; }} onClick={(p) => { const q = near(p); if (q) onOpen(q.r.meta.id); }} cursor={(p) => (near(p) ? "pointer" : "crosshair")} ariaLabel={`${yLabel} against tear duration`} /> ); } // ---------- spectra overlay ---------- function SpectraOverlay({ rows, normalize, smoothing, settings }: { rows: Row[]; normalize: boolean; smoothing: number; settings: AnalysisSettings }) { const fsMin = rows.length ? Math.min(...rows.map((r) => r.a.fs)) : 48000; const fLo = 20; const fHi = fsMin / 2; const lines = useMemo( () => rows.map((r) => { const scale = normalize ? 1 / r.a.energy : 1; const sm = smoothLog(r.a.freqs, r.a.netEsd.map((v) => v * scale), fLo, fHi, smoothing); return { name: rowName(r), dur: r.a.duration, f: sm.f, db: sm.v.map((v) => (v > 0 ? 10 * Math.log10(v) : NaN)) }; }), [rows, normalize, smoothing, fLo, fHi], ); const yr = useMemo<[number, number]>(() => { const all = lines.flatMap((l) => l.db.filter(Number.isFinite)); if (!all.length) return [-100, 0]; const top = Math.max(...all); return [Math.floor((top - 50) / 10) * 10, Math.ceil((top + 3) / 5) * 5]; }, [lines]); const draw = useCallback( (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => { { // mark the analysis band ctx.fillStyle = th.seg; const bl = s.x(Math.max(settings.energyLow, fLo)); const bh = s.x(Math.min(settings.energyHigh, fHi)); if (bh > bl) ctx.fillRect(bl, s.top, bh - bl, s.bottom - s.top); } // slowest first, so the fastest (strongest colour) are drawn on top for (const l of lines) drawLine(ctx, s, l.f, l.db, durationColor(l.dur, th), 2); }, [lines, normalize, settings, fLo, fHi], ); return ( <> { if (!lines.length) return null; const f = lines[0].f; let i = 0; for (let k = 1; k < f.length; k++) if (Math.abs(Math.log(f[k] / p.xv)) < Math.abs(Math.log(f[i] / p.xv))) i = k; return { lines: [fmtHz(f[i]), ...lines.map((l) => `${l.name}: ${Number.isFinite(l.db[i]) ? l.db[i].toFixed(1) : "–"} dB`)], x: f[i] }; }} ariaLabel="Energy spectra of the tears, overlaid" /> ); } // ---------- legend & table ---------- function Swatch({ color, line }: { color: string; line?: boolean }) { return line ? ( ) : ( ); } function Legend({ rows, lines, extra }: { rows: Row[]; lines?: boolean; extra?: string }) { const th = readTheme(document.documentElement); return (
Colour = tear duration (stronger = faster): {rows.map((r) => ( {rowName(r)} ))} {extra && {extra}}
); } function Table({ rows, onOpen }: { rows: Row[]; onOpen: (id: string) => void }) { const th = readTheme(document.documentElement); return (
{rows.map(({ meta, a }) => { return ( onOpen(meta.id)} title="Open on the Record tab"> ); })}
Sample Tear duration Speed (in/s) Energy (dB) Mean power (dBFS) Above background Peak (dBFS)
{meta.label || fmtDate(meta.createdAt)} {fmtSec(a.duration)} {a.speedInPerSec.toFixed(2)} {db10(a.energy).toFixed(1)} {db10(a.energy / a.duration).toFixed(1)} {Number.isFinite(a.snrDb) ? `${a.snrDb.toFixed(1)} dB` : "–"} {a.peakDbfs.toFixed(1)} {a.nearClip > 0 ? " ⚠ clipped" : ""}
); } function exportCsv(rows: Row[], settings: AnalysisSettings) { const head = [ "name", "notes", "recorded", "source", "sample_rate", "tear_start_s", "tear_end_s", "range_set_by_hand", "duration_s", "speed_in_per_s", "energy_db", "energy_raw_db", "background_db", "above_background_db", "peak_dbfs", "near_clip_samples", "band_low_hz", "band_high_hz", "sheet_length_in", ]; const q = (v: unknown) => { const s = String(v ?? ""); return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s; }; const lines = [head.join(",")]; for (const { meta: m, a } of rows) { lines.push( [ m.label, m.notes, new Date(m.createdAt).toISOString(), m.source, m.sampleRate, a.segment.start.toFixed(4), a.segment.end.toFixed(4), m.segmentManual, a.duration.toFixed(4), a.speedInPerSec.toFixed(4), db10(a.energy).toFixed(3), db10(a.energyRaw).toFixed(3), db10(a.energyNoise).toFixed(3), a.snrDb.toFixed(2), a.peakDbfs.toFixed(2), a.nearClip, settings.energyLow, settings.energyHigh, settings.sheetLengthIn, ] .map(q) .join(","), ); } download(new Blob([lines.join("\n")], { type: "text/csv" }), `rip-sound-summary-${new Date().toISOString().slice(0, 10)}.csv`); }