1import { useCallback, useEffect, useMemo, useState } from "react";
2import { CanvasPlot, drawLine, drawMarker, readTheme, type MarkerShape, type PointerInfo, type Scales, type Theme } from "./CanvasPlot.tsx";
3import { smoothLog, type Analysis, type AnalysisSettings } from "../analysis/analyze.ts";
4import type { RecordingMeta } from "../storage/db.ts";
5import { colorFor, db10, download, fmtHz, fmtSec, getAnalysis, linearFit, SPEEDS, speedName, speedStyle } from "../model.ts";
7interface Props {
8 recs: RecordingMeta[]; // at most one per speed, in speed order
9 settings: AnalysisSettings;
10 onOpen: (id: string) => void;
11}
13interface Row {
14 meta: RecordingMeta;
15 a: Analysis;
16}
18type Metric = "median" | "centroid" | "power";
19const METRICS: Record<Metric, { label: string; axis: string; get: (a: Analysis) => number; fmt: (v: number) => string; minSpan: number; unit: string }> = {
20 median: { label: "Median frequency", axis: "median frequency (Hz)", get: (a) => a.medianFreq, fmt: fmtHz, minSpan: 4000, unit: "Hz" },
21 centroid: { label: "Spectral centroid", axis: "centroid (Hz)", get: (a) => a.centroid, fmt: fmtHz, minSpan: 4000, unit: "Hz" },
22 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" },
23};
25const energyOf = (a: Analysis) => db10(a.energy);
26const fmtDb = (v: number) => `${v.toFixed(1)} dB`;
28export function CompareView({ recs, settings, onOpen }: Props) {
29 const [rows, setRows] = useState<Row[]>([]);
30 const [ready, setReady] = useState(false);
31 const [metric, setMetric] = useState<Metric>("median");
32 const [normalize, setNormalize] = useState(false);
33 const [smoothing, setSmoothing] = useState(1 / 6);
35 useEffect(() => {
36 let live = true;
37 setReady(false);
38 (async () => {
39 const out: Row[] = [];
40 for (const m of recs) {
41 const a = await getAnalysis(m, settings);
42 if (!live) return;
43 if (a && a.energy > 0) out.push({ meta: m, a });
44 await new Promise((r) => setTimeout(r, 0));
45 }
46 if (live) {
47 setRows(out);
48 setReady(true);
49 }
50 })();
51 return () => {
52 live = false;
53 };
54 }, [recs, settings]);
56 const missing = SPEEDS.filter((s) => !recs.some((r) => r.label === s.id));
57 const unusable = recs.filter((m) => !rows.some((r) => r.meta.id === m.id));
59 if (!recs.length) return <div className="card empty">Nothing to compare yet. Record a tear at two or more speeds on the Record tab.</div>;
60 if (!ready) return <div className="card muted">Analysing…</div>;
62 return (
63 <div className="compare">
64 {(missing.length > 0 || unusable.length > 0) && (
65 <div className="card muted small">
66 {missing.length > 0 && <div>Not recorded yet: {missing.map((s) => s.name.toLowerCase()).join(", ")}.</div>}
67 {unusable.length > 0 && <div>Left out (no tear range or no sound above the background): {unusable.map((m) => speedName(m.label)).join(", ")}.</div>}
68 </div>
69 )}
71 <Summary rows={rows} />
73 <div className="grid2">
74 <section className="card">
75 <h3>Total sound energy vs tear duration</h3>
76 <p className="caption">If every tear contains the same clicks, the points should lie on a flat line.</p>
77 <Scatter rows={rows} y={energyOf} yFmt={fmtDb} yLabel="energy (dB, relative)" onOpen={onOpen} unit="dB" minSpan={10} />
78 </section>
79 <section className="card">
80 <div className="plot-head">
81 <h3>{METRICS[metric].label} vs tear duration</h3>
82 <select value={metric} onChange={(e) => setMetric(e.target.value as Metric)} aria-label="Quantity to plot">
83 {(Object.keys(METRICS) as Metric[]).map((k) => (
84 <option key={k} value={k}>
85 {METRICS[k].label}
86 </option>
87 ))}
88 </select>
89 </div>
90 <p className="caption">
91 {metric === "power"
92 ? "The same energy packed into less time: power should rise 10 dB for every 10× shorter tear (slope −10 dB)."
93 : "If the clicks are the same at every speed, this should not depend on duration."}
94 </p>
95 <Scatter rows={rows} y={METRICS[metric].get} yFmt={METRICS[metric].fmt} yLabel={METRICS[metric].axis} onOpen={onOpen} unit={METRICS[metric].unit} minSpan={METRICS[metric].minSpan} />
96 </section>
97 </div>
99 <section className="card">
100 <div className="plot-head">
101 <h3>Frequency makeup</h3>
102 <div className="toolbar">
103 <label>
104 <input type="checkbox" checked={normalize} onChange={(e) => setNormalize(e.target.checked)} /> compare shape only (scale each to the same total energy)
105 </label>
106 <label>
107 smoothing
108 <select value={smoothing} onChange={(e) => setSmoothing(+e.target.value)}>
109 <option value={1 / 12}>1/12 octave</option>
110 <option value={1 / 6}>1/6 octave</option>
111 <option value={1 / 3}>1/3 octave</option>
112 </select>
113 </label>
114 </div>
115 </div>
116 <p className="caption">
117 Energy spectrum of each tear, background removed.
118 {normalize
119 ? " Each curve is divided by its total energy, so only the shape is compared."
120 : " If tears at all speeds contain the same clicks, the curves should lie on top of each other."}
121 </p>
122 <SpectraOverlay rows={rows} normalize={normalize} smoothing={smoothing} settings={settings} />
123 </section>
125 <section className="card">
126 <div className="plot-head">
127 <h3>Numbers</h3>
128 <button onClick={() => exportCsv(rows, settings)} disabled={!rows.length}>
129 Download CSV
130 </button>
131 </div>
132 <Table rows={rows} onOpen={onOpen} />
133 </section>
134 </div>
135 );
136}
138// ---------- summary ----------
140function Summary({ rows }: { rows: Row[] }) {
141 if (rows.length < 2) return <div className="card muted">Record at least two speeds to compare them.</div>;
142 const lx = rows.map((r) => Math.log10(r.a.duration));
143 const e = rows.map((r) => db10(r.a.energy));
144 const fe = linearFit(lx, e);
145 const fm = linearFit(lx, rows.map((r) => r.a.medianFreq));
146 const span = Math.max(...rows.map((r) => r.a.duration)) / Math.min(...rows.map((r) => r.a.duration));
147 const eRange = Math.max(...e) - Math.min(...e);
148 const meds = rows.map((r) => r.a.medianFreq);
149 return (
150 <section className="card summary">
151 <h3>The two questions</h3>
152 <div className="q">
153 <div className="q-title">Same total energy at every speed?</div>
154 <div>
155 Across {rows.length} speeds the energy varies over a range of <b>{eRange.toFixed(1)} dB</b>.
156 {fe && (
157 <>
158 {" "}
159 The trend is <b>{fmtSigned(fe.b)} dB</b> per 10× longer tear (straight-line fit, ± {fe.seB.toFixed(2)} dB).
160 </>
161 )}
162 </div>
163 </div>
164 <div className="q">
165 <div className="q-title">Same frequency makeup at every speed?</div>
166 <div>
167 Median frequency ranges from <b>{fmtHz(Math.min(...meds))}</b> to <b>{fmtHz(Math.max(...meds))}</b>.
168 {fm && (
169 <>
170 {" "}
171 The trend is <b>{fmtSigned(fm.b, 0)} Hz</b> per 10× longer tear (± {fm.seB.toFixed(0)} Hz).
172 </>
173 )}{" "}
174 Compare the curve shapes below.
175 </div>
176 </div>
177 <p className="caption">
178 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.
179 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
180 ordinary variation from tear to tear.
181 {fe ? "" : " A trend line needs at least three speeds."}
182 </p>
183 </section>
184 );
185}
187function fmtSigned(v: number, digits = 2) {
188 return `${v >= 0 ? "+" : "−"}${Math.abs(v).toFixed(digits)}`;
189}
191// ---------- scatter ----------
193function Scatter({
194 rows,
195 y,
196 yFmt,
197 yLabel,
198 onOpen,
199 unit,
200 minSpan,
201}: {
202 rows: Row[];
203 y: (a: Analysis) => number;
204 yFmt: (v: number) => string;
205 yLabel: string;
206 onOpen: (id: string) => void;
207 unit: string;
208 minSpan: number;
209}) {
210 const pts = useMemo(() => rows.map((r) => ({ r, x: r.a.duration, y: y(r.a) })).filter((p) => Number.isFinite(p.y)), [rows, y]);
211 const xr = useMemo<[number, number]>(() => {
212 if (!pts.length) return [0.1, 20];
213 const lo = Math.min(...pts.map((p) => p.x));
214 const hi = Math.max(...pts.map((p) => p.x));
215 return [Math.min(lo / 1.5, 0.2), Math.max(hi * 1.5, 15)];
216 }, [pts]);
217 const yr = useMemo<[number, number]>(() => {
218 if (!pts.length) return [0, 1];
219 const lo = Math.min(...pts.map((p) => p.y));
220 const hi = Math.max(...pts.map((p) => p.y));
221 // keep a minimum span so tiny differences are not blown up to fill the plot
222 const mid = (lo + hi) / 2;
223 const half = Math.max((hi - lo) * 0.6, minSpan / 2);
224 return [mid - half, mid + half];
225 }, [pts, minSpan]);
226 const fit = useMemo(() => linearFit(pts.map((p) => Math.log10(p.x)), pts.map((p) => p.y)), [pts]);
228 const draw = useCallback(
229 (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
230 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]);
231 for (const p of pts) {
232 const st = speedStyle(p.r.meta.label);
233 drawMarker(ctx, s.x(p.x), s.y(p.y), st.shape, colorFor(st.slot, th.series, th.muted), th.surface, 6);
234 }
235 },
236 [pts, fit, xr],
237 );
239 const near = (p: PointerInfo) => {
240 let best: (typeof pts)[number] | null = null;
241 let bd = 14 * 14;
242 for (const q of pts) {
243 const d = (p.scales.x(q.x) - p.px) ** 2 + (p.scales.y(q.y) - p.py) ** 2;
244 if (d < bd) {
245 bd = d;
246 best = q;
247 }
248 }
249 return best;
250 };
252 return (
253 <>
254 <CanvasPlot
255 height={280}
256 xRange={xr}
257 xLog
258 yRange={yr}
259 xLabel="tear duration (s)"
260 yLabel={yLabel}
261 draw={draw}
262 hover={(p) => {
263 const q = near(p);
264 if (!q) return null;
265 return { lines: [speedName(q.r.meta.label), `${fmtSec(q.x)} · ${yFmt(q.y)}`, "click to open"], x: q.x, y: q.y };
266 }}
267 onClick={(p) => {
268 const q = near(p);
269 if (q) onOpen(q.r.meta.id);
270 }}
271 cursor={(p) => (near(p) ? "pointer" : "crosshair")}
272 ariaLabel={`${yLabel} against tear duration`}
273 />
274 <Legend rows={rows} extra={fit ? `dashed: trend, ${fmtSigned(fit.b, unit === "Hz" ? 0 : 2)} ${unit} per 10× duration` : undefined} />
275 </>
276 );
277}
279// ---------- spectra overlay ----------
281function SpectraOverlay({ rows, normalize, smoothing, settings }: { rows: Row[]; normalize: boolean; smoothing: number; settings: AnalysisSettings }) {
282 const fsMin = rows.length ? Math.min(...rows.map((r) => r.a.fs)) : 48000;
283 const fLo = Math.max(20, settings.bandLow);
284 const fHi = Math.min(settings.bandHigh, fsMin / 2);
286 const lines = useMemo(
287 () =>
288 rows.map((r) => {
289 const scale = normalize ? 1 / r.a.energy : 1;
290 const sm = smoothLog(r.a.freqs, r.a.netEsd.map((v) => v * scale), fLo, fHi, smoothing);
291 return { label: r.meta.label, f: sm.f, db: sm.v.map((v) => (v > 0 ? 10 * Math.log10(v) : NaN)) };
292 }),
293 [rows, normalize, smoothing, fLo, fHi],
294 );
296 const yr = useMemo<[number, number]>(() => {
297 const all = lines.flatMap((l) => l.db.filter(Number.isFinite));
298 if (!all.length) return [-100, 0];
299 const top = Math.max(...all);
300 return [Math.floor((top - 50) / 10) * 10, Math.ceil((top + 3) / 5) * 5];
301 }, [lines]);
303 const draw = useCallback(
304 (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
305 for (const l of lines) {
306 const st = speedStyle(l.label);
307 drawLine(ctx, s, l.f, l.db, colorFor(st.slot, th.series, th.muted), 2);
308 }
309 },
310 [lines],
311 );
313 return (
314 <>
315 <CanvasPlot
316 height={340}
317 xRange={[fLo, fHi]}
318 xLog
319 yRange={yr}
320 xLabel="frequency (Hz)"
321 yLabel={normalize ? "relative density (dB re 1/Hz)" : "energy density (dB re FS²·s/Hz)"}
322 draw={draw}
323 hover={(p) => {
324 if (!lines.length) return null;
325 const f = lines[0].f;
326 let i = 0;
327 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;
328 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] };
329 }}
330 ariaLabel="Energy spectra of the tears, overlaid"
331 />
332 <Legend rows={rows} lines />
333 </>
334 );
335}
337// ---------- legend & table ----------
339function MarkerIcon({ shape, color, line }: { shape: MarkerShape; color: string; line?: boolean }) {
340 if (line)
341 return (
342 <svg width="18" height="10" aria-hidden>
343 <line x1="1" y1="5" x2="17" y2="5" stroke={color} strokeWidth="2.5" strokeLinecap="round" />
344 </svg>
345 );
346 const d: Record<MarkerShape, string> = {
347 circle: "M9,4 a5,5 0 1,0 0.01,0",
348 square: "M4.5,4.5 h9 v9 h-9 z",
349 triangle: "M9,3.5 L14.2,13 L3.8,13 z",
350 diamond: "M9,2.8 L14.2,9 L9,15.2 L3.8,9 z",
351 cross: "M7,4 h4 v3 h3 v4 h-3 v3 h-4 v-3 h-3 v-4 h3 z",
352 };
353 return (
354 <svg width="18" height="18" aria-hidden>
355 <path d={d[shape]} fill={color} />
356 </svg>
357 );
358}
360function Legend({ rows, lines, extra }: { rows: Row[]; lines?: boolean; extra?: string }) {
361 const th = readTheme(document.documentElement);
362 return (
363 <div className="legend">
364 {rows.map((r) => {
365 const st = speedStyle(r.meta.label);
366 return (
367 <span key={r.meta.id}>
368 <MarkerIcon shape={st.shape} color={colorFor(st.slot, th.series, th.muted)} line={lines} /> {speedName(r.meta.label)}
369 </span>
370 );
371 })}
372 {extra && <span className="muted">{extra}</span>}
373 </div>
374 );
375}
377function Table({ rows, onOpen }: { rows: Row[]; onOpen: (id: string) => void }) {
378 const th = readTheme(document.documentElement);
379 return (
380 <div className="table-wrap">
381 <table>
382 <thead>
383 <tr>
384 <th>Speed</th>
385 <th className="num">Tear duration</th>
386 <th className="num">Speed (in/s)</th>
387 <th className="num">Energy (dB)</th>
388 <th className="num">Mean power (dBFS)</th>
389 <th className="num">Median freq</th>
390 <th className="num">Centroid</th>
391 <th className="num">Above background</th>
392 <th className="num">Peak (dBFS)</th>
393 </tr>
394 </thead>
395 <tbody>
396 {rows.map(({ meta, a }) => {
397 const st = speedStyle(meta.label);
398 return (
399 <tr key={meta.id} className="clickable" onClick={() => onOpen(meta.id)} title="Open on the Record tab">
400 <td>
401 <MarkerIcon shape={st.shape} color={colorFor(st.slot, th.series, th.muted)} /> {speedName(meta.label)}
402 </td>
403 <td className="num">{fmtSec(a.duration)}</td>
404 <td className="num">{a.speedInPerSec.toFixed(2)}</td>
405 <td className="num">{db10(a.energy).toFixed(1)}</td>
406 <td className="num">{db10(a.energy / a.duration).toFixed(1)}</td>
407 <td className="num">{fmtHz(a.medianFreq)}</td>
408 <td className="num">{fmtHz(a.centroid)}</td>
409 <td className="num">{Number.isFinite(a.snrDb) ? `${a.snrDb.toFixed(1)} dB` : "–"}</td>
410 <td className="num">
411 {a.peakDbfs.toFixed(1)}
412 {a.nearClip > 0 ? " ⚠ clipped" : ""}
413 </td>
414 </tr>
415 );
416 })}
417 </tbody>
418 </table>
419 </div>
420 );
421}
423function exportCsv(rows: Row[], settings: AnalysisSettings) {
424 const head = [
425 "speed", "recorded", "source", "sample_rate", "tear_start_s", "tear_end_s", "range_set_by_hand", "duration_s", "speed_in_per_s",
426 "energy_db", "energy_raw_db", "background_db", "above_background_db", "median_hz", "centroid_hz", "f10_hz", "f90_hz", "peak_dbfs", "near_clip_samples",
427 "band_low_hz", "band_high_hz", "sheet_length_in",
428 ];
429 const q = (v: unknown) => {
430 const s = String(v ?? "");
431 return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
432 };
433 const lines = [head.join(",")];
434 for (const { meta: m, a } of rows) {
435 lines.push(
436 [
437 m.label, new Date(m.createdAt).toISOString(), m.source, m.sampleRate, a.segment.start.toFixed(4), a.segment.end.toFixed(4), m.segmentManual,
438 a.duration.toFixed(4), a.speedInPerSec.toFixed(4), db10(a.energy).toFixed(3), db10(a.energyRaw).toFixed(3), db10(a.energyNoise).toFixed(3),
439 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,
440 settings.bandLow, settings.bandHigh, settings.sheetLengthIn,
441 ]
442 .map(q)
443 .join(","),
444 );
445 }
446 download(new Blob([lines.join("\n")], { type: "text/csv" }), `rip-sound-summary-${new Date().toISOString().slice(0, 10)}.csv`);
447}