import { useCallback, useEffect, useMemo, useState } from "react"; import { CanvasPlot, drawLine, drawMarker, readTheme, type MarkerShape, 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 { colorFor, db10, download, fmtHz, fmtSec, getAnalysis, groupOrder, groupStyle, linearFit } from "../model.ts"; interface Props { recs: RecordingMeta[]; // recordings included in the comparison all: RecordingMeta[]; settings: AnalysisSettings; onOpen: (id: string) => void; } interface Row { meta: RecordingMeta; a: Analysis; } type Metric = "median" | "centroid" | "power"; const METRICS: Record number; fmt: (v: number) => string; log: boolean }> = { median: { label: "Median frequency", axis: "median frequency (Hz)", get: (a) => a.medianFreq, fmt: fmtHz, log: false }, centroid: { label: "Spectral centroid", axis: "centroid (Hz)", get: (a) => a.centroid, fmt: fmtHz, log: false }, power: { label: "Mean power", axis: "mean power (dBFS)", get: (a) => db10(a.energy / a.duration), fmt: (v) => `${v.toFixed(1)} dBFS`, log: false }, }; export function CompareView({ recs, all, settings, onOpen }: Props) { const [rows, setRows] = useState([]); const [progress, setProgress] = useState<[number, number]>([0, 0]); const [metric, setMetric] = useState("median"); const [specMode, setSpecMode] = useState<"group" | "each">("group"); const [normalize, setNormalize] = useState(false); const [smoothing, setSmoothing] = useState(1 / 6); useEffect(() => { let live = true; (async () => { const out: Row[] = []; setProgress([0, recs.length]); for (let i = 0; i < recs.length; i++) { const a = await getAnalysis(recs[i], settings); if (!live) return; if (a && a.energy > 0) out.push({ meta: recs[i], a }); setProgress([i + 1, recs.length]); await new Promise((r) => setTimeout(r, 0)); } if (live) setRows(out); })(); return () => { live = false; }; }, [recs, settings]); const groups = useMemo(() => groupOrder(rows.map((r) => r.meta)), [rows]); const style = useCallback((label: string) => groupStyle(label, all), [all]); const skipped = recs.length - rows.length; const loading = progress[0] < progress[1]; if (!recs.length) return
No recordings are included in the comparison. Tick some in the list on the left.
; return (
{loading && (
Analysing {progress[0]} / {progress[1]}…
)} {!loading && skipped > 0 && (
{skipped} recording{skipped > 1 ? "s have" : " has"} no tear segment or no energy above the background and {skipped > 1 ? "are" : "is"} left out.
)}

Total sound energy vs tear duration

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

db10(a.energy)} yFmt={(v) => `${v.toFixed(1)} dB`} yLabel="energy (dB re FS²·s)" style={style} onOpen={onOpen} fitUnit="dB" minSpan={10} />

{METRICS[metric].label} vs tear duration

{metric === "power" ? "Same energy packed into less time means power rises 10 dB for every 10× shorter tear." : "If the clicks are the same at every speed, this should not depend on duration."}

Frequency makeup

Energy spectral density of each tear with the background removed. {normalize ? " Each curve is divided by its total energy in the band, so only the shape is compared." : " If tears at all speeds contain the same clicks, the curves should lie on top of each other."}

All recordings

); } // ---------- summary ---------- function Summary({ rows, groups }: { rows: Row[]; groups: string[] }) { if (rows.length < 3) return
Add at least three recordings (ideally at a few different speeds) to see trends.
; const lx = rows.map((r) => Math.log10(r.a.duration)); const fe = linearFit(lx, rows.map((r) => db10(r.a.energy))); const fm = linearFit(lx, rows.map((r) => r.a.medianFreq)); const span = Math.max(...rows.map((r) => r.a.duration)) / Math.min(...rows.map((r) => r.a.duration)); return (

The two questions

Same total energy at every speed?
{fe && (
Energy changes by {fmtSigned(fe.b)} ± {fe.seB.toFixed(2)} dB for each 10× longer tear (straight-line fit, ± one standard error, {fe.n} recordings). {" "} {verdict(fe.b, fe.seB)}
)}
Same frequency makeup at every speed?
{fm && (
Median frequency changes by {fmtSigned(fm.b, 0)} ± {fm.seB.toFixed(0)} Hz for each 10× longer tear. Compare the curve shapes below (tick “shape only”). {" "} {verdict(fm.b, fm.seB)}
)}

Durations span {span.toFixed(1)}× across {groups.length} label{groups.length === 1 ? "" : "s"}. {span < 3 ? " That is a narrow range; trends will be hard to see." : ""} The fit uses measured durations, not labels. A trend within about two standard errors of zero is not distinguishable from no trend. Run-to-run scatter at the same speed tells you how much a single comparison can be trusted.

); } function fmtSigned(v: number, digits = 2) { return `${v >= 0 ? "+" : "−"}${Math.abs(v).toFixed(digits)}`; } function verdict(b: number, se: number) { if (!Number.isFinite(se)) return null; return Math.abs(b) < 2 * se ? (not clearly different from zero) : (clearly different from zero); } // ---------- scatter ---------- function Scatter({ rows, y, yFmt, yLabel, style, onOpen, fitUnit, minSpan, }: { minSpan: number; rows: Row[]; y: (a: Analysis) => number; yFmt: (v: number) => string; yLabel: string; style: (l: string) => { slot: number | null; shape: MarkerShape }; onOpen: (id: string) => void; fitUnit: string; }) { 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 (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) { const st = style(p.r.meta.label); drawMarker(ctx, s.x(p.x), s.y(p.y), st.shape, colorFor(st.slot, th.series, th.muted), th.surface, 5); } }, [pts, fit, xr, style], ); 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: [q.r.meta.label, `${fmtSec(q.x)} · ${yFmt(q.y)}`, "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`} /> r.meta))} style={style} extra={fit ? `dashed: straight-line fit, slope ${fmtSigned(fit.b, fitUnit === "Hz" ? 0 : 2)} ${fitUnit} per 10× duration` : undefined} /> ); } // ---------- spectra overlay ---------- function SpectraOverlay({ rows, groups, mode, normalize, smoothing, settings, style, }: { rows: Row[]; groups: string[]; mode: "group" | "each"; normalize: boolean; smoothing: number; settings: AnalysisSettings; style: (l: string) => { slot: number | null; shape: MarkerShape }; }) { const fsMin = rows.length ? Math.min(...rows.map((r) => r.a.fs)) : 48000; const fLo = Math.max(20, settings.bandLow); const fHi = Math.min(settings.bandHigh, fsMin / 2); const lines = useMemo(() => { const per = 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 { label: r.meta.label, name: r.meta.label, f: sm.f, v: sm.v }; }); if (mode === "each") return per.map((p) => ({ ...p, db: p.v.map(db10Floor) })); return groups .map((g) => { const members = per.filter((p) => p.label === g); if (!members.length) return null; const f = members[0].f; const v = f.map((_, i) => members.reduce((s, m) => s + (m.v[i] ?? 0), 0) / members.length); return { label: g, name: `${g} (n=${members.length})`, f, v, db: v.map(db10Floor) }; }) .filter((x): x is NonNullable => !!x); }, [rows, groups, mode, 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) => { for (const l of lines) { const st = style(l.label); drawLine(ctx, s, l.f, l.db, colorFor(st.slot, th.series, th.muted), mode === "each" ? 1.5 : 2); } }, [lines, style, mode], ); 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; const vals = lines.slice(0, 10).map((l) => `${l.name}: ${Number.isFinite(l.db[i]) ? l.db[i].toFixed(1) : "–"} dB`); if (lines.length > 10) vals.push(`… ${lines.length - 10} more`); return { lines: [fmtHz(f[i]), ...vals], x: f[i] }; }} ariaLabel="Energy spectral density of tears, overlaid" /> ); } function db10Floor(v: number) { return v > 0 ? 10 * Math.log10(v) : NaN; } // ---------- legend & table ---------- function MarkerIcon({ shape, color, line }: { shape: MarkerShape; color: string; line?: boolean }) { if (line) return ; const d: Record = { circle: "M9,4 a5,5 0 1,0 0.01,0", square: "M4.5,4.5 h9 v9 h-9 z", triangle: "M9,3.5 L14.2,13 L3.8,13 z", diamond: "M9,2.8 L14.2,9 L9,15.2 L3.8,9 z", cross: "M7,4 h4 v3 h3 v4 h-3 v3 h-4 v-3 h-3 v-4 h3 z", }; return ( ); } function Legend({ labels, style, lines, extra }: { labels: string[]; style: (l: string) => { slot: number | null; shape: MarkerShape }; lines?: boolean; extra?: string }) { const th = readTheme(document.documentElement); return (
{labels.map((l) => { const st = style(l); return ( {l} ); })} {extra && {extra}}
); } function Table({ rows, groups, style, onOpen }: { rows: Row[]; groups: string[]; style: (l: string) => { slot: number | null; shape: MarkerShape }; onOpen: (id: string) => void }) { const th = readTheme(document.documentElement); const sorted = [...rows].sort((a, b) => groups.indexOf(a.meta.label) - groups.indexOf(b.meta.label) || b.a.duration - a.a.duration); const groupStats = groups.map((g) => { const rs = rows.filter((r) => r.meta.label === g); const e = rs.map((r) => db10(r.a.energy)); const mean = e.reduce((s, v) => s + v, 0) / e.length; const sd = e.length > 1 ? Math.sqrt(e.reduce((s, v) => s + (v - mean) ** 2, 0) / (e.length - 1)) : NaN; return { g, n: rs.length, dur: rs.reduce((s, r) => s + r.a.duration, 0) / rs.length, mean, sd, med: rs.reduce((s, r) => s + r.a.medianFreq, 0) / rs.length, }; }); return (
{groupStats.map((s) => { const st = style(s.g); return ( ); })}
Label n Mean duration Energy (dB), mean ± sd Median freq, mean
{s.g} {s.n} {fmtSec(s.dur)} {s.mean.toFixed(1)} {Number.isFinite(s.sd) ? ` ± ${s.sd.toFixed(1)}` : ""} {fmtHz(s.med)}
{sorted.map(({ meta, a }) => { const st = style(meta.label); return ( onOpen(meta.id)}> ); })}
Label Duration Speed (in/s) Energy (dB) Above bg (dB) Median freq Centroid Peak (dBFS)
{meta.label} {fmtSec(a.duration)} {a.speedInPerSec.toFixed(2)} {db10(a.energy).toFixed(1)} {Number.isFinite(a.snrDb) ? a.snrDb.toFixed(1) : "–"} {fmtHz(a.medianFreq)} {fmtHz(a.centroid)} {a.peakDbfs.toFixed(1)} {a.nearClip > 0 ? ⚠ clipped : meta.source !== "mic" ? {meta.source} : null}
); } function exportCsv(rows: Row[], settings: AnalysisSettings) { const head = [ "id", "created", "label", "source", "notes", "sample_rate", "tear_start_s", "tear_end_s", "segment_manual", "duration_s", "speed_in_per_s", "energy_db", "energy_raw_db", "background_db", "above_background_db", "median_hz", "centroid_hz", "f10_hz", "f90_hz", "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.id, new Date(m.createdAt).toISOString(), m.label, m.source, m.notes, 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.medianFreq.toFixed(1), a.centroid.toFixed(1), a.f10.toFixed(1), a.f90.toFixed(1), a.peakDbfs.toFixed(2), a.nearClip, settings.bandLow, settings.bandHigh, settings.sheetLengthIn, ] .map(q) .join(","), ); } download(new Blob([lines.join("\n")], { type: "text/csv" }), `rip-sound-summary-${new Date().toISOString().slice(0, 10)}.csv`); }