/ magland / rip-sound-analyzer
Sign in
magland / rip-sound-analyzer
rip-sound-analyzer / src / components / CompareView.tsx
443 lines · 16.8 KBBlameHistoryRaw
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;
13interface Row {
14 meta: RecordingMeta;
15 a: Analysis;
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 fmtDb = (v: number) => `${v.toFixed(1)} dB`;
24export function CompareView({ recs, settings, onOpen }: Props) {
25 const [rows, setRows] = useState<Row[]>([]);
26 const [ready, setReady] = useState(false);
27 const [normalize, setNormalize] = useState(false);
28 const [smoothing, setSmoothing] = useState(1 / 6);
30 useEffect(() => {
31 let live = true;
32 setReady(false);
33 (async () => {
34 const out: Row[] = [];
35 for (const m of recs) {
36 const a = await getAnalysis(m, settings);
37 if (!live) return;
38 if (a && a.energy > 0) out.push({ meta: m, a });
39 await new Promise((r) => setTimeout(r, 0));
40 }
41 if (live) {
42 setRows(out);
43 setReady(true);
44 }
45 })();
46 return () => {
47 live = false;
48 };
49 }, [recs, settings]);
51 const bandLabel = `${+(settings.energyLow / 1000).toFixed(2)}–${+(settings.energyHigh / 1000).toFixed(2)} kHz`;
52 const missing = SPEEDS.filter((s) => !recs.some((r) => r.label === s.id));
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 a tear at two or more speeds on the Record tab.</div>;
56 if (!ready) return <div className="card muted">Analysing…</div>;
58 return (
59 <div className="compare">
60 {(missing.length > 0 || unusable.length > 0) && (
61 <div className="card muted small">
62 {missing.length > 0 && <div>Not recorded yet: {missing.map((s) => s.name.toLowerCase()).join(", ")}.</div>}
63 {unusable.length > 0 && <div>Left out (no tear range or no sound above the background): {unusable.map((m) => speedName(m.label)).join(", ")}.</div>}
64 </div>
65 )}
67 <Summary rows={rows} bandLabel={bandLabel} />
69 <div className="grid2">
70 <section className="card">
71 <h3>Total sound energy ({bandLabel}) vs tear duration</h3>
72 <p className="caption">If every tear contains the same clicks, the points should lie on a flat line.</p>
73 <Scatter rows={rows} y={energyOf} yFmt={fmtDb} yLabel="energy (dB, relative)" onOpen={onOpen} unit="dB" minSpan={10} />
74 </section>
75 <section className="card">
76 <h3>Loudness ({bandLabel}) vs tear duration</h3>
77 <p className="caption">
78 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.
79 </p>
80 <Scatter rows={rows} y={powerOf} yFmt={fmtDbfs} yLabel="mean power (dBFS)" onOpen={onOpen} unit="dB" minSpan={10} expectSlope={-10} />
81 </section>
82 </div>
84 <section className="card">
85 <div className="plot-head">
86 <h3>Frequency makeup</h3>
87 <div className="toolbar">
88 <label>
89 <input type="checkbox" checked={normalize} onChange={(e) => setNormalize(e.target.checked)} /> compare shape only (scale each to the same total energy)
90 </label>
91 <label>
92 smoothing
93 <select value={smoothing} onChange={(e) => setSmoothing(+e.target.value)}>
94 <option value={1 / 12}>1/12 octave</option>
95 <option value={1 / 6}>1/6 octave</option>
96 <option value={1 / 3}>1/3 octave</option>
97 </select>
98 </label>
99 </div>
100 </div>
101 <p className="caption">
102 Energy spectrum of each tear, background removed.
103 {normalize
104 ? " Each curve is divided by its total energy over the plotted range, so only the shape is compared."
105 : " If tears at all speeds contain the same clicks, the curves should lie on top of each other."}
106 </p>
107 <SpectraOverlay rows={rows} normalize={normalize} smoothing={smoothing} settings={settings} />
108 </section>
110 <section className="card">
111 <div className="plot-head">
112 <h3>Numbers</h3>
113 <button onClick={() => exportCsv(rows, settings)} disabled={!rows.length}>
114 Download CSV
115 </button>
116 </div>
117 <Table rows={rows} onOpen={onOpen} />
118 </section>
119 </div>
120 );
123// ---------- summary ----------
125function Summary({ rows, bandLabel }: { rows: Row[]; bandLabel: string }) {
126 if (rows.length < 2) return <div className="card muted">Record at least two speeds to compare them.</div>;
127 const lx = rows.map((r) => Math.log10(r.a.duration));
128 const e = rows.map((r) => db10(r.a.energy));
129 const fe = linearFit(lx, e);
130 const span = Math.max(...rows.map((r) => r.a.duration)) / Math.min(...rows.map((r) => r.a.duration));
131 const eRange = Math.max(...e) - Math.min(...e);
132 return (
133 <section className="card summary">
134 <h3>The two questions</h3>
135 <div className="q">
136 <div className="q-title">Same total energy at every speed?</div>
137 <div>
138 Across {rows.length} speeds the energy in {bandLabel} varies over a range of <b>{eRange.toFixed(1)} dB</b>.
139 {fe && (
140 <>
141 {" "}
142 The trend is <b>{fmtSigned(fe.b)} dB</b> per 10× longer tear (straight-line fit, ± {fe.seB.toFixed(2)} dB).
143 </>
144 )}
145 </div>
146 </div>
147 <div className="q">
148 <div className="q-title">Same frequency makeup at every speed?</div>
149 <div>
150 See the frequency plot below. If the curves for different speeds have the same shape (tick “compare shape only” to line them up), the
151 frequency makeup is the same.
152 </div>
153 </div>
154 <p className="caption">
155 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.
156 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
157 ordinary variation from tear to tear.
158 {fe ? "" : " A trend line needs at least three speeds."}
159 </p>
160 </section>
161 );
164function fmtSigned(v: number, digits = 2) {
165 return `${v >= 0 ? "+" : "−"}${Math.abs(v).toFixed(digits)}`;
168// ---------- scatter ----------
170function Scatter({
171 rows,
172 y,
173 yFmt,
174 yLabel,
175 onOpen,
176 unit,
177 minSpan,
178 expectSlope,
179}: {
180 expectSlope?: number; // dB per 10× duration: draws the expected trend through the points' mean
181 rows: Row[];
182 y: (a: Analysis) => number;
183 yFmt: (v: number) => string;
184 yLabel: string;
185 onOpen: (id: string) => void;
186 unit: string;
187 minSpan: number;
188}) {
189 const pts = useMemo(() => rows.map((r) => ({ r, x: r.a.duration, y: y(r.a) })).filter((p) => Number.isFinite(p.y)), [rows, y]);
190 const xr = useMemo<[number, number]>(() => {
191 if (!pts.length) return [0.1, 20];
192 const lo = Math.min(...pts.map((p) => p.x));
193 const hi = Math.max(...pts.map((p) => p.x));
194 return [Math.min(lo / 1.5, 0.2), Math.max(hi * 1.5, 15)];
195 }, [pts]);
196 const yr = useMemo<[number, number]>(() => {
197 if (!pts.length) return [0, 1];
198 const lo = Math.min(...pts.map((p) => p.y));
199 const hi = Math.max(...pts.map((p) => p.y));
200 // keep a minimum span so tiny differences are not blown up to fill the plot
201 const mid = (lo + hi) / 2;
202 const half = Math.max((hi - lo) * 0.6, minSpan / 2);
203 return [mid - half, mid + half];
204 }, [pts, minSpan]);
205 const fit = useMemo(() => linearFit(pts.map((p) => Math.log10(p.x)), pts.map((p) => p.y)), [pts]);
207 const draw = useCallback(
208 (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
209 if (expectSlope !== undefined && pts.length) {
210 const mx = pts.reduce((t, p) => t + Math.log10(p.x), 0) / pts.length;
211 const my = pts.reduce((t, p) => t + p.y, 0) / pts.length;
212 const yAt = (x: number) => my + expectSlope * (Math.log10(x) - mx);
213 drawLine(ctx, s, [xr[0], xr[1]], [yAt(xr[0]), yAt(xr[1])], th.ink2, 1.5, [2, 4]);
214 }
215 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]);
216 for (const p of pts) {
217 const st = speedStyle(p.r.meta.label);
218 drawMarker(ctx, s.x(p.x), s.y(p.y), st.shape, colorFor(st.slot, th.series, th.muted), th.surface, 6);
219 }
220 },
221 [pts, fit, xr, expectSlope],
222 );
224 const near = (p: PointerInfo) => {
225 let best: (typeof pts)[number] | null = null;
226 let bd = 14 * 14;
227 for (const q of pts) {
228 const d = (p.scales.x(q.x) - p.px) ** 2 + (p.scales.y(q.y) - p.py) ** 2;
229 if (d < bd) {
230 bd = d;
231 best = q;
232 }
233 }
234 return best;
235 };
237 return (
238 <>
239 <CanvasPlot
240 height={280}
241 xRange={xr}
242 xLog
243 yRange={yr}
244 xLabel="tear duration (s)"
245 yLabel={yLabel}
246 draw={draw}
247 hover={(p) => {
248 const q = near(p);
249 if (!q) return null;
250 return { lines: [speedName(q.r.meta.label), `${fmtSec(q.x)} · ${yFmt(q.y)}`, "click to open"], x: q.x, y: q.y };
251 }}
252 onClick={(p) => {
253 const q = near(p);
254 if (q) onOpen(q.r.meta.id);
255 }}
256 cursor={(p) => (near(p) ? "pointer" : "crosshair")}
257 ariaLabel={`${yLabel} against tear duration`}
258 />
259 <Legend
260 rows={rows}
261 extra={[
262 fit ? `dashed: trend, ${fmtSigned(fit.b)} ${unit} per 10× duration` : "",
263 expectSlope !== undefined ? `dotted: expected if energy is the same (${fmtSigned(expectSlope, 0)} ${unit} per 10×)` : "",
264 ]
265 .filter(Boolean)
266 .join(" · ") || undefined}
267 />
268 </>
269 );
272// ---------- spectra overlay ----------
274function SpectraOverlay({ rows, normalize, smoothing, settings }: { rows: Row[]; normalize: boolean; smoothing: number; settings: AnalysisSettings }) {
275 const fsMin = rows.length ? Math.min(...rows.map((r) => r.a.fs)) : 48000;
276 const fLo = Math.max(20, settings.shapeLow);
277 const fHi = Math.min(settings.shapeHigh, fsMin / 2);
279 const lines = useMemo(
280 () =>
281 rows.map((r) => {
282 const scale = normalize ? 1 / r.a.shapeEnergy : 1;
283 const sm = smoothLog(r.a.freqs, r.a.netEsd.map((v) => v * scale), fLo, fHi, smoothing);
284 return { label: r.meta.label, f: sm.f, db: sm.v.map((v) => (v > 0 ? 10 * Math.log10(v) : NaN)) };
285 }),
286 [rows, normalize, smoothing, fLo, fHi],
287 );
289 const yr = useMemo<[number, number]>(() => {
290 const all = lines.flatMap((l) => l.db.filter(Number.isFinite));
291 if (!all.length) return [-100, 0];
292 const top = Math.max(...all);
293 return [Math.floor((top - 50) / 10) * 10, Math.ceil((top + 3) / 5) * 5];
294 }, [lines]);
296 const draw = useCallback(
297 (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
298 if (!normalize) {
299 // mark the energy band
300 ctx.fillStyle = th.seg;
301 const bl = s.x(Math.max(settings.energyLow, fLo));
302 const bh = s.x(Math.min(settings.energyHigh, fHi));
303 if (bh > bl) ctx.fillRect(bl, s.top, bh - bl, s.bottom - s.top);
304 }
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, normalize, settings, fLo, fHi],
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 extra={normalize ? undefined : "shaded: energy band"} />
333 </>
334 );
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 );
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 );
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">Above background</th>
390 <th className="num">Peak (dBFS)</th>
391 </tr>
392 </thead>
393 <tbody>
394 {rows.map(({ meta, a }) => {
395 const st = speedStyle(meta.label);
396 return (
397 <tr key={meta.id} className="clickable" onClick={() => onOpen(meta.id)} title="Open on the Record tab">
398 <td>
399 <MarkerIcon shape={st.shape} color={colorFor(st.slot, th.series, th.muted)} /> {speedName(meta.label)}
400 </td>
401 <td className="num">{fmtSec(a.duration)}</td>
402 <td className="num">{a.speedInPerSec.toFixed(2)}</td>
403 <td className="num">{db10(a.energy).toFixed(1)}</td>
404 <td className="num">{db10(a.energy / a.duration).toFixed(1)}</td>
405 <td className="num">{Number.isFinite(a.snrDb) ? `${a.snrDb.toFixed(1)} dB` : "–"}</td>
406 <td className="num">
407 {a.peakDbfs.toFixed(1)}
408 {a.nearClip > 0 ? " ⚠ clipped" : ""}
409 </td>
410 </tr>
411 );
412 })}
413 </tbody>
414 </table>
415 </div>
416 );
419function exportCsv(rows: Row[], settings: AnalysisSettings) {
420 const head = [
421 "speed", "recorded", "source", "sample_rate", "tear_start_s", "tear_end_s", "range_set_by_hand", "duration_s", "speed_in_per_s",
422 "energy_db", "energy_raw_db", "background_db", "above_background_db", "peak_dbfs", "near_clip_samples",
423 "energy_band_low_hz", "energy_band_high_hz", "spectrum_band_low_hz", "spectrum_band_high_hz", "sheet_length_in",
424 ];
425 const q = (v: unknown) => {
426 const s = String(v ?? "");
427 return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
428 };
429 const lines = [head.join(",")];
430 for (const { meta: m, a } of rows) {
431 lines.push(
432 [
433 m.label, new Date(m.createdAt).toISOString(), m.source, m.sampleRate, a.segment.start.toFixed(4), a.segment.end.toFixed(4), m.segmentManual,
434 a.duration.toFixed(4), a.speedInPerSec.toFixed(4), db10(a.energy).toFixed(3), db10(a.energyRaw).toFixed(3), db10(a.energyNoise).toFixed(3),
435 a.snrDb.toFixed(2), a.peakDbfs.toFixed(2), a.nearClip,
436 settings.energyLow, settings.energyHigh, settings.shapeLow, settings.shapeHigh, settings.sheetLengthIn,
437 ]
438 .map(q)
439 .join(","),
440 );
441 }
442 download(new Blob([lines.join("\n")], { type: "text/csv" }), `rip-sound-summary-${new Date().toISOString().slice(0, 10)}.csv`);
↑↓ move↵openescclose