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, linearFit, SPEEDS, speedName, speedStyle } from "../model.ts"; interface Props { recs: RecordingMeta[]; // at most one per speed, in speed order 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; minSpan: number; unit: string }> = { median: { label: "Median frequency", axis: "median frequency (Hz)", get: (a) => a.medianFreq, fmt: fmtHz, minSpan: 4000, unit: "Hz" }, centroid: { label: "Spectral centroid", axis: "centroid (Hz)", get: (a) => a.centroid, fmt: fmtHz, minSpan: 4000, unit: "Hz" }, power: { label: "Mean power", axis: "mean power (dBFS)", get: (a) => db10(a.energy / a.duration), fmt: (v) => `${v.toFixed(1)} dBFS`, minSpan: 10, unit: "dB" }, }; const energyOf = (a: Analysis) => db10(a.energy); 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 [metric, setMetric] = useState("median"); 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); setReady(true); } })(); return () => { live = false; }; }, [recs, settings]); const bandLabel = `${+(settings.energyLow / 1000).toFixed(2)}–${+(settings.energyHigh / 1000).toFixed(2)} kHz`; const missing = SPEEDS.filter((s) => !recs.some((r) => r.label === s.id)); const unusable = recs.filter((m) => !rows.some((r) => r.meta.id === m.id)); if (!recs.length) return
Nothing to compare yet. Record a tear at two or more speeds on the Record tab.
; if (!ready) return
Analysing…
; return (
{(missing.length > 0 || unusable.length > 0) && (
{missing.length > 0 &&
Not recorded yet: {missing.map((s) => s.name.toLowerCase()).join(", ")}.
} {unusable.length > 0 &&
Left out (no tear range or no sound above the background): {unusable.map((m) => speedName(m.label)).join(", ")}.
}
)}

Total sound energy ({bandLabel}) vs tear duration

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

{METRICS[metric].label} vs tear duration

{metric === "power" ? "The same energy packed into less time: power should rise 10 dB for every 10× shorter tear (slope −10 dB)." : "If the clicks are the same at every speed, this should not depend on duration."}

Frequency makeup

Energy spectrum of each tear, background removed. {normalize ? " Each curve is divided by its total energy over the plotted range, so only the shape is compared." : " 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 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 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)); const eRange = Math.max(...e) - Math.min(...e); const meds = rows.map((r) => r.a.medianFreq); return (

The two questions

Same total energy at every speed?
Across {rows.length} speeds 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?
Median frequency ranges from {fmtHz(Math.min(...meds))} to {fmtHz(Math.max(...meds))}. {fm && ( <> {" "} The trend is {fmtSigned(fm.b, 0)} Hz per 10× longer tear (± {fm.seB.toFixed(0)} Hz). )}{" "} Compare the curve shapes below.

Tear durations span {span.toFixed(1)}×{span < 3 ? ", a narrow range, so trends will be hard to see" : ""}. Trends use measured durations, not the speed names. With one tear per speed there is no way to tell how much two tears at the same speed would differ, so differences of a dB or two may just be ordinary variation from tear to tear. {fe ? "" : " A trend line needs at least three speeds."}

); } function fmtSigned(v: number, digits = 2) { return `${v >= 0 ? "+" : "−"}${Math.abs(v).toFixed(digits)}`; } // ---------- scatter ---------- function Scatter({ rows, y, yFmt, yLabel, onOpen, unit, minSpan, }: { 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 (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 = speedStyle(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, 6); } }, [pts, fit, xr], ); 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: [speedName(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`} /> ); } // ---------- 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 = Math.max(20, settings.shapeLow); const fHi = Math.min(settings.shapeHigh, fsMin / 2); const lines = useMemo( () => rows.map((r) => { const scale = normalize ? 1 / r.a.shapeEnergy : 1; const sm = smoothLog(r.a.freqs, r.a.netEsd.map((v) => v * scale), fLo, fHi, smoothing); return { label: r.meta.label, 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) => { if (!normalize) { // mark the energy 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); } for (const l of lines) { const st = speedStyle(l.label); drawLine(ctx, s, l.f, l.db, colorFor(st.slot, th.series, th.muted), 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) => `${speedName(l.label)}: ${Number.isFinite(l.db[i]) ? l.db[i].toFixed(1) : "–"} dB`)], x: f[i] }; }} ariaLabel="Energy spectra of the tears, overlaid" /> ); } // ---------- 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({ rows, lines, extra }: { rows: Row[]; lines?: boolean; extra?: string }) { const th = readTheme(document.documentElement); return (
{rows.map((r) => { const st = speedStyle(r.meta.label); return ( {speedName(r.meta.label)} ); })} {extra && {extra}}
); } function Table({ rows, onOpen }: { rows: Row[]; onOpen: (id: string) => void }) { const th = readTheme(document.documentElement); return (
{rows.map(({ meta, a }) => { const st = speedStyle(meta.label); return ( onOpen(meta.id)} title="Open on the Record tab"> ); })}
Speed Tear duration Speed (in/s) Energy (dB) Mean power (dBFS) Median freq Centroid Above background Peak (dBFS)
{speedName(meta.label)} {fmtSec(a.duration)} {a.speedInPerSec.toFixed(2)} {db10(a.energy).toFixed(1)} {db10(a.energy / a.duration).toFixed(1)} {fmtHz(a.medianFreq)} {fmtHz(a.centroid)} {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 = [ "speed", "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", "median_hz", "centroid_hz", "f10_hz", "f90_hz", "peak_dbfs", "near_clip_samples", "energy_band_low_hz", "energy_band_high_hz", "spectrum_band_low_hz", "spectrum_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, 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.medianFreq.toFixed(1), a.centroid.toFixed(1), a.f10.toFixed(1), a.f90.toFixed(1), a.peakDbfs.toFixed(2), a.nearClip, settings.energyLow, settings.energyHigh, settings.shapeLow, settings.shapeHigh, settings.sheetLengthIn, ] .map(q) .join(","), ); } download(new Blob([lines.join("\n")], { type: "text/csv" }), `rip-sound-summary-${new Date().toISOString().slice(0, 10)}.csv`); }