/ magland / rip-sound-analyzer
Sign in
magland / rip-sound-analyzer
Record tab organised around five fixed speeds, one tear each
Per-speed page: record / re-record / delete, tear range drawn by dragging (with handles and numeric inputs), playback with playhead, close-up with zoom buttons, spectrum. Compare simplified to one tear per speed.
Jeremy Magland <jmagland@flatironinstitute.org> committed commit d8b88de2298b parent d0a8b32 Browse files
13 changed files+1345−1221
README.mdmodified+6−4View file
@@ -24,10 +24,12 @@ Open the printed localhost URL in Chrome. Everything runs in the browser; record
2424
2525 ## What it does
2626
27-- **Record**: raw capture from the microphone, with Chrome's echo cancellation, noise suppression and auto gain turned off. Samples come straight from the audio graph via an AudioWorklet at the mic's own sample rate (32-bit float, no compression). The settings the browser actually applied are shown.
28-- **Inspect one recording**: level over time, waveform and spectrogram on a shared, zoomable time axis; the tear segment (auto-detected, adjustable by dragging its edges); the tear's energy spectral density against the background; summary numbers (duration, speed, energy, median frequency, centroid, peak, clipping, level above background).
29-- **Compare**: energy vs tear duration, median frequency / centroid / mean power vs duration, spectra overlaid per label (optionally normalised to compare shape only), straight-line trends with standard errors, and tables. CSV export.
30-- **Synthetic tears**: built exactly as the hypothesis says, to check the analysis gives flat energy and identical spectra.
27+- **Record**: five fixed speeds (very slow ~10 s to very fast <0.5 s), one tear each. Pick a speed, record it, check it, re-record or delete it. Capture is raw: Chrome's echo cancellation, noise suppression and auto gain are off, and samples come straight from the audio graph via an AudioWorklet at the mic's own sample rate (32-bit float, no compression). For each recording:
28+ - **Tear range**: found automatically; drag across the level plot to mark it again, drag its edges, or type start/end times. Play the tear (with a moving playhead) or the whole recording.
29+ - **Results**: duration, speed, energy, median frequency, centroid, mean power, peak/clipping, level above background.
30+ - **Close-up**: waveform and spectrogram, with zoom buttons, to look for individual clicks.
31+ - **Frequency makeup**: the tear's energy spectrum against the background.
32+- **Compare**: energy vs tear duration, median frequency / centroid / mean power vs duration, spectra of all speeds overlaid (optionally shape only), a table and CSV export.
3133
3234 The “What this can tell you” tab in the app explains the method and its limits.
3335
src/App.tsxmodified+179−119View file
@@ -1,89 +1,110 @@
11 import { useEffect, useMemo, useState } from "react";
2-import { RecordBar } from "./components/RecordBar.tsx";
3-import { RecordingView } from "./components/RecordingView.tsx";
2+import { RecordPanel } from "./components/RecordPanel.tsx";
3+import { TearView } from "./components/TearView.tsx";
44 import { CompareView } from "./components/CompareView.tsx";
55 import { About } from "./components/About.tsx";
66 import { readTheme } from "./components/CanvasPlot.tsx";
7-import { deleteRecording, listRecordings, saveRecording, updateMeta, type RecordingMeta } from "./storage/db.ts";
8-import { colorFor, fmtSec, forgetAudio, groupOrder, groupStyle, loadSettings, PRESET_LABELS, putAudio, storeSettings } from "./model.ts";
7+import { detectSegment } from "./analysis/analyze.ts";
8+import type { CaptureInfo } from "./audio/recorder.ts";
9+import { encodeWavFloat32 } from "./audio/wav.ts";
10+import { deleteRecording, listRecordings, newId, saveRecording, updateMeta, type RecordingMeta } from "./storage/db.ts";
11+import {
12+ colorFor,
13+ download,
14+ fmtDate,
15+ fmtSec,
16+ forgetAudio,
17+ getAudio,
18+ loadSettings,
19+ putAudio,
20+ safeName,
21+ SPEEDS,
22+ speedStyle,
23+ storeSettings,
24+ type Speed,
25+} from "./model.ts";
926 import type { AnalysisSettings } from "./analysis/analyze.ts";
1027
1128 type Tab = "record" | "compare" | "about";
1229
13-function loadExcluded(): Set<string> {
14- try {
15- return new Set(JSON.parse(localStorage.getItem("rsa-excluded") ?? "[]"));
16- } catch {
17- return new Set();
18- }
19-}
20-
2130 export function App() {
2231 const [recs, setRecs] = useState<RecordingMeta[]>([]);
2332 const [loaded, setLoaded] = useState(false);
24- const [selected, setSelected] = useState<string | null>(null);
33+ const [selected, setSelected] = useState(SPEEDS[0].id);
34+ const [rerecording, setRerecording] = useState<string | null>(null);
2535 const [tab, setTab] = useState<Tab>("record");
26- const [label, setLabel] = useState(PRESET_LABELS[2]);
2736 const [settings, setSettingsState] = useState<AnalysisSettings>(loadSettings);
28- const [excluded, setExcluded] = useState<Set<string>>(loadExcluded);
2937 const [showSettings, setShowSettings] = useState(false);
3038
3139 useEffect(() => {
3240 listRecordings().then((r) => {
3341 setRecs(r);
34- setSelected(r.length ? r[r.length - 1].id : null);
3542 setLoaded(true);
43+ const firstMissing = SPEEDS.find((s) => !r.some((m) => m.label === s.id));
44+ if (firstMissing) setSelected(firstMissing.id);
3645 });
3746 navigator.storage?.persist?.().catch(() => {});
3847 }, []);
3948
40- useEffect(() => {
41- try {
42- localStorage.setItem("rsa-excluded", JSON.stringify([...excluded]));
43- } catch {
44- /* ignore */
45- }
46- }, [excluded]);
49+ // one recording per speed: the newest one wins (older ones only exist from earlier versions)
50+ const bySpeed = useMemo(() => {
51+ const m = new Map<string, RecordingMeta>();
52+ for (const r of recs) if (SPEEDS.some((s) => s.id === r.label)) m.set(r.label, r);
53+ return m;
54+ }, [recs]);
55+ const others = recs.filter((r) => bySpeed.get(r.label) !== r);
56+ const recorded = SPEEDS.map((s) => bySpeed.get(s.id)).filter((r): r is RecordingMeta => !!r);
4757
4858 const setSettings = (s: AnalysisSettings) => {
4959 setSettingsState(s);
5060 storeSettings(s);
5161 };
5262
53- const onNew = async (meta: RecordingMeta, x: Float32Array) => {
63+ const onDone = async (speed: Speed, x: Float32Array, fs: number, info: CaptureInfo | null, fileName?: string) => {
64+ const meta: RecordingMeta = {
65+ id: newId(),
66+ createdAt: Date.now(),
67+ label: speed.id,
68+ notes: "",
69+ material: "paper",
70+ source: fileName ? "file" : "mic",
71+ fileName,
72+ sampleRate: fs,
73+ length: x.length,
74+ segment: detectSegment(x, fs),
75+ segmentManual: false,
76+ capture: info ?? undefined,
77+ };
5478 await saveRecording(meta, x);
5579 putAudio(meta.id, x);
56- setRecs((r) => [...r, meta]);
57- setSelected(meta.id);
58- setTab("record");
80+ const old = bySpeed.get(speed.id);
81+ if (old) {
82+ await deleteRecording(old.id);
83+ forgetAudio(old.id);
84+ }
85+ setRecs((r) => [...r.filter((m) => m.id !== old?.id), meta]);
86+ setRerecording(null);
5987 };
88+
6089 const onUpdate = async (meta: RecordingMeta) => {
6190 await updateMeta(meta);
6291 setRecs((r) => r.map((m) => (m.id === meta.id ? meta : m)));
6392 };
64- const onDelete = async (meta: RecordingMeta) => {
65- if (!confirm(`Delete this recording (“${meta.label}”)? This cannot be undone.`)) return;
66- await deleteRecording(meta.id);
67- forgetAudio(meta.id);
68- setRecs((r) => {
69- const next = r.filter((m) => m.id !== meta.id);
70- if (selected === meta.id) setSelected(next.length ? next[next.length - 1].id : null);
71- return next;
72- });
93+
94+ const remove = async (metas: RecordingMeta[]) => {
95+ for (const m of metas) {
96+ await deleteRecording(m.id);
97+ forgetAudio(m.id);
98+ }
99+ const ids = new Set(metas.map((m) => m.id));
100+ setRecs((r) => r.filter((m) => !ids.has(m.id)));
73101 };
74102
75- const groups = useMemo(() => groupOrder(recs), [recs]);
76- const knownLabels = useMemo(() => [...new Set([...PRESET_LABELS, ...recs.map((r) => r.label)])], [recs]);
77- const included = useMemo(() => recs.filter((r) => !excluded.has(r.id)), [recs, excluded]);
78- const current = recs.find((r) => r.id === selected) ?? null;
103+ const speed = SPEEDS.find((s) => s.id === selected)!;
104+ const current = bySpeed.get(selected) ?? null;
79105 const th = readTheme(document.documentElement);
80-
81- const toggle = (ids: string[], on: boolean) =>
82- setExcluded((ex) => {
83- const n = new Set(ex);
84- for (const id of ids) on ? n.delete(id) : n.add(id);
85- return n;
86- });
106+ const idx = SPEEDS.indexOf(speed);
107+ const next = SPEEDS[idx + 1];
87108
88109 return (
89110 <div className="app">
@@ -92,8 +113,8 @@ export function App() {
92113 <nav className="tabs" role="tablist">
93114 {(
94115 [
95- ["record", "Record & inspect"],
96- ["compare", `Compare (${included.length})`],
116+ ["record", "Record"],
117+ ["compare", "Compare"],
97118 ["about", "What this can tell you"],
98119 ] as [Tab, string][]
99120 ).map(([t, name]) => (
@@ -109,79 +130,118 @@ export function App() {
109130
110131 {showSettings && <SettingsPanel settings={settings} setSettings={setSettings} />}
111132
112- <div className="layout">
113- <aside className="sidebar" aria-label="Recordings">
114- <div className="side-head">
115- <span>Recordings</span>
116- <span className="muted">tick = in comparison</span>
117- </div>
118- {loaded && !recs.length && <p className="muted pad">No recordings yet. Enable the microphone and record a tear.</p>}
119- {groups.map((g) => {
120- const members = recs.filter((r) => r.label === g);
121- const st = groupStyle(g, recs);
122- const allOn = members.every((m) => !excluded.has(m.id));
123- return (
124- <div key={g} className="group">
125- <label className="group-head">
126- <input type="checkbox" checked={allOn} onChange={(e) => toggle(members.map((m) => m.id), e.target.checked)} />
127- <i className="swatch" style={{ background: colorFor(st.slot, th.series, th.muted) }} />
128- <span className="group-name">{g}</span>
129- <span className="muted">{members.length}</span>
130- </label>
131- {members.map((m) => (
132- <div key={m.id} className={`item ${m.id === selected ? "sel" : ""}`}>
133- <input
134- type="checkbox"
135- checked={!excluded.has(m.id)}
136- onChange={(e) => toggle([m.id], e.target.checked)}
137- aria-label="Include in comparison"
138- />
139- <button
140- className="item-btn"
141- onClick={() => {
142- setSelected(m.id);
143- setTab("record");
144- }}
145- >
146- <span>{m.segment ? fmtSec(m.segment.end - m.segment.start) : "no tear found"}</span>
147- <span className="muted">
148- {new Date(m.createdAt).toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit" })}
149- {m.source !== "mic" ? ` · ${m.source}` : ""}
150- </span>
151- </button>
152- </div>
153- ))}
133+ {tab === "record" && (
134+ <div className="layout">
135+ <aside className="sidebar" aria-label="Speeds">
136+ <div className="side-head">
137+ Speeds <span className="muted">{recorded.length} of {SPEEDS.length} recorded</span>
138+ </div>
139+ {SPEEDS.map((s) => {
140+ const r = bySpeed.get(s.id);
141+ const st = speedStyle(s.id);
142+ return (
143+ <button
144+ key={s.id}
145+ className={`speed-item ${s.id === selected ? "sel" : ""}`}
146+ onClick={() => {
147+ setSelected(s.id);
148+ setRerecording(null);
149+ }}
150+ >
151+ <span className={`dot ${r ? "done" : ""}`} style={r ? { background: colorFor(st.slot, th.series, th.muted) } : undefined} />
152+ <span className="speed-text">
153+ <span className="speed-name">{s.name}</span>
154+ <span className="muted small">
155+ {s.target} · {r ? (r.segment ? `tear ${fmtSec(r.segment.end - r.segment.start)}` : "no tear marked") : "not recorded"}
156+ </span>
157+ </span>
158+ </button>
159+ );
160+ })}
161+ <p className="muted pad small">Recordings are stored only in this browser.</p>
162+ {others.length > 0 && (
163+ <p className="pad small">
164+ <span className="muted">{others.length} older recording{others.length > 1 ? "s" : ""} from a previous version are not used. </span>
165+ <button
166+ className="link"
167+ onClick={() => confirm(`Delete ${others.length} unused recording(s)? This cannot be undone.`) && remove(others)}
168+ >
169+ Delete them
170+ </button>
171+ </p>
172+ )}
173+ </aside>
174+
175+ <main className="main">
176+ <div className="speed-head">
177+ <div>
178+ <h2>
179+ {speed.name} <span className="muted">· target {speed.target}</span>
180+ </h2>
181+ <div className="muted small">
182+ {current
183+ ? `Recorded ${fmtDate(current.createdAt)} · ${fmtSec(current.length / current.sampleRate)} long${current.fileName ? ` · from ${current.fileName}` : ""}`
184+ : "Not recorded yet"}
185+ </div>
154186 </div>
155- );
156- })}
157- <p className="muted pad small">Stored only in this browser. Use “Download WAV” to keep copies.</p>
158- </aside>
159-
160- <main className="main">
161- {tab === "record" && (
162- <>
163- <RecordBar label={label} setLabel={setLabel} knownLabels={knownLabels} onNew={onNew} />
164- {current ? (
165- <RecordingView key={current.id} meta={current} all={recs} settings={settings} onUpdate={onUpdate} onDelete={onDelete} />
166- ) : (
167- loaded && <div className="card empty">Your recordings will appear here.</div>
187+ {current && rerecording !== speed.id && (
188+ <div className="toolbar">
189+ <button onClick={() => setRerecording(speed.id)}>Re-record</button>
190+ <button
191+ onClick={async () => {
192+ const x = await getAudio(current.id);
193+ download(encodeWavFloat32(x, current.sampleRate), `tear_${safeName(speed.name)}_${new Date(current.createdAt).toISOString().slice(0, 19).replace(/:/g, "-")}.wav`);
194+ }}
195+ >
196+ Download WAV
197+ </button>
198+ <button
199+ className="danger"
200+ onClick={() => confirm(`Delete the ${speed.name.toLowerCase()} recording? This cannot be undone.`) && remove([current])}
201+ >
202+ Delete
203+ </button>
204+ {next && (
205+ <button onClick={() => setSelected(next.id)} title={`Go to ${next.name}`}>
206+ Next speed →
207+ </button>
208+ )}
209+ </div>
168210 )}
169- </>
170- )}
171- {tab === "compare" && (
172- <CompareView
173- recs={included}
174- all={recs}
175- settings={settings}
176- onOpen={(id) => {
177- setSelected(id);
178- setTab("record");
179- }}
180- />
181- )}
182- {tab === "about" && <About settings={settings} />}
211+ </div>
212+
213+ {loaded && (!current || rerecording === speed.id) && (
214+ <RecordPanel
215+ key={speed.id}
216+ speed={speed}
217+ replacing={!!current}
218+ onDone={(x, fs, info, fileName) => onDone(speed, x, fs, info, fileName)}
219+ onCancel={current ? () => setRerecording(null) : null}
220+ />
221+ )}
222+ {current && rerecording !== speed.id && <TearView key={current.id} meta={current} settings={settings} onUpdate={onUpdate} />}
223+ </main>
224+ </div>
225+ )}
226+
227+ {tab === "compare" && (
228+ <main className="main solo">
229+ <CompareView
230+ recs={recorded}
231+ settings={settings}
232+ onOpen={(id) => {
233+ const r = recs.find((m) => m.id === id);
234+ if (r) setSelected(r.label);
235+ setTab("record");
236+ }}
237+ />
238+ </main>
239+ )}
240+ {tab === "about" && (
241+ <main className="main solo">
242+ <About settings={settings} />
183243 </main>
184- </div>
244+ )}
185245 </div>
186246 );
187247 }
src/audio/mic.tsadded+78−0View file
@@ -0,0 +1,78 @@
1+// One microphone for the whole app, opened once and kept open while switching speeds.
2+import { useSyncExternalStore } from "react";
3+import { MicRecorder, listInputs, type CaptureInfo } from "./recorder.ts";
4+
5+export interface MicState {
6+ status: "closed" | "opening" | "ready" | "recording" | "saving";
7+ info: CaptureInfo | null;
8+ devices: MediaDeviceInfo[];
9+ error: string | null;
10+ peak: number; // latest peak (linear), decays for display
11+ clipped: boolean; // during the current recording
12+ startedAt: number; // performance.now() at start of recording
13+}
14+
15+const rec = new MicRecorder();
16+let state: MicState = { status: "closed", info: null, devices: [], error: null, peak: 0, clipped: false, startedAt: 0 };
17+const listeners = new Set<() => void>();
18+const set = (p: Partial<MicState>) => {
19+ state = { ...state, ...p };
20+ listeners.forEach((l) => l());
21+};
22+
23+let peakAcc = 0;
24+rec.onPeak = (p) => {
25+ peakAcc = Math.max(peakAcc, p);
26+ if (p >= 0.99 && rec.recording && !state.clipped) set({ clipped: true });
27+};
28+// repaint the meter at display rate rather than per audio block
29+const tick = () => {
30+ if (state.status !== "closed") {
31+ const shown = Math.max(peakAcc, state.peak * 0.93);
32+ peakAcc = 0;
33+ if (Math.abs(shown - state.peak) > 1e-5 || state.status === "recording") set({ peak: shown });
34+ }
35+ requestAnimationFrame(tick);
36+};
37+requestAnimationFrame(tick);
38+
39+export const mic = {
40+ get: () => state,
41+ subscribe(l: () => void) {
42+ listeners.add(l);
43+ return () => listeners.delete(l);
44+ },
45+ get sampleRate() {
46+ return rec.sampleRate;
47+ },
48+ async open(deviceId?: string) {
49+ set({ status: "opening", error: null });
50+ try {
51+ const info = await rec.open(deviceId);
52+ set({ status: "ready", info, devices: await listInputs() });
53+ } catch (e) {
54+ set({ status: "closed", error: `Could not open the microphone: ${(e as Error).message}` });
55+ }
56+ },
57+ start() {
58+ if (state.status !== "ready") return;
59+ rec.start();
60+ set({ status: "recording", clipped: false, startedAt: performance.now() });
61+ },
62+ async stop(): Promise<{ samples: Float32Array; fs: number; info: CaptureInfo | null } | null> {
63+ if (state.status !== "recording") return null;
64+ set({ status: "saving" });
65+ const samples = await rec.stop();
66+ set({ status: "ready" });
67+ return { samples, fs: rec.sampleRate, info: rec.info };
68+ },
69+ async cancel() {
70+ if (state.status !== "recording") return;
71+ await rec.stop();
72+ set({ status: "ready" });
73+ },
74+};
75+
76+export function useMic(): MicState {
77+ return useSyncExternalStore(mic.subscribe, mic.get);
78+}
src/audio/player.tsadded+70−0View file
@@ -0,0 +1,70 @@
1+// Plays part of a recording and reports the playhead position for drawing.
2+import { useSyncExternalStore } from "react";
3+
4+let ctx: AudioContext | null = null;
5+let src: AudioBufferSourceNode | null = null;
6+let state: { id: string; t: number } | null = null; // recording id + current time (s)
7+let startCtx = 0;
8+let from = 0;
9+let to = 0;
10+let raf = 0;
11+const listeners = new Set<() => void>();
12+const emit = () => listeners.forEach((l) => l());
13+
14+function tick() {
15+ if (!ctx || !state) return;
16+ const t = from + (ctx.currentTime - startCtx);
17+ if (t >= to) {
18+ stop();
19+ return;
20+ }
21+ state = { id: state.id, t };
22+ emit();
23+ raf = requestAnimationFrame(tick);
24+}
25+
26+export function play(id: string, x: Float32Array, fs: number, a: number, b: number) {
27+ stop();
28+ ctx ??= new AudioContext();
29+ const s = Math.max(0, Math.floor(a * fs));
30+ const e = Math.min(x.length, Math.ceil(b * fs));
31+ if (e <= s) return;
32+ const buf = ctx.createBuffer(1, e - s, fs);
33+ buf.copyToChannel(x.subarray(s, e) as Float32Array<ArrayBuffer>, 0);
34+ src = ctx.createBufferSource();
35+ src.buffer = buf;
36+ src.connect(ctx.destination);
37+ void ctx.resume();
38+ startCtx = ctx.currentTime + 0.02;
39+ src.start(startCtx);
40+ from = s / fs;
41+ to = e / fs;
42+ state = { id, t: from };
43+ emit();
44+ raf = requestAnimationFrame(tick);
45+}
46+
47+export function stop() {
48+ cancelAnimationFrame(raf);
49+ try {
50+ src?.stop();
51+ } catch {
52+ /* not started */
53+ }
54+ src = null;
55+ if (state) {
56+ state = null;
57+ emit();
58+ }
59+}
60+
61+const subscribe = (l: () => void) => {
62+ listeners.add(l);
63+ return () => listeners.delete(l);
64+};
65+
66+// Playhead time for this recording, or null when it is not playing.
67+export function usePlayhead(id: string): number | null {
68+ const s = useSyncExternalStore(subscribe, () => state);
69+ return s && s.id === id ? s.t : null;
70+}
src/components/About.tsxmodified+3−4View file
@@ -18,8 +18,7 @@ export function About({ settings }: { settings: AnalysisSettings }) {
1818 <h2>What is measured</h2>
1919 <ul>
2020 <li>
21- <b>Tear segment</b>: found automatically as the loudest stretch well above the background (gaps under 0.6 s are bridged). Check it on the plots and drag
22- its edges if it is wrong. Duration and speed ({settings.sheetLengthIn} in ÷ duration) come from this segment, not from the label.
21+ <b>Tear segment</b>: found automatically as the loudest stretch well above the background (gaps under 0.6 s are bridged). Check it on the Record tab and adjust it if it is wrong. Duration and speed ({settings.sheetLengthIn} in ÷ duration) come from this segment, not from the label.
2322 </li>
2423 <li>
2524 <b>Energy spectral density</b> of the tear: Welch average of 2048-point Hann-windowed spectra over the segment, times its duration. Units are digital
@@ -81,8 +80,8 @@ export function About({ settings }: { settings: AnalysisSettings }) {
8180
8281 <h2>Checking the analysis</h2>
8382 <p>
84- Under “Import a file or add a synthetic test tear” you can add synthetic tears made exactly as the hypothesis says: 4000 clicks of one fixed shape with
85- random amplitudes, spread over 0.3 to 10 seconds. Their energies and spectra should agree within a fraction of a dB. If they don't, the analysis is wrong.
83+ The project's test script (<code>npm test</code>) builds synthetic tears exactly as the hypothesis says (4000 clicks of one fixed shape with random
84+ amplitudes, spread over 0.3 to 10 seconds) and checks that their measured energies and spectra agree. They do, within a fraction of a dB.
8685 </p>
8786 </div>
8887 );
src/components/CanvasPlot.tsxmodified+12−5View file
@@ -62,7 +62,7 @@ interface Props {
6262 // returns tooltip lines for a hover position (null = no tooltip)
6363 hover?: (p: PointerInfo) => { lines: string[]; x?: number; y?: number } | null;
6464 onPointer?: (type: "down" | "move" | "up", p: PointerInfo, ev: PointerEvent) => void;
65- onWheel?: (p: PointerInfo, ev: WheelEvent) => void;
65+ onWheel?: (p: PointerInfo, ev: WheelEvent) => boolean; // true = handled (page does not scroll)
6666 onDoubleClick?: () => void;
6767 onClick?: (p: PointerInfo) => void;
6868 cursor?: (p: PointerInfo) => string;
@@ -287,11 +287,16 @@ export function CanvasPlot(props: Props) {
287287 }
288288 };
289289 let down = false;
290+ let downAt = { x: 0, y: 0 };
291+ let moved = false;
290292 const onMove = (ev: PointerEvent) => {
291293 const p = info(ev);
292294 if (!p) return;
293295 const pr = propsRef.current;
294- if (down) pr.onPointer?.("move", p, ev);
296+ if (down) {
297+ if (Math.abs(ev.clientX - downAt.x) + Math.abs(ev.clientY - downAt.y) > 3) moved = true;
298+ pr.onPointer?.("move", p, ev);
299+ }
295300 else if (pr.cursor) setCursor(pr.cursor(p));
296301 const h = pr.hover?.(p) ?? null;
297302 const s = p.scales;
@@ -307,6 +312,8 @@ export function CanvasPlot(props: Props) {
307312 const p = info(ev);
308313 if (!p || !propsRef.current.onPointer) return;
309314 down = true;
315+ downAt = { x: ev.clientX, y: ev.clientY };
316+ moved = false;
310317 el.setPointerCapture(ev.pointerId);
311318 propsRef.current.onPointer("down", p, ev);
312319 };
@@ -324,13 +331,13 @@ export function CanvasPlot(props: Props) {
324331 const onWheel = (ev: WheelEvent) => {
325332 const p = info(ev);
326333 if (!p || !propsRef.current.onWheel) return;
327- ev.preventDefault();
328- propsRef.current.onWheel(p, ev);
334+ if (propsRef.current.onWheel(p, ev)) ev.preventDefault();
329335 };
330336 const onDbl = () => propsRef.current.onDoubleClick?.();
331337 const onClick = (ev: MouseEvent) => {
332338 const p = info(ev);
333- if (p) propsRef.current.onClick?.(p);
339+ if (p && !moved) propsRef.current.onClick?.(p);
340+ moved = false;
334341 };
335342 el.addEventListener("pointermove", onMove);
336343 el.addEventListener("pointerdown", onDown);
src/components/CompareView.tsxmodified+121−202View file
@@ -2,11 +2,10 @@ import { useCallback, useEffect, useMemo, useState } from "react";
22 import { CanvasPlot, drawLine, drawMarker, readTheme, type MarkerShape, type PointerInfo, type Scales, type Theme } from "./CanvasPlot.tsx";
33 import { smoothLog, type Analysis, type AnalysisSettings } from "../analysis/analyze.ts";
44 import type { RecordingMeta } from "../storage/db.ts";
5-import { colorFor, db10, download, fmtHz, fmtSec, getAnalysis, groupOrder, groupStyle, linearFit } from "../model.ts";
5+import { colorFor, db10, download, fmtHz, fmtSec, getAnalysis, linearFit, SPEEDS, speedName, speedStyle } from "../model.ts";
66
77 interface Props {
8- recs: RecordingMeta[]; // recordings included in the comparison
9- all: RecordingMeta[];
8+ recs: RecordingMeta[]; // at most one per speed, in speed order
109 settings: AnalysisSettings;
1110 onOpen: (id: string) => void;
1211 }
@@ -17,71 +16,70 @@ interface Row {
1716 }
1817
1918 type Metric = "median" | "centroid" | "power";
20-const METRICS: Record<Metric, { label: string; axis: string; get: (a: Analysis) => number; fmt: (v: number) => string; log: boolean }> = {
21- median: { label: "Median frequency", axis: "median frequency (Hz)", get: (a) => a.medianFreq, fmt: fmtHz, log: false },
22- centroid: { label: "Spectral centroid", axis: "centroid (Hz)", get: (a) => a.centroid, fmt: fmtHz, log: false },
23- power: { label: "Mean power", axis: "mean power (dBFS)", get: (a) => db10(a.energy / a.duration), fmt: (v) => `${v.toFixed(1)} dBFS`, log: false },
19+const 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" },
2423 };
2524
26-export function CompareView({ recs, all, settings, onOpen }: Props) {
25+const energyOf = (a: Analysis) => db10(a.energy);
26+const fmtDb = (v: number) => `${v.toFixed(1)} dB`;
27+
28+export function CompareView({ recs, settings, onOpen }: Props) {
2729 const [rows, setRows] = useState<Row[]>([]);
28- const [progress, setProgress] = useState<[number, number]>([0, 0]);
30+ const [ready, setReady] = useState(false);
2931 const [metric, setMetric] = useState<Metric>("median");
30- const [specMode, setSpecMode] = useState<"group" | "each">("group");
3132 const [normalize, setNormalize] = useState(false);
3233 const [smoothing, setSmoothing] = useState(1 / 6);
3334
3435 useEffect(() => {
3536 let live = true;
37+ setReady(false);
3638 (async () => {
3739 const out: Row[] = [];
38- setProgress([0, recs.length]);
39- for (let i = 0; i < recs.length; i++) {
40- const a = await getAnalysis(recs[i], settings);
40+ for (const m of recs) {
41+ const a = await getAnalysis(m, settings);
4142 if (!live) return;
42- if (a && a.energy > 0) out.push({ meta: recs[i], a });
43- setProgress([i + 1, recs.length]);
43+ if (a && a.energy > 0) out.push({ meta: m, a });
4444 await new Promise((r) => setTimeout(r, 0));
4545 }
46- if (live) setRows(out);
46+ if (live) {
47+ setRows(out);
48+ setReady(true);
49+ }
4750 })();
4851 return () => {
4952 live = false;
5053 };
5154 }, [recs, settings]);
5255
53- const groups = useMemo(() => groupOrder(rows.map((r) => r.meta)), [rows]);
54- const style = useCallback((label: string) => groupStyle(label, all), [all]);
55-
56- const skipped = recs.length - rows.length;
57- const loading = progress[0] < progress[1];
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));
5858
59- if (!recs.length) return <div className="card empty">No recordings are included in the comparison. Tick some in the list on the left.</div>;
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>;
6061
6162 return (
6263 <div className="compare">
63- {loading && (
64- <div className="card muted">
65- Analysing {progress[0]} / {progress[1]}…
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>}
6668 </div>
6769 )}
68- {!loading && skipped > 0 && (
69- <div className="card warn">
70- {skipped} recording{skipped > 1 ? "s have" : " has"} no tear segment or no energy above the background and {skipped > 1 ? "are" : "is"} left out.
71- </div>
72- )}
73- <Summary rows={rows} groups={groups} />
70+
71+ <Summary rows={rows} />
7472
7573 <div className="grid2">
7674 <section className="card">
7775 <h3>Total sound energy vs tear duration</h3>
7876 <p className="caption">If every tear contains the same clicks, the points should lie on a flat line.</p>
79- <Scatter rows={rows} y={(a) => db10(a.energy)} yFmt={(v) => `${v.toFixed(1)} dB`} yLabel="energy (dB re FS²·s)" style={style} onOpen={onOpen} fitUnit="dB" minSpan={10} />
77+ <Scatter rows={rows} y={energyOf} yFmt={fmtDb} yLabel="energy (dB, relative)" onOpen={onOpen} unit="dB" minSpan={10} />
8078 </section>
8179 <section className="card">
8280 <div className="plot-head">
8381 <h3>{METRICS[metric].label} vs tear duration</h3>
84- <select value={metric} onChange={(e) => setMetric(e.target.value as Metric)} aria-label="Metric">
82+ <select value={metric} onChange={(e) => setMetric(e.target.value as Metric)} aria-label="Quantity to plot">
8583 {(Object.keys(METRICS) as Metric[]).map((k) => (
8684 <option key={k} value={k}>
8785 {METRICS[k].label}
@@ -91,19 +89,10 @@ export function CompareView({ recs, all, settings, onOpen }: Props) {
9189 </div>
9290 <p className="caption">
9391 {metric === "power"
94- ? "Same energy packed into less time means power rises 10 dB for every 10× shorter tear."
92+ ? "The same energy packed into less time: power should rise 10 dB for every 10× shorter tear (slope −10 dB)."
9593 : "If the clicks are the same at every speed, this should not depend on duration."}
9694 </p>
97- <Scatter
98- rows={rows}
99- y={METRICS[metric].get}
100- yFmt={METRICS[metric].fmt}
101- yLabel={METRICS[metric].axis}
102- style={style}
103- onOpen={onOpen}
104- fitUnit={metric === "power" ? "dB" : "Hz"}
105- minSpan={metric === "power" ? 10 : 4000}
106- />
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} />
10796 </section>
10897 </div>
10998
@@ -111,12 +100,8 @@ export function CompareView({ recs, all, settings, onOpen }: Props) {
111100 <div className="plot-head">
112101 <h3>Frequency makeup</h3>
113102 <div className="toolbar">
114- <select value={specMode} onChange={(e) => setSpecMode(e.target.value as "group" | "each")} aria-label="Lines">
115- <option value="group">average per label</option>
116- <option value="each">each recording</option>
117- </select>
118103 <label>
119- <input type="checkbox" checked={normalize} onChange={(e) => setNormalize(e.target.checked)} /> shape only (scale each to equal energy)
104+ <input type="checkbox" checked={normalize} onChange={(e) => setNormalize(e.target.checked)} /> compare shape only (scale each to the same total energy)
120105 </label>
121106 <label>
122107 smoothing
@@ -129,22 +114,22 @@ export function CompareView({ recs, all, settings, onOpen }: Props) {
129114 </div>
130115 </div>
131116 <p className="caption">
132- Energy spectral density of each tear with the background removed.
117+ Energy spectrum of each tear, background removed.
133118 {normalize
134- ? " Each curve is divided by its total energy in the band, so only the shape is compared."
119+ ? " Each curve is divided by its total energy, so only the shape is compared."
135120 : " If tears at all speeds contain the same clicks, the curves should lie on top of each other."}
136121 </p>
137- <SpectraOverlay rows={rows} groups={groups} mode={specMode} normalize={normalize} smoothing={smoothing} settings={settings} style={style} />
122+ <SpectraOverlay rows={rows} normalize={normalize} smoothing={smoothing} settings={settings} />
138123 </section>
139124
140125 <section className="card">
141126 <div className="plot-head">
142- <h3>All recordings</h3>
127+ <h3>Numbers</h3>
143128 <button onClick={() => exportCsv(rows, settings)} disabled={!rows.length}>
144129 Download CSV
145130 </button>
146131 </div>
147- <Table rows={rows} groups={groups} style={style} onOpen={onOpen} />
132+ <Table rows={rows} onOpen={onOpen} />
148133 </section>
149134 </div>
150135 );
@@ -152,38 +137,48 @@ export function CompareView({ recs, all, settings, onOpen }: Props) {
152137
153138 // ---------- summary ----------
154139
155-function Summary({ rows, groups }: { rows: Row[]; groups: string[] }) {
156- if (rows.length < 3) return <div className="card muted">Add at least three recordings (ideally at a few different speeds) to see trends.</div>;
140+function Summary({ rows }: { rows: Row[] }) {
141+ if (rows.length < 2) return <div className="card muted">Record at least two speeds to compare them.</div>;
157142 const lx = rows.map((r) => Math.log10(r.a.duration));
158- const fe = linearFit(lx, rows.map((r) => db10(r.a.energy)));
143+ const e = rows.map((r) => db10(r.a.energy));
144+ const fe = linearFit(lx, e);
159145 const fm = linearFit(lx, rows.map((r) => r.a.medianFreq));
160146 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);
161149 return (
162150 <section className="card summary">
163151 <h3>The two questions</h3>
164152 <div className="q">
165153 <div className="q-title">Same total energy at every speed?</div>
166- {fe && (
167- <div>
168- Energy changes by <b>{fmtSigned(fe.b)} ± {fe.seB.toFixed(2)} dB</b> for each 10× longer tear (straight-line fit, ± one standard error, {fe.n} recordings).
169- {" "}
170- {verdict(fe.b, fe.seB)}
171- </div>
172- )}
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>
173163 </div>
174164 <div className="q">
175165 <div className="q-title">Same frequency makeup at every speed?</div>
176- {fm && (
177- <div>
178- Median frequency changes by <b>{fmtSigned(fm.b, 0)} ± {fm.seB.toFixed(0)} Hz</b> for each 10× longer tear. Compare the curve shapes below (tick “shape only”).
179- {" "}
180- {verdict(fm.b, fm.seB)}
181- </div>
182- )}
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>
183176 </div>
184177 <p className="caption">
185- Durations span {span.toFixed(1)}× across {groups.length} label{groups.length === 1 ? "" : "s"}.
186- {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.
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."}
187182 </p>
188183 </section>
189184 );
@@ -193,11 +188,6 @@ function fmtSigned(v: number, digits = 2) {
193188 return `${v >= 0 ? "+" : "−"}${Math.abs(v).toFixed(digits)}`;
194189 }
195190
196-function verdict(b: number, se: number) {
197- if (!Number.isFinite(se)) return null;
198- return Math.abs(b) < 2 * se ? <span className="muted">(not clearly different from zero)</span> : <span className="muted">(clearly different from zero)</span>;
199-}
200-
201191 // ---------- scatter ----------
202192
203193 function Scatter({
@@ -205,19 +195,17 @@ function Scatter({
205195 y,
206196 yFmt,
207197 yLabel,
208- style,
209198 onOpen,
210- fitUnit,
199+ unit,
211200 minSpan,
212201 }: {
213- minSpan: number;
214202 rows: Row[];
215203 y: (a: Analysis) => number;
216204 yFmt: (v: number) => string;
217205 yLabel: string;
218- style: (l: string) => { slot: number | null; shape: MarkerShape };
219206 onOpen: (id: string) => void;
220- fitUnit: string;
207+ unit: string;
208+ minSpan: number;
221209 }) {
222210 const pts = useMemo(() => rows.map((r) => ({ r, x: r.a.duration, y: y(r.a) })).filter((p) => Number.isFinite(p.y)), [rows, y]);
223211 const xr = useMemo<[number, number]>(() => {
@@ -239,15 +227,13 @@ function Scatter({
239227
240228 const draw = useCallback(
241229 (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
242- if (fit) {
243- 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]);
244- }
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]);
245231 for (const p of pts) {
246- const st = style(p.r.meta.label);
247- drawMarker(ctx, s.x(p.x), s.y(p.y), st.shape, colorFor(st.slot, th.series, th.muted), th.surface, 5);
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);
248234 }
249235 },
250- [pts, fit, xr, style],
236+ [pts, fit, xr],
251237 );
252238
253239 const near = (p: PointerInfo) => {
@@ -276,7 +262,7 @@ function Scatter({
276262 hover={(p) => {
277263 const q = near(p);
278264 if (!q) return null;
279- return { lines: [q.r.meta.label, `${fmtSec(q.x)} · ${yFmt(q.y)}`, "click to open"], x: q.x, y: q.y };
265+ return { lines: [speedName(q.r.meta.label), `${fmtSec(q.x)} · ${yFmt(q.y)}`, "click to open"], x: q.x, y: q.y };
280266 }}
281267 onClick={(p) => {
282268 const q = near(p);
@@ -285,51 +271,27 @@ function Scatter({
285271 cursor={(p) => (near(p) ? "pointer" : "crosshair")}
286272 ariaLabel={`${yLabel} against tear duration`}
287273 />
288- <Legend labels={groupOrder(rows.map((r) => r.meta))} style={style} extra={fit ? `dashed: straight-line fit, slope ${fmtSigned(fit.b, fitUnit === "Hz" ? 0 : 2)} ${fitUnit} per 10× duration` : undefined} />
274+ <Legend rows={rows} extra={fit ? `dashed: trend, ${fmtSigned(fit.b, unit === "Hz" ? 0 : 2)} ${unit} per 10× duration` : undefined} />
289275 </>
290276 );
291277 }
292278
293279 // ---------- spectra overlay ----------
294280
295-function SpectraOverlay({
296- rows,
297- groups,
298- mode,
299- normalize,
300- smoothing,
301- settings,
302- style,
303-}: {
304- rows: Row[];
305- groups: string[];
306- mode: "group" | "each";
307- normalize: boolean;
308- smoothing: number;
309- settings: AnalysisSettings;
310- style: (l: string) => { slot: number | null; shape: MarkerShape };
311-}) {
281+function SpectraOverlay({ rows, normalize, smoothing, settings }: { rows: Row[]; normalize: boolean; smoothing: number; settings: AnalysisSettings }) {
312282 const fsMin = rows.length ? Math.min(...rows.map((r) => r.a.fs)) : 48000;
313283 const fLo = Math.max(20, settings.bandLow);
314284 const fHi = Math.min(settings.bandHigh, fsMin / 2);
315285
316- const lines = useMemo(() => {
317- const per = rows.map((r) => {
318- const scale = normalize ? 1 / r.a.energy : 1;
319- const sm = smoothLog(r.a.freqs, r.a.netEsd.map((v) => v * scale), fLo, fHi, smoothing);
320- return { label: r.meta.label, name: r.meta.label, f: sm.f, v: sm.v };
321- });
322- if (mode === "each") return per.map((p) => ({ ...p, db: p.v.map(db10Floor) }));
323- return groups
324- .map((g) => {
325- const members = per.filter((p) => p.label === g);
326- if (!members.length) return null;
327- const f = members[0].f;
328- const v = f.map((_, i) => members.reduce((s, m) => s + (m.v[i] ?? 0), 0) / members.length);
329- return { label: g, name: `${g} (n=${members.length})`, f, v, db: v.map(db10Floor) };
330- })
331- .filter((x): x is NonNullable<typeof x> => !!x);
332- }, [rows, groups, mode, normalize, smoothing, fLo, fHi]);
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+ );
333295
334296 const yr = useMemo<[number, number]>(() => {
335297 const all = lines.flatMap((l) => l.db.filter(Number.isFinite));
@@ -341,11 +303,11 @@ function SpectraOverlay({
341303 const draw = useCallback(
342304 (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
343305 for (const l of lines) {
344- const st = style(l.label);
345- drawLine(ctx, s, l.f, l.db, colorFor(st.slot, th.series, th.muted), mode === "each" ? 1.5 : 2);
306+ const st = speedStyle(l.label);
307+ drawLine(ctx, s, l.f, l.db, colorFor(st.slot, th.series, th.muted), 2);
346308 }
347309 },
348- [lines, style, mode],
310+ [lines],
349311 );
350312
351313 return (
@@ -363,25 +325,24 @@ function SpectraOverlay({
363325 const f = lines[0].f;
364326 let i = 0;
365327 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;
366- const vals = lines.slice(0, 10).map((l) => `${l.name}: ${Number.isFinite(l.db[i]) ? l.db[i].toFixed(1) : "–"} dB`);
367- if (lines.length > 10) vals.push(`… ${lines.length - 10} more`);
368- return { lines: [fmtHz(f[i]), ...vals], x: f[i] };
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] };
369329 }}
370- ariaLabel="Energy spectral density of tears, overlaid"
330+ ariaLabel="Energy spectra of the tears, overlaid"
371331 />
372- <Legend labels={groups} style={style} lines />
332+ <Legend rows={rows} lines />
373333 </>
374334 );
375335 }
376336
377-function db10Floor(v: number) {
378- return v > 0 ? 10 * Math.log10(v) : NaN;
379-}
380-
381337 // ---------- legend & table ----------
382338
383339 function MarkerIcon({ shape, color, line }: { shape: MarkerShape; color: string; line?: boolean }) {
384- if (line) return <svg width="18" height="10" aria-hidden><line x1="1" y1="5" x2="17" y2="5" stroke={color} strokeWidth="2.5" strokeLinecap="round" /></svg>;
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+ );
385346 const d: Record<MarkerShape, string> = {
386347 circle: "M9,4 a5,5 0 1,0 0.01,0",
387348 square: "M4.5,4.5 h9 v9 h-9 z",
@@ -396,15 +357,15 @@ function MarkerIcon({ shape, color, line }: { shape: MarkerShape; color: string;
396357 );
397358 }
398359
399-function Legend({ labels, style, lines, extra }: { labels: string[]; style: (l: string) => { slot: number | null; shape: MarkerShape }; lines?: boolean; extra?: string }) {
360+function Legend({ rows, lines, extra }: { rows: Row[]; lines?: boolean; extra?: string }) {
400361 const th = readTheme(document.documentElement);
401362 return (
402363 <div className="legend">
403- {labels.map((l) => {
404- const st = style(l);
364+ {rows.map((r) => {
365+ const st = speedStyle(r.meta.label);
405366 return (
406- <span key={l}>
407- <MarkerIcon shape={st.shape} color={colorFor(st.slot, th.series, th.muted)} line={lines} /> {l}
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)}
408369 </span>
409370 );
410371 })}
@@ -413,85 +374,43 @@ function Legend({ labels, style, lines, extra }: { labels: string[]; style: (l:
413374 );
414375 }
415376
416-function Table({ rows, groups, style, onOpen }: { rows: Row[]; groups: string[]; style: (l: string) => { slot: number | null; shape: MarkerShape }; onOpen: (id: string) => void }) {
377+function Table({ rows, onOpen }: { rows: Row[]; onOpen: (id: string) => void }) {
417378 const th = readTheme(document.documentElement);
418- const sorted = [...rows].sort((a, b) => groups.indexOf(a.meta.label) - groups.indexOf(b.meta.label) || b.a.duration - a.a.duration);
419- const groupStats = groups.map((g) => {
420- const rs = rows.filter((r) => r.meta.label === g);
421- const e = rs.map((r) => db10(r.a.energy));
422- const mean = e.reduce((s, v) => s + v, 0) / e.length;
423- const sd = e.length > 1 ? Math.sqrt(e.reduce((s, v) => s + (v - mean) ** 2, 0) / (e.length - 1)) : NaN;
424- return {
425- g,
426- n: rs.length,
427- dur: rs.reduce((s, r) => s + r.a.duration, 0) / rs.length,
428- mean,
429- sd,
430- med: rs.reduce((s, r) => s + r.a.medianFreq, 0) / rs.length,
431- };
432- });
433379 return (
434380 <div className="table-wrap">
435381 <table>
436382 <thead>
437383 <tr>
438- <th>Label</th>
439- <th>n</th>
440- <th className="num">Mean duration</th>
441- <th className="num">Energy (dB), mean ± sd</th>
442- <th className="num">Median freq, mean</th>
443- </tr>
444- </thead>
445- <tbody>
446- {groupStats.map((s) => {
447- const st = style(s.g);
448- return (
449- <tr key={s.g}>
450- <td>
451- <MarkerIcon shape={st.shape} color={colorFor(st.slot, th.series, th.muted)} /> {s.g}
452- </td>
453- <td>{s.n}</td>
454- <td className="num">{fmtSec(s.dur)}</td>
455- <td className="num">
456- {s.mean.toFixed(1)}
457- {Number.isFinite(s.sd) ? ` ± ${s.sd.toFixed(1)}` : ""}
458- </td>
459- <td className="num">{fmtHz(s.med)}</td>
460- </tr>
461- );
462- })}
463- </tbody>
464- </table>
465- <table>
466- <thead>
467- <tr>
468- <th>Label</th>
469- <th className="num">Duration</th>
384+ <th>Speed</th>
385+ <th className="num">Tear duration</th>
470386 <th className="num">Speed (in/s)</th>
471387 <th className="num">Energy (dB)</th>
472- <th className="num">Above bg (dB)</th>
388+ <th className="num">Mean power (dBFS)</th>
473389 <th className="num">Median freq</th>
474390 <th className="num">Centroid</th>
391+ <th className="num">Above background</th>
475392 <th className="num">Peak (dBFS)</th>
476- <th></th>
477393 </tr>
478394 </thead>
479395 <tbody>
480- {sorted.map(({ meta, a }) => {
481- const st = style(meta.label);
396+ {rows.map(({ meta, a }) => {
397+ const st = speedStyle(meta.label);
482398 return (
483- <tr key={meta.id} className="clickable" onClick={() => onOpen(meta.id)}>
399+ <tr key={meta.id} className="clickable" onClick={() => onOpen(meta.id)} title="Open on the Record tab">
484400 <td>
485- <MarkerIcon shape={st.shape} color={colorFor(st.slot, th.series, th.muted)} /> {meta.label}
401+ <MarkerIcon shape={st.shape} color={colorFor(st.slot, th.series, th.muted)} /> {speedName(meta.label)}
486402 </td>
487403 <td className="num">{fmtSec(a.duration)}</td>
488404 <td className="num">{a.speedInPerSec.toFixed(2)}</td>
489405 <td className="num">{db10(a.energy).toFixed(1)}</td>
490- <td className="num">{Number.isFinite(a.snrDb) ? a.snrDb.toFixed(1) : "–"}</td>
406+ <td className="num">{db10(a.energy / a.duration).toFixed(1)}</td>
491407 <td className="num">{fmtHz(a.medianFreq)}</td>
492408 <td className="num">{fmtHz(a.centroid)}</td>
493- <td className="num">{a.peakDbfs.toFixed(1)}</td>
494- <td>{a.nearClip > 0 ? <span className="warn-inline">⚠ clipped</span> : meta.source !== "mic" ? <span className={`badge ${meta.source}`}>{meta.source}</span> : null}</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>
495414 </tr>
496415 );
497416 })}
@@ -503,7 +422,7 @@ function Table({ rows, groups, style, onOpen }: { rows: Row[]; groups: string[];
503422
504423 function exportCsv(rows: Row[], settings: AnalysisSettings) {
505424 const head = [
506- "id", "created", "label", "source", "notes", "sample_rate", "tear_start_s", "tear_end_s", "segment_manual", "duration_s", "speed_in_per_s",
425+ "speed", "recorded", "source", "sample_rate", "tear_start_s", "tear_end_s", "range_set_by_hand", "duration_s", "speed_in_per_s",
507426 "energy_db", "energy_raw_db", "background_db", "above_background_db", "median_hz", "centroid_hz", "f10_hz", "f90_hz", "peak_dbfs", "near_clip_samples",
508427 "band_low_hz", "band_high_hz", "sheet_length_in",
509428 ];
@@ -515,7 +434,7 @@ function exportCsv(rows: Row[], settings: AnalysisSettings) {
515434 for (const { meta: m, a } of rows) {
516435 lines.push(
517436 [
518- 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,
437+ m.label, new Date(m.createdAt).toISOString(), m.source, m.sampleRate, a.segment.start.toFixed(4), a.segment.end.toFixed(4), m.segmentManual,
519438 a.duration.toFixed(4), a.speedInPerSec.toFixed(4), db10(a.energy).toFixed(3), db10(a.energyRaw).toFixed(3), db10(a.energyNoise).toFixed(3),
520439 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,
521440 settings.bandLow, settings.bandHigh, settings.sheetLengthIn,
src/components/RecordBar.tsxdeleted+0−313View file
@@ -1,313 +0,0 @@
1-import { useEffect, useRef, useState } from "react";
2-import { MicRecorder, listInputs, type CaptureInfo } from "../audio/recorder.ts";
3-import { decodeWav } from "../audio/wav.ts";
4-import { syntheticTear } from "../audio/synthetic.ts";
5-import { detectSegment } from "../analysis/analyze.ts";
6-import { newId, type RecordingMeta } from "../storage/db.ts";
7-import { PRESET_LABELS } from "../model.ts";
8-
9-const MAX_SECONDS = 60;
10-
11-interface Props {
12- label: string;
13- setLabel: (l: string) => void;
14- knownLabels: string[];
15- onNew: (meta: RecordingMeta, samples: Float32Array) => Promise<void>;
16-}
17-
18-type Status = "closed" | "opening" | "ready" | "recording" | "saving";
19-
20-export function RecordBar({ label, setLabel, knownLabels, onNew }: Props) {
21- const rec = useRef<MicRecorder>(null);
22- rec.current ??= new MicRecorder();
23- const [status, setStatus] = useState<Status>("closed");
24- const [info, setInfo] = useState<CaptureInfo | null>(null);
25- const [devices, setDevices] = useState<MediaDeviceInfo[]>([]);
26- const [deviceId, setDeviceId] = useState<string>("");
27- const [error, setError] = useState<string | null>(null);
28- const [level, setLevel] = useState(-120);
29- const [clipped, setClipped] = useState(false);
30- const [elapsed, setElapsed] = useState(0);
31- const [synthT, setSynthT] = useState(1);
32- const peakAcc = useRef(0);
33- const peakHold = useRef(0);
34- const startedAt = useRef(0);
35- const statusRef = useRef(status);
36- statusRef.current = status;
37-
38- // meter: accumulate peaks from the worklet, repaint at display rate
39- useEffect(() => {
40- let raf = 0;
41- const tick = () => {
42- const p = peakAcc.current;
43- peakAcc.current = 0;
44- peakHold.current = Math.max(p, peakHold.current * 0.93);
45- setLevel(20 * Math.log10(Math.max(peakHold.current, 1e-6)));
46- if (statusRef.current === "recording") {
47- const t = (performance.now() - startedAt.current) / 1000;
48- setElapsed(t);
49- if (t > MAX_SECONDS) void stop();
50- }
51- raf = requestAnimationFrame(tick);
52- };
53- raf = requestAnimationFrame(tick);
54- return () => cancelAnimationFrame(raf);
55- // eslint-disable-next-line react-hooks/exhaustive-deps
56- }, []);
57-
58- useEffect(() => () => void rec.current?.close(), []);
59-
60- async function open(id?: string) {
61- setError(null);
62- setStatus("opening");
63- try {
64- const r = rec.current!;
65- r.onPeak = (p) => {
66- peakAcc.current = Math.max(peakAcc.current, p);
67- if (p >= 0.99 && r.recording) setClipped(true);
68- };
69- const inf = await r.open(id || undefined);
70- setInfo(inf);
71- setDevices(await listInputs());
72- const dev = (inf.trackSettings.deviceId as string) ?? "";
73- setDeviceId(dev);
74- setStatus("ready");
75- } catch (e) {
76- setError(`Could not open the microphone: ${(e as Error).message}`);
77- setStatus("closed");
78- }
79- }
80-
81- function start() {
82- if (statusRef.current !== "ready") return;
83- setClipped(false);
84- setElapsed(0);
85- startedAt.current = performance.now();
86- rec.current!.start();
87- setStatus("recording");
88- }
89-
90- async function stop() {
91- if (statusRef.current !== "recording") return;
92- setStatus("saving");
93- const r = rec.current!;
94- const x = await r.stop();
95- const fs = r.sampleRate;
96- if (x.length < fs * 0.5) {
97- setError("Recording was shorter than half a second and was discarded.");
98- setStatus("ready");
99- return;
100- }
101- const seg = detectSegment(x, fs);
102- const meta: RecordingMeta = {
103- id: newId(),
104- createdAt: Date.now(),
105- label: label.trim() || "unlabelled",
106- notes: "",
107- material: "paper",
108- source: "mic",
109- sampleRate: fs,
110- length: x.length,
111- segment: seg,
112- segmentManual: false,
113- capture: r.info ?? undefined,
114- };
115- await onNew(meta, x);
116- setStatus("ready");
117- }
118-
119- // space bar toggles recording (ignored while typing)
120- useEffect(() => {
121- const onKey = (e: KeyboardEvent) => {
122- if (e.code !== "Space" || e.repeat) return;
123- const t = e.target as HTMLElement;
124- if (t.closest("input, textarea, select, button")) return;
125- if (statusRef.current === "ready") {
126- e.preventDefault();
127- start();
128- } else if (statusRef.current === "recording") {
129- e.preventDefault();
130- void stop();
131- }
132- };
133- window.addEventListener("keydown", onKey);
134- return () => window.removeEventListener("keydown", onKey);
135- });
136-
137- async function importFiles(files: FileList | null) {
138- if (!files) return;
139- setError(null);
140- for (const f of Array.from(files)) {
141- const buf = await f.arrayBuffer();
142- let fs: number;
143- let x: Float32Array;
144- let note = "";
145- const d = decodeWav(buf);
146- if (d) {
147- fs = d.sampleRate;
148- x = d.samples;
149- if (d.channels > 1) note = `File had ${d.channels} channels; only the first is used.`;
150- } else {
151- // other formats: let the browser decode (this resamples to the context rate)
152- try {
153- const ctx = new OfflineAudioContext(1, 1, 48000);
154- const ab = await ctx.decodeAudioData(buf);
155- fs = ab.sampleRate;
156- x = ab.getChannelData(0).slice();
157- note = "Decoded by the browser (not WAV): may have been resampled or lossy-compressed.";
158- } catch {
159- setError(`Could not read ${f.name}.`);
160- continue;
161- }
162- }
163- const name = f.name.replace(/\.[^.]+$/, "");
164- await onNew(
165- {
166- id: newId(),
167- createdAt: Date.now(),
168- label: label.trim() || "unlabelled",
169- notes: note,
170- material: "paper",
171- source: "file",
172- fileName: f.name || name,
173- sampleRate: fs,
174- length: x.length,
175- segment: detectSegment(x, fs),
176- segmentManual: false,
177- },
178- x,
179- );
180- }
181- }
182-
183- async function addSynthetic() {
184- const fs = 48000;
185- const x = syntheticTear({ tearSeconds: synthT, sampleRate: fs, seed: Math.floor(Math.random() * 1e9) });
186- await onNew(
187- {
188- id: newId(),
189- createdAt: Date.now(),
190- label: `synthetic ${synthT} s`,
191- notes: "Synthetic: 4000 identical-shape clicks with random times and amplitudes. Not a real recording.",
192- material: "synthetic",
193- source: "synthetic",
194- sampleRate: fs,
195- length: x.length,
196- segment: detectSegment(x, fs),
197- segmentManual: false,
198- },
199- x,
200- );
201- }
202-
203- const s = info?.trackSettings ?? {};
204- const processingOn = ["echoCancellation", "noiseSuppression", "autoGainControl"].filter((k) => s[k] === true);
205- const meterPct = Math.max(0, Math.min(100, ((level + 60) / 60) * 100));
206-
207- return (
208- <section className="card recordbar" aria-label="Record">
209- <div className="rb-row">
210- <div className="rb-label">
211- <label htmlFor="speed-label">Speed label for the next recording</label>
212- <div className="chips">
213- {PRESET_LABELS.map((l) => (
214- <button key={l} className={`chip ${l === label ? "on" : ""}`} onClick={() => setLabel(l)}>
215- {l}
216- </button>
217- ))}
218- </div>
219- <input
220- id="speed-label"
221- list="known-labels"
222- value={label}
223- onChange={(e) => setLabel(e.target.value)}
224- placeholder="or type your own label"
225- />
226- <datalist id="known-labels">
227- {knownLabels.map((l) => (
228- <option key={l} value={l} />
229- ))}
230- </datalist>
231- </div>
232-
233- <div className="rb-controls">
234- {status === "closed" || status === "opening" ? (
235- <button className="primary big" onClick={() => open()} disabled={status === "opening"}>
236- {status === "opening" ? "Opening…" : "Enable microphone"}
237- </button>
238- ) : (
239- <>
240- <button
241- className={`primary big ${status === "recording" ? "recording" : ""}`}
242- onClick={() => (status === "recording" ? stop() : start())}
243- disabled={status === "saving"}
244- >
245- {status === "recording" ? `■ Stop ${elapsed.toFixed(1)} s` : status === "saving" ? "Saving…" : "● Record"}
246- </button>
247- <div className="hint">Space bar also starts / stops.</div>
248- <div className="meter" title="Peak level (dBFS)">
249- <div className="meter-fill" style={{ width: `${meterPct}%` }} />
250- <span className="meter-text">{level > -119 ? `${level.toFixed(0)} dBFS` : "–"}</span>
251- </div>
252- {clipped && <div className="warn">⚠ Clipping in this recording: energy will be underestimated. Move the paper further from the mic.</div>}
253- </>
254- )}
255- </div>
256- </div>
257-
258- <p className="howto">
259- Press record, keep still for about a second, tear one strip off the full 11 inch sheet, keep still for another second, then stop.
260- Keep the paper at the same distance and position relative to the microphone every time.
261- </p>
262-
263- {info && (
264- <div className="capture-info">
265- <span>
266- <b>{info.deviceLabel || "microphone"}</b>
267- </span>
268- {devices.length > 1 && (
269- <select value={deviceId} onChange={(e) => open(e.target.value)} disabled={status === "recording"} aria-label="Input device">
270- {devices.map((d) => (
271- <option key={d.deviceId} value={d.deviceId}>
272- {d.label || d.deviceId}
273- </option>
274- ))}
275- </select>
276- )}
277- <span>{info.contextSampleRate} Hz</span>
278- <span>{String(s.channelCount ?? "?")} ch</span>
279- {processingOn.length ? (
280- <span className="warn">⚠ Browser processing still on: {processingOn.join(", ")}</span>
281- ) : (
282- <span className="ok">Browser processing off (echo cancellation, noise suppression, auto gain)</span>
283- )}
284- {typeof s.sampleRate === "number" && s.sampleRate !== info.contextSampleRate && (
285- <span className="warn">⚠ Mic rate {String(s.sampleRate)} Hz ≠ capture rate: audio is being resampled</span>
286- )}
287- </div>
288- )}
289- {error && <div className="warn">{error}</div>}
290-
291- <details className="more">
292- <summary>Import a file or add a synthetic test tear</summary>
293- <div className="more-body">
294- <label className="filepick">
295- Import WAV file(s) (labelled with the speed label above)
296- <input type="file" accept=".wav,audio/*" multiple onChange={(e) => importFiles(e.target.files)} />
297- </label>
298- <div className="synth">
299- <span>Synthetic tear (identical clicks, for checking the analysis):</span>
300- <select value={synthT} onChange={(e) => setSynthT(+e.target.value)} aria-label="Synthetic tear duration">
301- {[0.3, 1, 3, 10].map((t) => (
302- <option key={t} value={t}>
303- {t} s
304- </option>
305- ))}
306- </select>
307- <button onClick={addSynthetic}>Add</button>
308- </div>
309- </div>
310- </details>
311- </section>
312- );
313-}
src/components/RecordPanel.tsxadded+149−0View file
@@ -0,0 +1,149 @@
1+import { useEffect } from "react";
2+import { mic, useMic } from "../audio/mic.ts";
3+import type { CaptureInfo } from "../audio/recorder.ts";
4+import { decodeWav } from "../audio/wav.ts";
5+import type { Speed } from "../model.ts";
6+
7+const MAX_SECONDS = 60;
8+
9+interface Props {
10+ speed: Speed;
11+ replacing: boolean; // a recording already exists for this speed
12+ onDone: (samples: Float32Array, fs: number, info: CaptureInfo | null, fileName?: string) => Promise<void>;
13+ onCancel: (() => void) | null;
14+}
15+
16+export function RecordPanel({ speed, replacing, onDone, onCancel }: Props) {
17+ const m = useMic();
18+ const elapsed = m.status === "recording" ? (performance.now() - m.startedAt) / 1000 : 0;
19+
20+ const stop = async () => {
21+ const r = await mic.stop();
22+ if (!r) return;
23+ if (r.samples.length < r.fs * 0.5) {
24+ alert("That recording was shorter than half a second and was not kept.");
25+ return;
26+ }
27+ await onDone(r.samples, r.fs, r.info);
28+ };
29+
30+ useEffect(() => {
31+ if (m.status === "recording" && elapsed > MAX_SECONDS) void stop();
32+ });
33+
34+ // space bar starts / stops (ignored while typing or when a button has focus)
35+ useEffect(() => {
36+ const onKey = (e: KeyboardEvent) => {
37+ if (e.code !== "Space" || e.repeat) return;
38+ if ((e.target as HTMLElement).closest("input, textarea, select, button")) return;
39+ const st = mic.get().status;
40+ if (st === "ready") {
41+ e.preventDefault();
42+ mic.start();
43+ } else if (st === "recording") {
44+ e.preventDefault();
45+ void stop();
46+ }
47+ };
48+ window.addEventListener("keydown", onKey);
49+ return () => window.removeEventListener("keydown", onKey);
50+ });
51+
52+ // leaving this panel mid-recording discards the take
53+ useEffect(() => () => void mic.cancel(), []);
54+
55+ const loadFile = async (f: File | undefined) => {
56+ if (!f) return;
57+ const d = decodeWav(await f.arrayBuffer());
58+ if (!d) {
59+ alert("Only WAV files can be loaded.");
60+ return;
61+ }
62+ await onDone(d.samples, d.sampleRate, null, f.name);
63+ };
64+
65+ const s = m.info?.trackSettings ?? {};
66+ const processingOn = ["echoCancellation", "noiseSuppression", "autoGainControl"].filter((k) => s[k] === true);
67+ const levelDb = 20 * Math.log10(Math.max(m.peak, 1e-6));
68+ const meterPct = Math.max(0, Math.min(100, ((levelDb + 60) / 60) * 100));
69+
70+ return (
71+ <section className="card record-panel">
72+ {replacing && (
73+ <div className="replace-note">
74+ Re-recording. The current recording stays until you finish; the new one then replaces it.
75+ </div>
76+ )}
77+ <ol className="steps">
78+ <li>Press <b>Start</b> (or the space bar) and keep still for about a second.</li>
79+ <li>
80+ Tear one strip off the full 11 inch sheet, taking <b>{speed.target}</b>.
81+ </li>
82+ <li>Keep still for another second, then press <b>Stop</b>.</li>
83+ </ol>
84+
85+ <div className="rec-controls">
86+ {m.status === "closed" || m.status === "opening" ? (
87+ <button className="primary big" onClick={() => mic.open()} disabled={m.status === "opening"}>
88+ {m.status === "opening" ? "Opening…" : "Enable microphone"}
89+ </button>
90+ ) : m.status === "recording" ? (
91+ <button className="primary big recording" onClick={stop}>
92+ ■ Stop · {elapsed.toFixed(1)} s
93+ </button>
94+ ) : (
95+ <button className="primary big" onClick={() => mic.start()} disabled={m.status === "saving"}>
96+ {m.status === "saving" ? "Saving…" : "● Start"}
97+ </button>
98+ )}
99+ {m.status !== "closed" && m.status !== "opening" && (
100+ <div className="meter" title="Input peak level">
101+ <div className="meter-fill" style={{ width: `${meterPct}%` }} />
102+ <span className="meter-text">{levelDb > -119 ? `${levelDb.toFixed(0)} dBFS` : "–"}</span>
103+ </div>
104+ )}
105+ {onCancel && (
106+ <button onClick={() => (m.status === "recording" ? mic.cancel().then(onCancel) : onCancel())}>Cancel</button>
107+ )}
108+ </div>
109+ {m.clipped && m.status === "recording" && (
110+ <div className="warn">⚠ Clipping: the sound hit full scale, so its energy will be underestimated. Tear further from the microphone and re-record.</div>
111+ )}
112+ {m.error && <div className="warn">{m.error}</div>}
113+
114+ {m.info && (
115+ <div className="capture-info">
116+ <span>{m.info.deviceLabel || "Microphone"}</span>
117+ {m.devices.length > 1 && (
118+ <select
119+ value={String(s.deviceId ?? "")}
120+ onChange={(e) => mic.open(e.target.value)}
121+ disabled={m.status === "recording"}
122+ aria-label="Input device"
123+ >
124+ {m.devices.map((d) => (
125+ <option key={d.deviceId} value={d.deviceId}>
126+ {d.label || d.deviceId}
127+ </option>
128+ ))}
129+ </select>
130+ )}
131+ <span>{m.info.contextSampleRate} Hz</span>
132+ {processingOn.length ? (
133+ <span className="warn">⚠ Browser processing still on: {processingOn.join(", ")}</span>
134+ ) : (
135+ <span className="ok">✓ Browser processing off</span>
136+ )}
137+ {typeof s.sampleRate === "number" && s.sampleRate !== m.info.contextSampleRate && (
138+ <span className="warn">⚠ Audio is being resampled from {String(s.sampleRate)} Hz</span>
139+ )}
140+ </div>
141+ )}
142+
143+ <label className="file-link">
144+ or load a WAV file for this speed
145+ <input type="file" accept=".wav,audio/wav" onChange={(e) => loadFile(e.target.files?.[0])} />
146+ </label>
147+ </section>
148+ );
149+}
src/components/RecordingView.tsxdeleted+0−550View file
@@ -1,550 +0,0 @@
1-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
2-import { CanvasPlot, drawLine, readTheme, type PointerInfo, type Scales, type Theme } from "./CanvasPlot.tsx";
3-import { detectSegment, frameLevels, smoothLog, spectrogram, type Analysis, type AnalysisSettings, type Segment } from "../analysis/analyze.ts";
4-import type { RecordingMeta } from "../storage/db.ts";
5-import { encodeWavFloat32 } from "../audio/wav.ts";
6-import { colorFor, db10, download, fmtDate, fmtHz, fmtSec, getAnalysis, getAudio, groupStyle, PRESET_LABELS, safeName } from "../model.ts";
7-import { magma } from "../colormap.ts";
8-
9-interface Props {
10- meta: RecordingMeta;
11- all: RecordingMeta[];
12- settings: AnalysisSettings;
13- onUpdate: (m: RecordingMeta) => void;
14- onDelete: (m: RecordingMeta) => void;
15-}
16-
17-const SMOOTHING: [string, number][] = [
18- ["none", 0],
19- ["1/24 octave", 1 / 24],
20- ["1/12 octave", 1 / 12],
21- ["1/6 octave", 1 / 6],
22- ["1/3 octave", 1 / 3],
23-];
24-
25-let playCtx: AudioContext | null = null;
26-let playing: AudioBufferSourceNode | null = null;
27-
28-function play(x: Float32Array, fs: number, a: number, b: number) {
29- stopPlay();
30- playCtx ??= new AudioContext();
31- const s = Math.max(0, Math.floor(a * fs));
32- const e = Math.min(x.length, Math.ceil(b * fs));
33- const buf = playCtx.createBuffer(1, Math.max(1, e - s), fs);
34- buf.copyToChannel(x.subarray(s, e) as Float32Array<ArrayBuffer>, 0);
35- const src = playCtx.createBufferSource();
36- src.buffer = buf;
37- src.connect(playCtx.destination);
38- src.start();
39- playing = src;
40-}
41-
42-function stopPlay() {
43- try {
44- playing?.stop();
45- } catch {
46- /* already stopped */
47- }
48- playing = null;
49-}
50-
51-export function RecordingView({ meta, all, settings, onUpdate, onDelete }: Props) {
52- const [x, setX] = useState<Float32Array | null>(null);
53- const [analysis, setAnalysis] = useState<Analysis | null>(null);
54- const dur = meta.length / meta.sampleRate;
55- const [view, setView] = useState<[number, number]>([0, dur]);
56- const [seg, setSeg] = useState<Segment | null>(meta.segment);
57- const [smoothing, setSmoothing] = useState(1 / 12);
58- const [notes, setNotes] = useState(meta.notes);
59- const [label, setLabel] = useState(meta.label);
60-
61- useEffect(() => {
62- let live = true;
63- setX(null);
64- setView([0, meta.length / meta.sampleRate]);
65- setNotes(meta.notes);
66- setLabel(meta.label);
67- getAudio(meta.id).then((a) => live && setX(a));
68- return () => {
69- live = false;
70- stopPlay();
71- };
72- }, [meta.id, meta.length, meta.sampleRate, meta.notes, meta.label]);
73-
74- useEffect(() => setSeg(meta.segment), [meta.segment]);
75-
76- useEffect(() => {
77- let live = true;
78- setAnalysis(null);
79- getAnalysis(meta, settings).then((a) => live && setAnalysis(a));
80- return () => {
81- live = false;
82- };
83- }, [meta, settings]);
84-
85- const fs = meta.sampleRate;
86- const levels = useMemo(() => (x ? frameLevels(x, fs, 0.005) : null), [x, fs]);
87- const spec = useMemo(() => (x ? spectrogram(x, fs) : null), [x, fs]);
88- const specImage = useMemo(() => (spec ? spectrogramImage(spec) : null), [spec]);
89-
90- const commitSeg = (s: Segment | null) => {
91- onUpdate({ ...meta, segment: s, segmentManual: true });
92- };
93-
94- // ---------- shared time-axis interaction ----------
95- const drag = useRef<{ kind: "start" | "end" | "pan"; px0: number; view0: [number, number] } | null>(null);
96- const edgeAt = (p: PointerInfo): "start" | "end" | null => {
97- if (!seg) return null;
98- if (Math.abs(p.px - p.scales.x(seg.start)) < 7) return "start";
99- if (Math.abs(p.px - p.scales.x(seg.end)) < 7) return "end";
100- return null;
101- };
102- const clampView = (a: number, b: number): [number, number] => {
103- const w = Math.min(dur, Math.max(b - a, 0.002));
104- let s = Math.max(0, a);
105- if (s + w > dur) s = dur - w;
106- return [s, s + w];
107- };
108- const timeHandlers = {
109- onWheel: (p: PointerInfo, ev: WheelEvent) => {
110- if (Math.abs(ev.deltaX) > Math.abs(ev.deltaY)) {
111- const shift = (ev.deltaX / (p.scales.right - p.scales.left)) * (view[1] - view[0]);
112- setView(clampView(view[0] + shift, view[1] + shift));
113- return;
114- }
115- const f = Math.exp(ev.deltaY * 0.0025);
116- const t = Math.min(Math.max(p.xv, view[0]), view[1]);
117- setView(clampView(t - (t - view[0]) * f, t + (view[1] - t) * f));
118- },
119- onPointer: (type: "down" | "move" | "up", p: PointerInfo) => {
120- if (type === "down") {
121- drag.current = { kind: edgeAt(p) ?? "pan", px0: p.px, view0: view };
122- } else if (type === "move" && drag.current) {
123- const d = drag.current;
124- if (d.kind === "pan") {
125- const dt = ((p.px - d.px0) / (p.scales.right - p.scales.left)) * (d.view0[1] - d.view0[0]);
126- setView(clampView(d.view0[0] - dt, d.view0[1] - dt));
127- } else if (seg) {
128- const t = Math.min(Math.max(p.xv, 0), dur);
129- setSeg(d.kind === "start" ? { start: Math.min(t, seg.end - 0.005), end: seg.end } : { start: seg.start, end: Math.max(t, seg.start + 0.005) });
130- }
131- } else if (type === "up") {
132- if (drag.current && drag.current.kind !== "pan" && seg) commitSeg(seg);
133- drag.current = null;
134- }
135- },
136- onDoubleClick: () => setView([0, dur]),
137- cursor: (p: PointerInfo) => (edgeAt(p) ? "ew-resize" : "grab"),
138- };
139-
140- const drawSeg = useCallback(
141- (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
142- if (!seg) return;
143- const a = s.x(seg.start);
144- const b = s.x(seg.end);
145- ctx.fillStyle = th.seg;
146- ctx.fillRect(a, s.top, b - a, s.bottom - s.top);
147- ctx.strokeStyle = th.ink2;
148- ctx.lineWidth = 1.5;
149- ctx.beginPath();
150- ctx.moveTo(a, s.top);
151- ctx.lineTo(a, s.bottom);
152- ctx.moveTo(b, s.top);
153- ctx.lineTo(b, s.bottom);
154- ctx.stroke();
155- },
156- [seg],
157- );
158-
159- const { slot } = groupStyle(meta.label, all);
160- const mainColor = (th: Theme) => colorFor(slot, th.series, th.ink2);
161-
162- const levelRange = useMemo<[number, number]>(() => {
163- if (!levels) return [-100, 0];
164- const dbs = Array.from(levels.power, (p) => db10(p)).sort((a, b) => a - b);
165- const lo = dbs[Math.floor(dbs.length * 0.01)] ?? -100;
166- return [Math.max(-140, Math.floor((lo - 6) / 10) * 10), 0];
167- }, [levels]);
168-
169- const drawLevel = useCallback(
170- (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
171- drawSeg(ctx, s, th);
172- if (!levels) return;
173- const { frameSec, power } = levels;
174- const i0 = Math.max(0, Math.floor(view[0] / frameSec) - 1);
175- const i1 = Math.min(power.length, Math.ceil(view[1] / frameSec) + 1);
176- const step = Math.max(1, Math.floor((i1 - i0) / ((s.right - s.left) * 2)));
177- const xs: number[] = [];
178- const ys: number[] = [];
179- for (let i = i0; i < i1; i += step) {
180- let m = 0;
181- for (let j = i; j < Math.min(i + step, i1); j++) m = Math.max(m, power[j]);
182- xs.push((i + step / 2) * frameSec);
183- ys.push(db10(m));
184- }
185- drawLine(ctx, s, xs, ys, mainColor(th), 1.5);
186- },
187- // eslint-disable-next-line react-hooks/exhaustive-deps
188- [levels, view, drawSeg, slot],
189- );
190-
191- const waveMax = useMemo(() => {
192- if (!x) return 1;
193- let m = 0;
194- for (let i = 0; i < x.length; i++) m = Math.max(m, Math.abs(x[i]));
195- return Math.max(m * 1.05, 1e-4);
196- }, [x]);
197-
198- const drawWave = useCallback(
199- (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
200- drawSeg(ctx, s, th);
201- if (!x) return;
202- const color = mainColor(th);
203- const a = Math.max(0, Math.floor(view[0] * fs));
204- const b = Math.min(x.length, Math.ceil(view[1] * fs));
205- const px = s.right - s.left;
206- const perPx = (b - a) / px;
207- if (perPx < 2) {
208- const xs: number[] = [];
209- const ys: number[] = [];
210- for (let i = Math.max(0, a - 1); i < Math.min(x.length, b + 1); i++) {
211- xs.push(i / fs);
212- ys.push(x[i]);
213- }
214- drawLine(ctx, s, xs, ys, color, 1.5);
215- if (perPx < 0.15) {
216- ctx.fillStyle = color;
217- for (let i = 0; i < xs.length; i++) ctx.fillRect(s.x(xs[i]) - 1.5, s.y(ys[i]) - 1.5, 3, 3);
218- }
219- return;
220- }
221- ctx.fillStyle = color;
222- for (let c = 0; c < px; c++) {
223- const i0 = a + Math.floor(c * perPx);
224- const i1 = Math.min(b, a + Math.floor((c + 1) * perPx));
225- let lo = Infinity;
226- let hi = -Infinity;
227- for (let i = i0; i < i1; i++) {
228- const v = x[i];
229- if (v < lo) lo = v;
230- if (v > hi) hi = v;
231- }
232- if (lo > hi) continue;
233- const y0 = s.y(hi);
234- const y1 = s.y(lo);
235- ctx.fillRect(s.left + c, y0, 1, Math.max(1, y1 - y0));
236- }
237- },
238- // eslint-disable-next-line react-hooks/exhaustive-deps
239- [x, view, fs, drawSeg, slot],
240- );
241-
242- const drawSpec = useCallback(
243- (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
244- if (spec && specImage) {
245- const c0 = (view[0] - spec.t0) / spec.dt;
246- const c1 = (view[1] - spec.t0) / spec.dt;
247- ctx.imageSmoothingEnabled = c1 - c0 < s.right - s.left;
248- const sx0 = Math.max(0, c0);
249- const sx1 = Math.min(spec.cols, c1);
250- const dx0 = s.x(spec.t0 + sx0 * spec.dt);
251- const dx1 = s.x(spec.t0 + sx1 * spec.dt);
252- if (sx1 > sx0) ctx.drawImage(specImage, sx0, 0, sx1 - sx0, spec.bins, dx0, s.top, dx1 - dx0, s.bottom - s.top);
253- }
254- if (seg) {
255- ctx.strokeStyle = th.surface;
256- ctx.lineWidth = 1.5;
257- ctx.setLineDash([4, 3]);
258- ctx.beginPath();
259- for (const t of [seg.start, seg.end]) {
260- ctx.moveTo(s.x(t), s.top);
261- ctx.lineTo(s.x(t), s.bottom);
262- }
263- ctx.stroke();
264- ctx.setLineDash([]);
265- }
266- },
267- [spec, specImage, view, seg],
268- );
269-
270- // ---------- spectrum ----------
271- const fLo = 20;
272- const fHi = fs / 2;
273- const specLines = useMemo(() => {
274- if (!analysis) return null;
275- const tear = smoothLog(analysis.freqs, analysis.esd, fLo, fHi, smoothing);
276- const bg = analysis.noiseEsd ? smoothLog(analysis.freqs, analysis.noiseEsd, fLo, fHi, smoothing) : null;
277- return { f: tear.f, tear: tear.v.map(db10), bg: bg ? bg.v.map(db10) : null };
278- }, [analysis, smoothing, fHi]);
279- const specRange = useMemo<[number, number]>(() => {
280- if (!specLines) return [-160, -60];
281- const top = Math.max(...specLines.tear.filter(Number.isFinite));
282- return [Math.floor((top - 80) / 10) * 10, Math.ceil((top + 3) / 10) * 10];
283- }, [specLines]);
284-
285- const drawSpectrum = useCallback(
286- (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
287- if (!specLines) return;
288- // grey out what lies outside the analysis band
289- ctx.fillStyle = th.seg;
290- const bl = s.x(settings.bandLow);
291- const bh = s.x(Math.min(settings.bandHigh, fHi));
292- ctx.fillRect(s.left, s.top, bl - s.left, s.bottom - s.top);
293- ctx.fillRect(bh, s.top, s.right - bh, s.bottom - s.top);
294- if (specLines.bg) drawLine(ctx, s, specLines.f, specLines.bg, th.muted, 2, [5, 4]);
295- drawLine(ctx, s, specLines.f, specLines.tear, mainColor(th), 2);
296- },
297- // eslint-disable-next-line react-hooks/exhaustive-deps
298- [specLines, settings, fHi, slot],
299- );
300-
301- const specHover = (p: PointerInfo) => {
302- if (!specLines) return null;
303- let best = 0;
304- for (let i = 1; i < specLines.f.length; i++) if (Math.abs(Math.log(specLines.f[i] / p.xv)) < Math.abs(Math.log(specLines.f[best] / p.xv))) best = i;
305- const lines = [fmtHz(specLines.f[best]), `tear: ${specLines.tear[best].toFixed(1)} dB`];
306- if (specLines.bg) lines.push(`background: ${specLines.bg[best].toFixed(1)} dB`);
307- return { lines, x: specLines.f[best], y: specLines.tear[best] };
308- };
309-
310- const timeHover = (p: PointerInfo) => {
311- const lines = [`${p.xv.toFixed(p.xv < 10 ? 3 : 2)} s`];
312- if (levels) {
313- const i = Math.floor(p.xv / levels.frameSec);
314- if (i >= 0 && i < levels.power.length) lines.push(`level: ${db10(levels.power[i]).toFixed(1)} dBFS (5 ms RMS)`);
315- }
316- return { lines };
317- };
318-
319- // ---------- actions ----------
320- const saveNotes = () => notes !== meta.notes && onUpdate({ ...meta, notes });
321- const saveLabel = (l: string) => {
322- setLabel(l);
323- if (l.trim() && l !== meta.label) onUpdate({ ...meta, label: l.trim() });
324- };
325- const autoDetect = () => {
326- if (!x) return;
327- const s = detectSegment(x, fs);
328- onUpdate({ ...meta, segment: s, segmentManual: false });
329- };
330- const exportWav = () => {
331- if (!x) return;
332- const d = new Date(meta.createdAt).toISOString().replace(/[:]/g, "-").slice(0, 19);
333- download(encodeWavFloat32(x, fs), `${d}_${safeName(meta.label)}_${meta.id.slice(0, 6)}.wav`);
334- };
335-
336- const a = analysis;
337- const warnings: string[] = [];
338- if (!seg) warnings.push("No tear was found automatically. Zoom so the tear fills the view and press “Use visible range as tear”.");
339- if (a && a.nearClip > 0) warnings.push(`${a.nearClip} samples in the tear are at or near full scale (clipping). The energy is underestimated and the spectrum is distorted.`);
340- if (a && !a.noiseEsd) warnings.push("Not enough quiet audio before or after the tear to estimate the background, so nothing was subtracted.");
341- else if (a && a.snrDb < 10) warnings.push(`The tear is only ${a.snrDb.toFixed(1)} dB above the background in the analysis band; the energy estimate is sensitive to the background subtraction.`);
342- if (seg && (seg.start < 0.05 || seg.end > dur - 0.05)) warnings.push("The tear touches the start or end of the recording and may be cut off.");
343-
344- return (
345- <div className="recview">
346- <section className="card">
347- <div className="rv-head">
348- <div className="rv-title">
349- <input
350- className="label-edit"
351- list="known-labels"
352- value={label}
353- onChange={(e) => setLabel(e.target.value)}
354- onBlur={(e) => saveLabel(e.target.value)}
355- onKeyDown={(e) => e.key === "Enter" && (e.target as HTMLInputElement).blur()}
356- aria-label="Speed label"
357- />
358- <select value="" onChange={(e) => e.target.value && saveLabel(e.target.value)} aria-label="Choose a preset label">
359- <option value="">preset…</option>
360- {PRESET_LABELS.map((l) => (
361- <option key={l}>{l}</option>
362- ))}
363- </select>
364- <span className={`badge ${meta.source}`}>{meta.source === "mic" ? "microphone" : meta.source}</span>
365- <span className="muted">
366- {fmtDate(meta.createdAt)} · {fmtSec(dur)} · {fs} Hz{meta.fileName ? ` · ${meta.fileName}` : ""}
367- </span>
368- </div>
369- <div className="rv-actions">
370- <button disabled={!x || !seg} onClick={() => x && seg && play(x, fs, seg.start, seg.end)}>
371- ▶ Play tear
372- </button>
373- <button disabled={!x} onClick={() => x && play(x, fs, 0, dur)}>
374- ▶ Play all
375- </button>
376- <button onClick={stopPlay}>■</button>
377- <button disabled={!x} onClick={exportWav}>
378- Download WAV
379- </button>
380- <button className="danger" onClick={() => onDelete(meta)}>
381- Delete
382- </button>
383- </div>
384- </div>
385- <textarea
386- className="notes"
387- placeholder="Notes (paper type, how it was torn, anything unusual)"
388- value={notes}
389- onChange={(e) => setNotes(e.target.value)}
390- onBlur={saveNotes}
391- rows={1}
392- />
393- {warnings.map((w) => (
394- <div key={w} className="warn">
395- ⚠ {w}
396- </div>
397- ))}
398- <Stats a={a} settings={settings} manual={meta.segmentManual} />
399- </section>
400-
401- <section className="card">
402- <div className="plot-head">
403- <h3>Over time</h3>
404- <div className="toolbar">
405- <span className="hint">Scroll to zoom, drag to pan, drag the edges of the shaded tear to adjust it, double-click to reset.</span>
406- <button disabled={!seg} onClick={() => seg && setView(clampView(seg.start - 0.1 * (seg.end - seg.start), seg.end + 0.1 * (seg.end - seg.start)))}>
407- Zoom to tear
408- </button>
409- <button onClick={() => setView([0, dur])}>Full</button>
410- <button onClick={() => commitSeg({ start: view[0], end: view[1] })}>Use visible range as tear</button>
411- <button disabled={!x} onClick={autoDetect} title="Re-run automatic tear detection">
412- Auto-detect tear
413- </button>
414- </div>
415- </div>
416- <CanvasPlot
417- height={150}
418- xRange={view}
419- yRange={levelRange}
420- xLabel="time (s)"
421- yLabel="level (dBFS)"
422- hideXTicks
423- draw={drawLevel}
424- hover={timeHover}
425- ariaLabel="Sound level over time"
426- {...timeHandlers}
427- />
428- <CanvasPlot
429- height={150}
430- xRange={view}
431- yRange={[-waveMax, waveMax]}
432- xLabel="time (s)"
433- yLabel="waveform"
434- hideXTicks
435- draw={drawWave}
436- hover={(p) => ({ lines: [`${p.xv.toFixed(4)} s`] })}
437- ariaLabel="Waveform"
438- {...timeHandlers}
439- />
440- <CanvasPlot
441- height={220}
442- xRange={view}
443- yRange={[0, fs / 2]}
444- xLabel="time (s)"
445- yLabel="frequency (Hz)"
446- draw={drawSpec}
447- hover={(p) => ({ lines: [`${p.xv.toFixed(3)} s`, fmtHz(p.yv)] })}
448- ariaLabel="Spectrogram"
449- {...timeHandlers}
450- />
451- <p className="caption">
452- Level is the RMS over 5 ms windows. Spectrogram: 1024-point Hann windows, colour spans the top 90 dB of this recording.
453- </p>
454- </section>
455-
456- <section className="card">
457- <div className="plot-head">
458- <h3>Frequency makeup of the tear</h3>
459- <label className="toolbar">
460- smoothing
461- <select value={smoothing} onChange={(e) => setSmoothing(+e.target.value)}>
462- {SMOOTHING.map(([n, v]) => (
463- <option key={n} value={v}>
464- {n}
465- </option>
466- ))}
467- </select>
468- </label>
469- </div>
470- <CanvasPlot
471- height={300}
472- xRange={[fLo, fHi]}
473- xLog
474- yRange={specRange}
475- xLabel="frequency (Hz)"
476- yLabel="energy density (dB re FS²·s/Hz)"
477- draw={drawSpectrum}
478- hover={specHover}
479- ariaLabel="Energy spectral density of the tear"
480- />
481- <div className="legend">
482- <span>
483- <i className="swatch" style={{ background: readThemeColor(slot) }} /> tear (energy spectral density)
484- </span>
485- <span>
486- <i className="swatch dashed" /> background alone over the same duration
487- </span>
488- <span>
489- <i className="swatch shade" /> outside the analysis band ({fmtHz(settings.bandLow)}–{fmtHz(settings.bandHigh)})
490- </span>
491- </div>
492- </section>
493- </div>
494- );
495-}
496-
497-function readThemeColor(slot: number | null) {
498- const th = readTheme(document.documentElement);
499- return colorFor(slot, th.series, th.ink2);
500-}
501-
502-function Stats({ a, settings, manual }: { a: Analysis | null; settings: AnalysisSettings; manual: boolean }) {
503- if (!a) return null;
504- const items: [string, string, string?][] = [
505- ["Tear duration", fmtSec(a.duration), manual ? "set by hand" : "auto-detected"],
506- ["Speed", `${a.speedInPerSec.toFixed(2)} in/s`, `${settings.sheetLengthIn} in ÷ duration`],
507- ["Sound energy", `${db10(a.energy).toFixed(1)} dB`, "re FS²·s, in band, background removed"],
508- ["Mean power", `${db10(a.energy / a.duration).toFixed(1)} dBFS`, "energy ÷ duration"],
509- ["Median frequency", fmtHz(a.medianFreq), "half the energy above, half below"],
510- ["Centroid", fmtHz(a.centroid), "energy-weighted mean frequency"],
511- ["10–90% of energy", `${fmtHz(a.f10)} – ${fmtHz(a.f90)}`],
512- ["Peak", `${a.peakDbfs.toFixed(1)} dBFS`, a.nearClip ? `${a.nearClip} samples near clipping` : "no clipping"],
513- ["Above background", Number.isFinite(a.snrDb) ? `${a.snrDb.toFixed(1)} dB` : "–", a.backgroundDbfs !== null ? `background ${a.backgroundDbfs.toFixed(1)} dBFS, from ${a.noiseSeconds.toFixed(1)} s` : "no background estimate"],
514- ];
515- return (
516- <div className="stats">
517- {items.map(([k, v, sub]) => (
518- <div key={k} className="stat">
519- <div className="stat-k">{k}</div>
520- <div className="stat-v">{v}</div>
521- {sub && <div className="stat-sub">{sub}</div>}
522- </div>
523- ))}
524- </div>
525- );
526-}
527-
528-function spectrogramImage(spec: ReturnType<typeof spectrogram>): HTMLCanvasElement {
529- const c = document.createElement("canvas");
530- c.width = spec.cols;
531- c.height = spec.bins;
532- const ctx = c.getContext("2d")!;
533- const img = ctx.createImageData(spec.cols, spec.bins);
534- const top = spec.maxDb;
535- const range = 90;
536- for (let col = 0; col < spec.cols; col++) {
537- for (let k = 0; k < spec.bins; k++) {
538- const v = (spec.db[col * spec.bins + k] - (top - range)) / range;
539- const [r, g, b] = magma(Math.min(1, Math.max(0, v)));
540- const row = spec.bins - 1 - k;
541- const o = (row * spec.cols + col) * 4;
542- img.data[o] = r;
543- img.data[o + 1] = g;
544- img.data[o + 2] = b;
545- img.data[o + 3] = 255;
546- }
547- }
548- ctx.putImageData(img, 0, 0);
549- return c;
550-}
src/components/TearView.tsxadded+576−0View file
@@ -0,0 +1,576 @@
1+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
2+import { CanvasPlot, drawLine, readTheme, type PointerInfo, type Scales, type Theme } from "./CanvasPlot.tsx";
3+import { detectSegment, frameLevels, smoothLog, spectrogram, type Analysis, type AnalysisSettings, type Segment } from "../analysis/analyze.ts";
4+import type { RecordingMeta } from "../storage/db.ts";
5+import { play, stop as stopPlay, usePlayhead } from "../audio/player.ts";
6+import { colorFor, db10, fmtHz, fmtSec, getAnalysis, getAudio, speedStyle } from "../model.ts";
7+import { magma } from "../colormap.ts";
8+
9+interface Props {
10+ meta: RecordingMeta;
11+ settings: AnalysisSettings;
12+ onUpdate: (m: RecordingMeta) => void;
13+}
14+
15+const SMOOTHING: [string, number][] = [
16+ ["none", 0],
17+ ["1/24 octave", 1 / 24],
18+ ["1/12 octave", 1 / 12],
19+ ["1/6 octave", 1 / 6],
20+ ["1/3 octave", 1 / 3],
21+];
22+
23+export function TearView({ meta, settings, onUpdate }: Props) {
24+ const [x, setX] = useState<Float32Array | null>(null);
25+ const [analysis, setAnalysis] = useState<Analysis | null>(null);
26+ const fs = meta.sampleRate;
27+ const dur = meta.length / fs;
28+ const [seg, setSeg] = useState<Segment | null>(meta.segment);
29+ const playhead = usePlayhead(meta.id);
30+
31+ useEffect(() => {
32+ let live = true;
33+ setX(null);
34+ getAudio(meta.id).then((a) => live && setX(a));
35+ return () => {
36+ live = false;
37+ stopPlay();
38+ };
39+ }, [meta.id]);
40+
41+ useEffect(() => setSeg(meta.segment), [meta.segment]);
42+
43+ useEffect(() => {
44+ let live = true;
45+ getAnalysis(meta, settings).then((a) => live && setAnalysis(a));
46+ return () => {
47+ live = false;
48+ };
49+ }, [meta, settings]);
50+
51+ const levels = useMemo(() => (x ? frameLevels(x, fs, 0.005) : null), [x, fs]);
52+ const spec = useMemo(() => (x ? spectrogram(x, fs) : null), [x, fs]);
53+ const specImage = useMemo(() => (spec ? spectrogramImage(spec) : null), [spec]);
54+ const { slot } = speedStyle(meta.label);
55+ const mainColor = (th: Theme) => colorFor(slot, th.series, th.ink2);
56+
57+ const commitSeg = (s: Segment | null) => {
58+ setSeg(s);
59+ onUpdate({ ...meta, segment: s, segmentManual: true });
60+ };
61+
62+ // ---------- tear range (whole recording) ----------
63+ const drag = useRef<{ kind: "start" | "end" | "new"; anchor: number; px0: number; before: Segment | null } | null>(null);
64+ const edgeAt = (p: PointerInfo): "start" | "end" | null => {
65+ if (!seg) return null;
66+ const ds = Math.abs(p.px - p.scales.x(seg.start));
67+ const de = Math.abs(p.px - p.scales.x(seg.end));
68+ if (Math.min(ds, de) > 8) return null;
69+ return ds <= de ? "start" : "end";
70+ };
71+ const clampT = (t: number) => Math.min(Math.max(t, 0), dur);
72+ const rangeHandlers = {
73+ onPointer: (type: "down" | "move" | "up", p: PointerInfo) => {
74+ if (type === "down") {
75+ drag.current = { kind: edgeAt(p) ?? "new", anchor: clampT(p.xv), px0: p.px, before: seg };
76+ } else if (type === "move" && drag.current) {
77+ const d = drag.current;
78+ const t = clampT(p.xv);
79+ if (d.kind === "new") {
80+ if (Math.abs(p.px - d.px0) > 3) setSeg({ start: Math.min(d.anchor, t), end: Math.max(d.anchor, t) });
81+ } else if (seg) {
82+ // dragging an edge past the other one swaps them
83+ const other = d.kind === "start" ? seg.end : seg.start;
84+ setSeg({ start: Math.min(t, other), end: Math.max(t, other) });
85+ if ((d.kind === "start" && t > other) || (d.kind === "end" && t < other)) d.kind = d.kind === "start" ? "end" : "start";
86+ }
87+ } else if (type === "up" && drag.current) {
88+ const d = drag.current;
89+ drag.current = null;
90+ if (d.kind === "new" && Math.abs(p.px - d.px0) <= 3) return; // a plain click changes nothing
91+ if (seg && seg.end - seg.start >= 0.01) commitSeg(seg);
92+ else setSeg(d.before);
93+ }
94+ },
95+ cursor: (p: PointerInfo) => (edgeAt(p) ? "ew-resize" : "crosshair"),
96+ };
97+
98+ const levelRange = useMemo<[number, number]>(() => {
99+ if (!levels) return [-100, 0];
100+ const dbs = Array.from(levels.power, (p) => db10(p)).sort((a, b) => a - b);
101+ const lo = dbs[Math.floor(dbs.length * 0.01)] ?? -100;
102+ return [Math.max(-140, Math.floor((lo - 6) / 10) * 10), 0];
103+ }, [levels]);
104+
105+ const drawPlayhead = (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
106+ if (playhead === null) return;
107+ ctx.strokeStyle = th.ink;
108+ ctx.lineWidth = 2;
109+ ctx.beginPath();
110+ ctx.moveTo(s.x(playhead), s.top);
111+ ctx.lineTo(s.x(playhead), s.bottom);
112+ ctx.stroke();
113+ };
114+
115+ const drawRange = useCallback(
116+ (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
117+ if (seg) {
118+ const a = s.x(seg.start);
119+ const b = s.x(seg.end);
120+ ctx.fillStyle = th.seg;
121+ ctx.fillRect(a, s.top, b - a, s.bottom - s.top);
122+ }
123+ if (levels) {
124+ const { frameSec, power } = levels;
125+ const perPx = Math.max(1, Math.floor(power.length / ((s.right - s.left) * 2)));
126+ const xs: number[] = [];
127+ const ys: number[] = [];
128+ for (let i = 0; i < power.length; i += perPx) {
129+ let m = 0;
130+ for (let j = i; j < Math.min(i + perPx, power.length); j++) m = Math.max(m, power[j]);
131+ xs.push((i + perPx / 2) * frameSec);
132+ ys.push(db10(m));
133+ }
134+ drawLine(ctx, s, xs, ys, mainColor(th), 1.5);
135+ }
136+ if (seg) {
137+ // edges with grab handles
138+ for (const t of [seg.start, seg.end]) {
139+ const px = s.x(t);
140+ ctx.strokeStyle = th.ink;
141+ ctx.lineWidth = 2;
142+ ctx.beginPath();
143+ ctx.moveTo(px, s.top);
144+ ctx.lineTo(px, s.bottom);
145+ ctx.stroke();
146+ ctx.fillStyle = th.ink;
147+ ctx.beginPath();
148+ ctx.roundRect(px - 4, (s.top + s.bottom) / 2 - 12, 8, 24, 3);
149+ ctx.fill();
150+ }
151+ }
152+ drawPlayhead(ctx, s, th);
153+ },
154+ // eslint-disable-next-line react-hooks/exhaustive-deps
155+ [levels, seg, slot, playhead],
156+ );
157+
158+ // ---------- close-up ----------
159+ const fit = useCallback(
160+ (s: Segment | null): [number, number] => {
161+ if (!s) return [0, dur];
162+ const m = Math.max(0.05, 0.08 * (s.end - s.start));
163+ return [Math.max(0, s.start - m), Math.min(dur, s.end + m)];
164+ },
165+ [dur],
166+ );
167+ const [view, setView] = useState<[number, number]>(() => fit(meta.segment));
168+ useEffect(() => setView(fit(meta.segment)), [meta.id, meta.segment, fit]);
169+ const clampView = (a: number, b: number): [number, number] => {
170+ const w = Math.min(dur, Math.max(b - a, 0.002));
171+ let s = Math.max(0, a);
172+ if (s + w > dur) s = dur - w;
173+ return [s, s + w];
174+ };
175+ const zoom = (f: number, around = (view[0] + view[1]) / 2) => setView(clampView(around - (around - view[0]) * f, around + (view[1] - around) * f));
176+ const pan = useRef<{ px0: number; view0: [number, number] } | null>(null);
177+ const closeHandlers = {
178+ onPointer: (type: "down" | "move" | "up", p: PointerInfo) => {
179+ if (type === "down") pan.current = { px0: p.px, view0: view };
180+ else if (type === "move" && pan.current) {
181+ const d = pan.current;
182+ const dt = ((p.px - d.px0) / (p.scales.right - p.scales.left)) * (d.view0[1] - d.view0[0]);
183+ setView(clampView(d.view0[0] - dt, d.view0[1] - dt));
184+ } else pan.current = null;
185+ },
186+ // pinch on a trackpad (or ctrl + scroll) zooms; plain scrolling scrolls the page
187+ onWheel: (p: PointerInfo, ev: WheelEvent) => {
188+ if (!ev.ctrlKey) return false;
189+ zoom(Math.exp(ev.deltaY * 0.01), Math.min(Math.max(p.xv, view[0]), view[1]));
190+ return true;
191+ },
192+ onDoubleClick: () => setView(fit(seg)),
193+ cursor: () => "grab",
194+ };
195+
196+ const drawEdges = (ctx: CanvasRenderingContext2D, s: Scales, color: string) => {
197+ if (!seg) return;
198+ ctx.strokeStyle = color;
199+ ctx.lineWidth = 1.5;
200+ ctx.setLineDash([5, 4]);
201+ ctx.beginPath();
202+ for (const t of [seg.start, seg.end]) {
203+ ctx.moveTo(s.x(t), s.top);
204+ ctx.lineTo(s.x(t), s.bottom);
205+ }
206+ ctx.stroke();
207+ ctx.setLineDash([]);
208+ };
209+
210+ const waveMax = useMemo(() => {
211+ if (!x) return 1;
212+ let m = 0;
213+ for (let i = 0; i < x.length; i++) m = Math.max(m, Math.abs(x[i]));
214+ return Math.max(m * 1.05, 1e-4);
215+ }, [x]);
216+
217+ const drawWave = useCallback(
218+ (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
219+ if (x) {
220+ const color = mainColor(th);
221+ const a = Math.max(0, Math.floor(view[0] * fs));
222+ const b = Math.min(x.length, Math.ceil(view[1] * fs));
223+ const px = s.right - s.left;
224+ const perPx = (b - a) / px;
225+ if (perPx < 2) {
226+ const xs: number[] = [];
227+ const ys: number[] = [];
228+ for (let i = Math.max(0, a - 1); i < Math.min(x.length, b + 1); i++) {
229+ xs.push(i / fs);
230+ ys.push(x[i]);
231+ }
232+ drawLine(ctx, s, xs, ys, color, 1.5);
233+ if (perPx < 0.15) {
234+ ctx.fillStyle = color;
235+ for (let i = 0; i < xs.length; i++) ctx.fillRect(s.x(xs[i]) - 1.5, s.y(ys[i]) - 1.5, 3, 3);
236+ }
237+ } else {
238+ ctx.fillStyle = color;
239+ for (let c = 0; c < px; c++) {
240+ const i0 = a + Math.floor(c * perPx);
241+ const i1 = Math.min(b, a + Math.floor((c + 1) * perPx));
242+ let lo = Infinity;
243+ let hi = -Infinity;
244+ for (let i = i0; i < i1; i++) {
245+ const v = x[i];
246+ if (v < lo) lo = v;
247+ if (v > hi) hi = v;
248+ }
249+ if (lo > hi) continue;
250+ const y0 = s.y(hi);
251+ ctx.fillRect(s.left + c, y0, 1, Math.max(1, s.y(lo) - y0));
252+ }
253+ }
254+ }
255+ drawEdges(ctx, s, th.ink2);
256+ drawPlayhead(ctx, s, th);
257+ },
258+ // eslint-disable-next-line react-hooks/exhaustive-deps
259+ [x, view, fs, seg, slot, playhead],
260+ );
261+
262+ const drawSpec = useCallback(
263+ (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
264+ if (spec && specImage) {
265+ const c0 = (view[0] - spec.t0) / spec.dt;
266+ const c1 = (view[1] - spec.t0) / spec.dt;
267+ ctx.imageSmoothingEnabled = c1 - c0 < s.right - s.left;
268+ const sx0 = Math.max(0, c0);
269+ const sx1 = Math.min(spec.cols, c1);
270+ const dx0 = s.x(spec.t0 + sx0 * spec.dt);
271+ const dx1 = s.x(spec.t0 + sx1 * spec.dt);
272+ if (sx1 > sx0) ctx.drawImage(specImage, sx0, 0, sx1 - sx0, spec.bins, dx0, s.top, dx1 - dx0, s.bottom - s.top);
273+ }
274+ drawEdges(ctx, s, "#ffffff");
275+ if (playhead !== null) {
276+ ctx.strokeStyle = "#ffffff";
277+ ctx.lineWidth = 2;
278+ ctx.beginPath();
279+ ctx.moveTo(s.x(playhead), s.top);
280+ ctx.lineTo(s.x(playhead), s.bottom);
281+ ctx.stroke();
282+ }
283+ void th;
284+ },
285+ // eslint-disable-next-line react-hooks/exhaustive-deps
286+ [spec, specImage, view, seg, playhead],
287+ );
288+
289+ // ---------- spectrum ----------
290+ const [smoothing, setSmoothing] = useState(1 / 12);
291+ const fLo = 20;
292+ const fHi = fs / 2;
293+ const specLines = useMemo(() => {
294+ if (!analysis) return null;
295+ const tear = smoothLog(analysis.freqs, analysis.esd, fLo, fHi, smoothing);
296+ const bg = analysis.noiseEsd ? smoothLog(analysis.freqs, analysis.noiseEsd, fLo, fHi, smoothing) : null;
297+ return { f: tear.f, tear: tear.v.map(db10), bg: bg ? bg.v.map(db10) : null };
298+ }, [analysis, smoothing, fHi]);
299+ const specRange = useMemo<[number, number]>(() => {
300+ if (!specLines) return [-160, -60];
301+ const top = Math.max(...specLines.tear.filter(Number.isFinite));
302+ return [Math.floor((top - 70) / 10) * 10, Math.ceil((top + 3) / 10) * 10];
303+ }, [specLines]);
304+ const drawSpectrum = useCallback(
305+ (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
306+ if (!specLines) return;
307+ ctx.fillStyle = th.seg;
308+ const bl = s.x(settings.bandLow);
309+ const bh = s.x(Math.min(settings.bandHigh, fHi));
310+ ctx.fillRect(s.left, s.top, bl - s.left, s.bottom - s.top);
311+ ctx.fillRect(bh, s.top, s.right - bh, s.bottom - s.top);
312+ if (specLines.bg) drawLine(ctx, s, specLines.f, specLines.bg, th.muted, 2, [5, 4]);
313+ drawLine(ctx, s, specLines.f, specLines.tear, mainColor(th), 2);
314+ },
315+ // eslint-disable-next-line react-hooks/exhaustive-deps
316+ [specLines, settings, fHi, slot],
317+ );
318+ const specHover = (p: PointerInfo) => {
319+ if (!specLines) return null;
320+ let best = 0;
321+ for (let i = 1; i < specLines.f.length; i++) if (Math.abs(Math.log(specLines.f[i] / p.xv)) < Math.abs(Math.log(specLines.f[best] / p.xv))) best = i;
322+ const lines = [fmtHz(specLines.f[best]), `tear: ${specLines.tear[best].toFixed(1)} dB`];
323+ if (specLines.bg) lines.push(`background: ${specLines.bg[best].toFixed(1)} dB`);
324+ return { lines, x: specLines.f[best], y: specLines.tear[best] };
325+ };
326+
327+ const a = analysis;
328+ const warnings: string[] = [];
329+ if (!seg) warnings.push("No tear was found automatically. Drag across the plot below to mark it.");
330+ if (a && a.nearClip > 0) warnings.push(`${a.nearClip} samples in the tear are at or near full scale (clipping). The energy is underestimated; consider re-recording further from the microphone.`);
331+ if (a && !a.noiseEsd) warnings.push("There is not enough quiet before or after the tear to measure the background, so nothing was subtracted. Leave about a second of quiet at each end.");
332+ else if (a && a.snrDb < 10) warnings.push(`The tear is only ${a.snrDb.toFixed(1)} dB above the background, so the energy depends on how well the background is estimated.`);
333+ if (seg && (seg.start < 0.05 || seg.end > dur - 0.05)) warnings.push("The tear touches the start or end of the recording and may be cut off.");
334+
335+ const th = readTheme(document.documentElement);
336+
337+ return (
338+ <>
339+ {warnings.map((w) => (
340+ <div key={w} className="warn">
341+ ⚠ {w}
342+ </div>
343+ ))}
344+
345+ <section className="card">
346+ <div className="plot-head">
347+ <div>
348+ <h3>Tear range</h3>
349+ <p className="caption">Drag across the plot to mark where the tear is. Drag a dark edge to adjust it. Everything below uses only this range.</p>
350+ </div>
351+ <div className="toolbar">
352+ <button className="primary" disabled={!x || !seg} onClick={() => x && seg && play(meta.id, x, fs, seg.start, seg.end)}>
353+ ▶ Play tear
354+ </button>
355+ <button disabled={!x} onClick={() => x && play(meta.id, x, fs, 0, dur)}>
356+ ▶ Play whole recording
357+ </button>
358+ <button disabled={playhead === null} onClick={stopPlay}>
359+ ■ Stop
360+ </button>
361+ </div>
362+ </div>
363+ <CanvasPlot
364+ height={150}
365+ xRange={[0, dur]}
366+ yRange={levelRange}
367+ xLabel="time (s)"
368+ yLabel="level (dBFS)"
369+ draw={drawRange}
370+ hover={(p) => {
371+ const lines = [`${p.xv.toFixed(2)} s`];
372+ if (levels) {
373+ const i = Math.floor(p.xv / levels.frameSec);
374+ if (i >= 0 && i < levels.power.length) lines.push(`${db10(levels.power[i]).toFixed(1)} dBFS`);
375+ }
376+ return { lines };
377+ }}
378+ ariaLabel="Sound level over the whole recording, with the tear range"
379+ {...rangeHandlers}
380+ />
381+ <RangeInputs seg={seg} dur={dur} onCommit={commitSeg} />
382+ <div className="range-row">
383+ <span className="muted small">{meta.segmentManual ? "Range set by hand." : "Range found automatically."}</span>
384+ <button
385+ disabled={!x}
386+ onClick={() => {
387+ if (!x) return;
388+ const s = detectSegment(x, fs);
389+ setSeg(s);
390+ onUpdate({ ...meta, segment: s, segmentManual: false });
391+ }}
392+ >
393+ Find tear automatically
394+ </button>
395+ </div>
396+ </section>
397+
398+ <section className="card">
399+ <h3>Results</h3>
400+ <Stats a={a} settings={settings} />
401+ </section>
402+
403+ <section className="card">
404+ <div className="plot-head">
405+ <div>
406+ <h3>Close-up</h3>
407+ <p className="caption">Drag to move along. Pinch (or ctrl + scroll) to zoom. Dashed lines mark the tear range.</p>
408+ </div>
409+ <div className="toolbar">
410+ <button onClick={() => zoom(0.5)} aria-label="Zoom in">
411+ + Zoom in
412+ </button>
413+ <button onClick={() => zoom(2)} aria-label="Zoom out">
414+ − Zoom out
415+ </button>
416+ <button onClick={() => setView(fit(seg))}>Fit tear</button>
417+ <button onClick={() => setView([0, dur])}>Whole recording</button>
418+ </div>
419+ </div>
420+ <CanvasPlot
421+ height={160}
422+ xRange={view}
423+ yRange={[-waveMax, waveMax]}
424+ xLabel="time (s)"
425+ yLabel="waveform"
426+ hideXTicks
427+ draw={drawWave}
428+ hover={(p) => ({ lines: [`${p.xv.toFixed(4)} s`] })}
429+ ariaLabel="Waveform close-up"
430+ {...closeHandlers}
431+ />
432+ <CanvasPlot
433+ height={230}
434+ xRange={view}
435+ yRange={[0, fs / 2]}
436+ xLabel="time (s)"
437+ yLabel="frequency (Hz)"
438+ draw={drawSpec}
439+ hover={(p) => ({ lines: [`${p.xv.toFixed(3)} s`, fmtHz(p.yv)] })}
440+ ariaLabel="Spectrogram close-up"
441+ {...closeHandlers}
442+ />
443+ <p className="caption">
444+ Showing {fmtSec(view[0])}–{fmtSec(view[1])}. Spectrogram: 1024-point windows; brighter is louder, spanning the top 90 dB of this recording.
445+ </p>
446+ </section>
447+
448+ <section className="card">
449+ <div className="plot-head">
450+ <div>
451+ <h3>Frequency makeup of the tear</h3>
452+ <p className="caption">How the tear's sound energy is spread over frequency, compared with the background noise alone.</p>
453+ </div>
454+ <label className="toolbar">
455+ smoothing
456+ <select value={smoothing} onChange={(e) => setSmoothing(+e.target.value)}>
457+ {SMOOTHING.map(([n, v]) => (
458+ <option key={n} value={v}>
459+ {n}
460+ </option>
461+ ))}
462+ </select>
463+ </label>
464+ </div>
465+ <CanvasPlot
466+ height={300}
467+ xRange={[fLo, fHi]}
468+ xLog
469+ yRange={specRange}
470+ xLabel="frequency (Hz)"
471+ yLabel="energy density (dB re FS²·s/Hz)"
472+ draw={drawSpectrum}
473+ hover={specHover}
474+ ariaLabel="Energy spectral density of the tear"
475+ />
476+ <div className="legend">
477+ <span>
478+ <i className="swatch" style={{ background: colorFor(slot, th.series, th.ink2) }} /> tear
479+ </span>
480+ <span>
481+ <i className="swatch dashed" /> background alone, over the same duration
482+ </span>
483+ <span>
484+ <i className="swatch shade" /> outside the analysis band ({fmtHz(settings.bandLow)}–{fmtHz(settings.bandHigh)})
485+ </span>
486+ </div>
487+ </section>
488+ </>
489+ );
490+}
491+
492+function RangeInputs({ seg, dur, onCommit }: { seg: Segment | null; dur: number; onCommit: (s: Segment) => void }) {
493+ const [a, setA] = useState("");
494+ const [b, setB] = useState("");
495+ useEffect(() => {
496+ setA(seg ? seg.start.toFixed(3) : "");
497+ setB(seg ? seg.end.toFixed(3) : "");
498+ }, [seg]);
499+ const commit = () => {
500+ const s = Math.min(Math.max(+a, 0), dur);
501+ const e = Math.min(Math.max(+b, 0), dur);
502+ if (Number.isFinite(s) && Number.isFinite(e) && e - s >= 0.01 && (!seg || s !== seg.start || e !== seg.end)) onCommit({ start: s, end: e });
503+ else {
504+ setA(seg ? seg.start.toFixed(3) : "");
505+ setB(seg ? seg.end.toFixed(3) : "");
506+ }
507+ };
508+ const key = (e: React.KeyboardEvent<HTMLInputElement>) => e.key === "Enter" && (e.target as HTMLInputElement).blur();
509+ return (
510+ <div className="range-inputs">
511+ <label>
512+ Start
513+ <input type="number" step="0.01" value={a} onChange={(e) => setA(e.target.value)} onBlur={commit} onKeyDown={key} /> s
514+ </label>
515+ <label>
516+ End
517+ <input type="number" step="0.01" value={b} onChange={(e) => setB(e.target.value)} onBlur={commit} onKeyDown={key} /> s
518+ </label>
519+ <span>
520+ Duration <b>{seg ? fmtSec(seg.end - seg.start) : "–"}</b>
521+ </span>
522+ </div>
523+ );
524+}
525+
526+function Stats({ a, settings }: { a: Analysis | null; settings: AnalysisSettings }) {
527+ if (!a) return <p className="muted">No tear range.</p>;
528+ const items: [string, string, string?][] = [
529+ ["Tear duration", fmtSec(a.duration)],
530+ ["Speed", `${a.speedInPerSec.toFixed(2)} in/s`, `${settings.sheetLengthIn} in ÷ duration`],
531+ ["Sound energy", `${db10(a.energy).toFixed(1)} dB`, "background removed (relative units)"],
532+ ["Median frequency", fmtHz(a.medianFreq), "half the energy above, half below"],
533+ ["Centroid", fmtHz(a.centroid), "energy-weighted mean frequency"],
534+ ["Mean power", `${db10(a.energy / a.duration).toFixed(1)} dBFS`, "energy ÷ duration"],
535+ ["Peak", `${a.peakDbfs.toFixed(1)} dBFS`, a.nearClip ? `${a.nearClip} samples near clipping` : "no clipping"],
536+ [
537+ "Above background",
538+ Number.isFinite(a.snrDb) ? `${a.snrDb.toFixed(1)} dB` : "–",
539+ a.backgroundDbfs !== null ? `background ${a.backgroundDbfs.toFixed(1)} dBFS` : "no background estimate",
540+ ],
541+ ];
542+ return (
543+ <div className="stats">
544+ {items.map(([k, v, sub]) => (
545+ <div key={k} className="stat">
546+ <div className="stat-k">{k}</div>
547+ <div className="stat-v">{v}</div>
548+ {sub && <div className="stat-sub">{sub}</div>}
549+ </div>
550+ ))}
551+ </div>
552+ );
553+}
554+
555+function spectrogramImage(spec: ReturnType<typeof spectrogram>): HTMLCanvasElement {
556+ const c = document.createElement("canvas");
557+ c.width = spec.cols;
558+ c.height = spec.bins;
559+ const ctx = c.getContext("2d")!;
560+ const img = ctx.createImageData(spec.cols, spec.bins);
561+ const top = spec.maxDb;
562+ const range = 90;
563+ for (let col = 0; col < spec.cols; col++) {
564+ for (let k = 0; k < spec.bins; k++) {
565+ const v = (spec.db[col * spec.bins + k] - (top - range)) / range;
566+ const [r, g, b] = magma(Math.min(1, Math.max(0, v)));
567+ const o = ((spec.bins - 1 - k) * spec.cols + col) * 4;
568+ img.data[o] = r;
569+ img.data[o + 1] = g;
570+ img.data[o + 2] = b;
571+ img.data[o + 3] = 255;
572+ }
573+ }
574+ ctx.putImageData(img, 0, 0);
575+ return c;
576+}
src/model.tsmodified+22−24View file
@@ -3,32 +3,30 @@ import { loadAudio, type RecordingMeta } from "./storage/db.ts";
33 import type { MarkerShape } from "./components/CanvasPlot.tsx";
44 import { SHAPES } from "./components/CanvasPlot.tsx";
55
6-export const PRESET_LABELS = [
7- "very slow (~10 s)",
8- "slow (~5 s)",
9- "medium (~2 s)",
10- "fast (~1 s)",
11- "very fast (<0.5 s)",
6+// The fixed set of speeds. `id` is what is stored as a recording's label.
7+export interface Speed {
8+ id: string;
9+ name: string;
10+ target: string; // intended tear duration
11+}
12+
13+export const SPEEDS: Speed[] = [
14+ { id: "very slow (~10 s)", name: "Very slow", target: "~10 s" },
15+ { id: "slow (~5 s)", name: "Slow", target: "~5 s" },
16+ { id: "medium (~2 s)", name: "Medium", target: "~2 s" },
17+ { id: "fast (~1 s)", name: "Fast", target: "~1 s" },
18+ { id: "very fast (<0.5 s)", name: "Very fast", target: "<0.5 s" },
1219 ];
1320
14-// Groups in display order: presets first (slow to fast), then custom labels by first use.
15-export function groupOrder(recs: RecordingMeta[]): string[] {
16- const used = new Set(recs.map((r) => r.label));
17- const out = PRESET_LABELS.filter((l) => used.has(l));
18- for (const r of recs) if (!out.includes(r.label)) out.push(r.label);
19- return out;
20-}
21-
22-// Colour follows the label, not its position in a filtered list: presets own slots 1–5,
23-// custom labels take 6–8 in order of first use, anything beyond shares the muted colour.
24-export function groupStyle(label: string, recs: RecordingMeta[]): { slot: number | null; shape: MarkerShape } {
25- const p = PRESET_LABELS.indexOf(label);
26- if (p >= 0) return { slot: p, shape: SHAPES[p % SHAPES.length] };
27- const custom: string[] = [];
28- for (const r of recs) if (!PRESET_LABELS.includes(r.label) && !custom.includes(r.label)) custom.push(r.label);
29- const c = custom.indexOf(label);
30- const slot = c >= 0 && c < 3 ? 5 + c : null;
31- return { slot, shape: SHAPES[(5 + Math.max(c, 0)) % SHAPES.length] };
21+export const speedName = (id: string) => {
22+ const s = SPEEDS.find((v) => v.id === id);
23+ return s ? `${s.name} (${s.target})` : id;
24+};
25+
26+// Colour and marker follow the speed, never its position in a filtered list.
27+export function speedStyle(id: string): { slot: number | null; shape: MarkerShape } {
28+ const i = SPEEDS.findIndex((s) => s.id === id);
29+ return i >= 0 ? { slot: i, shape: SHAPES[i] } : { slot: null, shape: "circle" };
3230 }
3331
3432 export function colorFor(slot: number | null, series: string[], muted: string) {
src/styles.cssmodified+129−0View file
@@ -646,3 +646,132 @@ tr.clickable:hover {
646646 grid-template-columns: 1fr;
647647 }
648648 }
649+
650+/* speed list */
651+.speed-item {
652+ display: flex;
653+ align-items: center;
654+ gap: 10px;
655+ width: 100%;
656+ border: none;
657+ border-radius: 0;
658+ background: none;
659+ padding: 9px 14px;
660+ text-align: left;
661+}
662+.speed-item.sel {
663+ background: var(--hover);
664+ box-shadow: inset 3px 0 0 var(--accent);
665+}
666+.dot {
667+ width: 12px;
668+ height: 12px;
669+ border-radius: 50%;
670+ border: 2px solid var(--axis);
671+ flex-shrink: 0;
672+}
673+.dot.done {
674+ border-color: transparent;
675+}
676+.speed-text {
677+ display: flex;
678+ flex-direction: column;
679+}
680+.speed-name {
681+ font-weight: 600;
682+}
683+.speed-head {
684+ display: flex;
685+ justify-content: space-between;
686+ align-items: flex-end;
687+ gap: 12px;
688+ flex-wrap: wrap;
689+}
690+.speed-head h2 {
691+ margin: 0;
692+ font-size: 20px;
693+}
694+.speed-head h2 .muted {
695+ font-weight: 400;
696+ font-size: 16px;
697+}
698+button.link {
699+ border: none;
700+ background: none;
701+ padding: 0;
702+ color: var(--accent);
703+ text-decoration: underline;
704+}
705+.main.solo {
706+ max-width: 1200px;
707+ width: 100%;
708+ margin: 0 auto;
709+}
710+
711+/* record panel */
712+.record-panel {
713+ display: flex;
714+ flex-direction: column;
715+ gap: 12px;
716+}
717+.replace-note {
718+ font-size: 13px;
719+ color: var(--ink2);
720+ background: var(--hover);
721+ border-radius: 6px;
722+ padding: 6px 10px;
723+}
724+.steps {
725+ margin: 0;
726+ padding-left: 20px;
727+ color: var(--ink2);
728+}
729+.steps li {
730+ margin: 2px 0;
731+}
732+.rec-controls {
733+ display: flex;
734+ gap: 14px;
735+ align-items: center;
736+ flex-wrap: wrap;
737+}
738+.file-link {
739+ font-size: 12.5px;
740+ color: var(--muted);
741+ display: flex;
742+ gap: 8px;
743+ align-items: center;
744+ flex-wrap: wrap;
745+}
746+.file-link input {
747+ font-size: 12px;
748+}
749+
750+/* tear range */
751+.range-inputs {
752+ display: flex;
753+ gap: 18px;
754+ align-items: center;
755+ flex-wrap: wrap;
756+ margin-top: 10px;
757+ font-size: 13px;
758+}
759+.range-inputs label {
760+ display: flex;
761+ gap: 6px;
762+ align-items: center;
763+}
764+.range-inputs input {
765+ width: 90px;
766+}
767+.range-row {
768+ display: flex;
769+ gap: 12px;
770+ align-items: center;
771+ justify-content: space-between;
772+ margin-top: 8px;
773+ flex-wrap: wrap;
774+}
775+.plot-head .caption {
776+ margin: 2px 0 0;
777+}
↑↓ move↵openescclose