1import { useCallback, useEffect, useMemo, useState } from "react";
2import { CanvasPlot, drawLine, drawMarker, readTheme, 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 { db10, download, durationColor, fmtDate, fmtHz, fmtSec, getAnalysis, linearFit, sampleTitle } from "../model.ts";
7interface Props {
8 recs: RecordingMeta[]; // all samples, slowest first
9 settings: AnalysisSettings;
10 onOpen: (id: string) => void;
11}
13interface Row {
14 meta: RecordingMeta;
15 a: Analysis;
16}
18const powerOf = (a: Analysis) => db10(a.energy / a.duration);
19const fmtDbfs = (v: number) => `${v.toFixed(1)} dBFS`;
21const energyOf = (a: Analysis) => db10(a.energy);
22const rowName = (r: Row) => `${fmtSec(r.a.duration)} tear${r.meta.label ? ` · ${r.meta.label}` : ""}`;
23const fmtDb = (v: number) => `${v.toFixed(1)} dB`;
25export function CompareView({ recs, settings, onOpen }: Props) {
26 const [rows, setRows] = useState<Row[]>([]);
27 const [ready, setReady] = useState(false);
28 const [normalize, setNormalize] = useState(false);
29 const [smoothing, setSmoothing] = useState(1 / 6);
31 useEffect(() => {
32 let live = true;
33 setReady(false);
34 (async () => {
35 const out: Row[] = [];
36 for (const m of recs) {
37 const a = await getAnalysis(m, settings);
38 if (!live) return;
39 if (a && a.energy > 0) out.push({ meta: m, a });
40 await new Promise((r) => setTimeout(r, 0));
41 }
42 if (live) {
43 setRows(out.sort((p, q) => q.a.duration - p.a.duration));
44 setReady(true);
45 }
46 })();
47 return () => {
48 live = false;
49 };
50 }, [recs, settings]);
52 const bandLabel = `${+(settings.energyLow / 1000).toFixed(2)}–${+(settings.energyHigh / 1000).toFixed(2)} kHz`;
53 const unusable = recs.filter((m) => !rows.some((r) => r.meta.id === m.id));
55 if (!recs.length) return <div className="card empty">Nothing to compare yet. Record tears at a few different speeds on the Record tab.</div>;
56 if (!ready) return <div className="card muted">Analysing…</div>;
58 return (
59 <div className="compare">
60 {unusable.length > 0 && (
61 <div className="card muted small">
62 Left out (no tear range or no sound above the background): {unusable.map((m) => m.label || `${sampleTitle(m)}, ${fmtDate(m.createdAt)}`).join("; ")}.
63 </div>
64 )}
66 <Summary rows={rows} bandLabel={bandLabel} />
68 <div className="grid2">
69 <section className="card">
70 <h3>Total sound energy ({bandLabel}) vs tear duration</h3>
71 <p className="caption">If every tear contains the same clicks, the points should lie on a flat line.</p>
72 <Scatter rows={rows} y={energyOf} yFmt={fmtDb} yLabel="energy (dB, relative)" onOpen={onOpen} unit="dB" minSpan={10} />
73 </section>
74 <section className="card">
75 <h3>Loudness ({bandLabel}) vs tear duration</h3>
76 <p className="caption">
77 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.
78 </p>
79 <Scatter rows={rows} y={powerOf} yFmt={fmtDbfs} yLabel="mean power (dBFS)" onOpen={onOpen} unit="dB" minSpan={10} expectSlope={-10} />
80 </section>
81 </div>
83 <section className="card">
84 <div className="plot-head">
85 <h3>Frequency makeup</h3>
86 <div className="toolbar">
87 <label>
88 <input type="checkbox" checked={normalize} onChange={(e) => setNormalize(e.target.checked)} /> compare shape only (scale each to the same total energy)
89 </label>
90 <label>
91 smoothing
92 <select value={smoothing} onChange={(e) => setSmoothing(+e.target.value)}>
93 <option value={1 / 12}>1/12 octave</option>
94 <option value={1 / 6}>1/6 octave</option>
95 <option value={1 / 3}>1/3 octave</option>
96 </select>
97 </label>
98 </div>
99 </div>
100 <p className="caption">
101 Energy spectrum of each tear, background removed.
102 {normalize
103 ? " Each curve is divided by its total energy over the plotted range, so only the shape is compared."
104 : " If tears at all speeds contain the same clicks, the curves should lie on top of each other."}
105 </p>
106 <SpectraOverlay rows={rows} normalize={normalize} smoothing={smoothing} settings={settings} />
107 </section>
109 <section className="card">
110 <div className="plot-head">
111 <h3>Numbers</h3>
112 <button onClick={() => exportCsv(rows, settings)} disabled={!rows.length}>
113 Download CSV
114 </button>
115 </div>
116 <Table rows={rows} onOpen={onOpen} />
117 </section>
118 </div>
119 );
120}
122// ---------- summary ----------
124function Summary({ rows, bandLabel }: { rows: Row[]; bandLabel: string }) {
125 if (rows.length < 2) return <div className="card muted">Record at least two samples at different speeds to compare them.</div>;
126 const lx = rows.map((r) => Math.log10(r.a.duration));
127 const e = rows.map((r) => db10(r.a.energy));
128 const fe = linearFit(lx, e);
129 const span = Math.max(...rows.map((r) => r.a.duration)) / Math.min(...rows.map((r) => r.a.duration));
130 const eRange = Math.max(...e) - Math.min(...e);
131 return (
132 <section className="card summary">
133 <h3>The two questions</h3>
134 <div className="q">
135 <div className="q-title">Same total energy at every speed?</div>
136 <div>
137 Across {rows.length} samples the energy in {bandLabel} varies over a range of <b>{eRange.toFixed(1)} dB</b>.
138 {fe && (
139 <>
140 {" "}
141 The trend is <b>{fmtSigned(fe.b)} dB</b> per 10× longer tear (straight-line fit, ± {fe.seB.toFixed(2)} dB).
142 </>
143 )}
144 </div>
145 </div>
146 <div className="q">
147 <div className="q-title">Same frequency makeup at every speed?</div>
148 <div>
149 See the frequency plot below. If the curves for different speeds have the same shape (tick “compare shape only” to line them up), the
150 frequency makeup is the same.
151 </div>
152 </div>
153 <p className="caption">
154 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
155 mean anything.
156 {fe ? "" : " A trend line needs at least three samples."}
157 </p>
158 </section>
159 );
160}
162function fmtSigned(v: number, digits = 2) {
163 return `${v >= 0 ? "+" : "−"}${Math.abs(v).toFixed(digits)}`;
164}
166// ---------- scatter ----------
168function Scatter({
169 rows,
170 y,
171 yFmt,
172 yLabel,
173 onOpen,
174 unit,
175 minSpan,
176 expectSlope,
177}: {
178 expectSlope?: number; // dB per 10× duration: draws the expected trend through the points' mean
179 rows: Row[];
180 y: (a: Analysis) => number;
181 yFmt: (v: number) => string;
182 yLabel: string;
183 onOpen: (id: string) => void;
184 unit: string;
185 minSpan: number;
186}) {
187 const pts = useMemo(() => rows.map((r) => ({ r, x: r.a.duration, y: y(r.a) })).filter((p) => Number.isFinite(p.y)), [rows, y]);
188 const xr = useMemo<[number, number]>(() => {
189 if (!pts.length) return [0.1, 20];
190 const lo = Math.min(...pts.map((p) => p.x));
191 const hi = Math.max(...pts.map((p) => p.x));
192 return [Math.min(lo / 1.5, 0.2), Math.max(hi * 1.5, 15)];
193 }, [pts]);
194 const yr = useMemo<[number, number]>(() => {
195 if (!pts.length) return [0, 1];
196 const lo = Math.min(...pts.map((p) => p.y));
197 const hi = Math.max(...pts.map((p) => p.y));
198 // keep a minimum span so tiny differences are not blown up to fill the plot
199 const mid = (lo + hi) / 2;
200 const half = Math.max((hi - lo) * 0.6, minSpan / 2);
201 return [mid - half, mid + half];
202 }, [pts, minSpan]);
203 const fit = useMemo(() => linearFit(pts.map((p) => Math.log10(p.x)), pts.map((p) => p.y)), [pts]);
205 const draw = useCallback(
206 (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
207 if (expectSlope !== undefined && pts.length) {
208 const mx = pts.reduce((t, p) => t + Math.log10(p.x), 0) / pts.length;
209 const my = pts.reduce((t, p) => t + p.y, 0) / pts.length;
210 const yAt = (x: number) => my + expectSlope * (Math.log10(x) - mx);
211 drawLine(ctx, s, [xr[0], xr[1]], [yAt(xr[0]), yAt(xr[1])], th.ink2, 1.5, [2, 4]);
212 }
213 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]);
214 for (const p of pts) drawMarker(ctx, s.x(p.x), s.y(p.y), "circle", durationColor(p.x, th), th.surface, 6);
215 },
216 [pts, fit, xr, expectSlope],
217 );
219 const near = (p: PointerInfo) => {
220 let best: (typeof pts)[number] | null = null;
221 let bd = 14 * 14;
222 for (const q of pts) {
223 const d = (p.scales.x(q.x) - p.px) ** 2 + (p.scales.y(q.y) - p.py) ** 2;
224 if (d < bd) {
225 bd = d;
226 best = q;
227 }
228 }
229 return best;
230 };
232 return (
233 <>
234 <CanvasPlot
235 height={280}
236 xRange={xr}
237 xLog
238 yRange={yr}
239 xLabel="tear duration (s)"
240 yLabel={yLabel}
241 draw={draw}
242 hover={(p) => {
243 const q = near(p);
244 if (!q) return null;
245 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 };
246 }}
247 onClick={(p) => {
248 const q = near(p);
249 if (q) onOpen(q.r.meta.id);
250 }}
251 cursor={(p) => (near(p) ? "pointer" : "crosshair")}
252 ariaLabel={`${yLabel} against tear duration`}
253 />
254 <Legend
255 rows={rows}
256 extra={[
257 fit ? `dashed: trend, ${fmtSigned(fit.b)} ${unit} per 10× duration` : "",
258 expectSlope !== undefined ? `dotted: expected if energy is the same (${fmtSigned(expectSlope, 0)} ${unit} per 10×)` : "",
259 ]
260 .filter(Boolean)
261 .join(" · ") || undefined}
262 />
263 </>
264 );
265}
267// ---------- spectra overlay ----------
269function SpectraOverlay({ rows, normalize, smoothing, settings }: { rows: Row[]; normalize: boolean; smoothing: number; settings: AnalysisSettings }) {
270 const fsMin = rows.length ? Math.min(...rows.map((r) => r.a.fs)) : 48000;
271 const fLo = Math.max(20, settings.shapeLow);
272 const fHi = Math.min(settings.shapeHigh, fsMin / 2);
274 const lines = useMemo(
275 () =>
276 rows.map((r) => {
277 const scale = normalize ? 1 / r.a.shapeEnergy : 1;
278 const sm = smoothLog(r.a.freqs, r.a.netEsd.map((v) => v * scale), fLo, fHi, smoothing);
279 return { name: rowName(r), dur: r.a.duration, f: sm.f, db: sm.v.map((v) => (v > 0 ? 10 * Math.log10(v) : NaN)) };
280 }),
281 [rows, normalize, smoothing, fLo, fHi],
282 );
284 const yr = useMemo<[number, number]>(() => {
285 const all = lines.flatMap((l) => l.db.filter(Number.isFinite));
286 if (!all.length) return [-100, 0];
287 const top = Math.max(...all);
288 return [Math.floor((top - 50) / 10) * 10, Math.ceil((top + 3) / 5) * 5];
289 }, [lines]);
291 const draw = useCallback(
292 (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
293 if (!normalize) {
294 // mark the energy band
295 ctx.fillStyle = th.seg;
296 const bl = s.x(Math.max(settings.energyLow, fLo));
297 const bh = s.x(Math.min(settings.energyHigh, fHi));
298 if (bh > bl) ctx.fillRect(bl, s.top, bh - bl, s.bottom - s.top);
299 }
300 // slowest first, so the fastest (strongest colour) are drawn on top
301 for (const l of lines) drawLine(ctx, s, l.f, l.db, durationColor(l.dur, th), 2);
302 },
303 [lines, normalize, settings, fLo, fHi],
304 );
306 return (
307 <>
308 <CanvasPlot
309 height={340}
310 xRange={[fLo, fHi]}
311 xLog
312 yRange={yr}
313 xLabel="frequency (Hz)"
314 yLabel={normalize ? "relative density (dB re 1/Hz)" : "energy density (dB re FS²·s/Hz)"}
315 draw={draw}
316 hover={(p) => {
317 if (!lines.length) return null;
318 const f = lines[0].f;
319 let i = 0;
320 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;
321 return { lines: [fmtHz(f[i]), ...lines.map((l) => `${l.name}: ${Number.isFinite(l.db[i]) ? l.db[i].toFixed(1) : "–"} dB`)], x: f[i] };
322 }}
323 ariaLabel="Energy spectra of the tears, overlaid"
324 />
325 <Legend rows={rows} lines extra={normalize ? undefined : "shaded: energy band"} />
326 </>
327 );
328}
330// ---------- legend & table ----------
332function Swatch({ color, line }: { color: string; line?: boolean }) {
333 return line ? (
334 <svg width="18" height="10" aria-hidden>
335 <line x1="1" y1="5" x2="17" y2="5" stroke={color} strokeWidth="2.5" strokeLinecap="round" />
336 </svg>
337 ) : (
338 <svg width="14" height="14" aria-hidden>
339 <circle cx="7" cy="7" r="5" fill={color} />
340 </svg>
341 );
342}
344function Legend({ rows, lines, extra }: { rows: Row[]; lines?: boolean; extra?: string }) {
345 const th = readTheme(document.documentElement);
346 return (
347 <div className="legend">
348 <span className="muted">Colour = tear duration (stronger = faster):</span>
349 {rows.map((r) => (
350 <span key={r.meta.id}>
351 <Swatch color={durationColor(r.a.duration, th)} line={lines} /> {rowName(r)}
352 </span>
353 ))}
354 {extra && <span className="muted">{extra}</span>}
355 </div>
356 );
357}
359function Table({ rows, onOpen }: { rows: Row[]; onOpen: (id: string) => void }) {
360 const th = readTheme(document.documentElement);
361 return (
362 <div className="table-wrap">
363 <table>
364 <thead>
365 <tr>
366 <th>Sample</th>
367 <th className="num">Tear duration</th>
368 <th className="num">Speed (in/s)</th>
369 <th className="num">Energy (dB)</th>
370 <th className="num">Mean power (dBFS)</th>
371 <th className="num">Above background</th>
372 <th className="num">Peak (dBFS)</th>
373 </tr>
374 </thead>
375 <tbody>
376 {rows.map(({ meta, a }) => {
377 return (
378 <tr key={meta.id} className="clickable" onClick={() => onOpen(meta.id)} title="Open on the Record tab">
379 <td>
380 <Swatch color={durationColor(a.duration, th)} /> {meta.label || fmtDate(meta.createdAt)}
381 </td>
382 <td className="num">{fmtSec(a.duration)}</td>
383 <td className="num">{a.speedInPerSec.toFixed(2)}</td>
384 <td className="num">{db10(a.energy).toFixed(1)}</td>
385 <td className="num">{db10(a.energy / a.duration).toFixed(1)}</td>
386 <td className="num">{Number.isFinite(a.snrDb) ? `${a.snrDb.toFixed(1)} dB` : "–"}</td>
387 <td className="num">
388 {a.peakDbfs.toFixed(1)}
389 {a.nearClip > 0 ? " ⚠ clipped" : ""}
390 </td>
391 </tr>
392 );
393 })}
394 </tbody>
395 </table>
396 </div>
397 );
398}
400function exportCsv(rows: Row[], settings: AnalysisSettings) {
401 const head = [
402 "name", "notes", "recorded", "source", "sample_rate", "tear_start_s", "tear_end_s", "range_set_by_hand", "duration_s", "speed_in_per_s",
403 "energy_db", "energy_raw_db", "background_db", "above_background_db", "peak_dbfs", "near_clip_samples",
404 "energy_band_low_hz", "energy_band_high_hz", "spectrum_band_low_hz", "spectrum_band_high_hz", "sheet_length_in",
405 ];
406 const q = (v: unknown) => {
407 const s = String(v ?? "");
408 return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
409 };
410 const lines = [head.join(",")];
411 for (const { meta: m, a } of rows) {
412 lines.push(
413 [
414 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,
415 a.duration.toFixed(4), a.speedInPerSec.toFixed(4), db10(a.energy).toFixed(3), db10(a.energyRaw).toFixed(3), db10(a.energyNoise).toFixed(3),
416 a.snrDb.toFixed(2), a.peakDbfs.toFixed(2), a.nearClip,
417 settings.energyLow, settings.energyHigh, settings.shapeLow, settings.shapeHigh, settings.sheetLengthIn,
418 ]
419 .map(q)
420 .join(","),
421 );
422 }
423 download(new Blob([lines.join("\n")], { type: "text/csv" }), `rip-sound-summary-${new Date().toISOString().slice(0, 10)}.csv`);
424}