/ magland / rip-sound-analyzer
Sign in
magland / rip-sound-analyzer
Open-ended samples instead of fixed speeds
Samples are added, re-recorded, renamed and deleted freely, listed by measured tear duration. Compare colours each sample by its tear duration on a fixed sequential scale.
Jeremy Magland <jmagland@flatironinstitute.org> committed commit 09371b0d5846 parent cc4197e Browse files
9 changed files+250−206
README.mdmodified+2−2View file
@@ -24,12 +24,12 @@ Open the printed localhost URL in Chrome. Everything runs in the browser; record
2424
2525 ## What it does
2626
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:
27+- **Record**: a list of samples, each one tear at whatever speed you choose, sorted slowest first by measured tear duration. Add a new sample, re-record or delete one, and give it an optional name and notes. 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 sample:
2828 - **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.
2929 - **Results**: duration, speed, energy, mean power, peak/clipping, level above background.
3030 - **Close-up**: waveform and spectrogram, with zoom buttons, to look for individual clicks.
3131 - **Frequency makeup**: the tear's energy spectrum against the background.
32-- **Compare**: energy vs tear duration, loudness (mean power) vs duration, spectra of all speeds overlaid (optionally shape only), a table and CSV export.
32+- **Compare**: all samples, coloured by tear duration (stronger = faster): energy vs tear duration, loudness (mean power) vs duration, spectra of all speeds overlaid (optionally shape only), a table and CSV export.
3333
3434 Two frequency bands (set under Analysis settings): the **energy band**, default 15–20 kHz, is used for total energy, finding the tear, the level-over-time plot and the background comparison, because lower frequencies carry much more room and handling noise. The **spectrum band**, default 100 Hz–20 kHz, is the range over which spectra are shown and compared.
3535
src/App.tsxmodified+134−106View file
@@ -9,8 +9,8 @@ import type { CaptureInfo } from "./audio/recorder.ts";
99 import { encodeWavFloat32 } from "./audio/wav.ts";
1010 import { deleteRecording, listRecordings, newId, saveRecording, updateMeta, type RecordingMeta } from "./storage/db.ts";
1111 import {
12- colorFor,
1312 download,
13+ durationColor,
1414 fmtDate,
1515 fmtSec,
1616 forgetAudio,
@@ -18,19 +18,20 @@ import {
1818 loadSettings,
1919 putAudio,
2020 safeName,
21- SPEEDS,
22- speedStyle,
21+ sampleTitle,
22+ sortSamples,
2323 storeSettings,
24- type Speed,
24+ tearDuration,
2525 } from "./model.ts";
2626 import type { AnalysisSettings } from "./analysis/analyze.ts";
2727
2828 type Tab = "record" | "compare" | "about";
29+const NEW = "new"; // selection value for the "new sample" page
2930
3031 export function App() {
3132 const [recs, setRecs] = useState<RecordingMeta[]>([]);
3233 const [loaded, setLoaded] = useState(false);
33- const [selected, setSelected] = useState(SPEEDS[0].id);
34+ const [selected, setSelected] = useState<string>(NEW);
3435 const [rerecording, setRerecording] = useState<string | null>(null);
3536 const [tab, setTab] = useState<Tab>("record");
3637 const [settings, setSettingsState] = useState<AnalysisSettings>(loadSettings);
@@ -40,20 +41,12 @@ export function App() {
4041 listRecordings().then((r) => {
4142 setRecs(r);
4243 setLoaded(true);
43- const firstMissing = SPEEDS.find((s) => !r.some((m) => m.label === s.id));
44- if (firstMissing) setSelected(firstMissing.id);
44+ if (r.length) setSelected(sortSamples(r)[0].id);
4545 });
4646 navigator.storage?.persist?.().catch(() => {});
4747 }, []);
4848
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);
49+ const samples = useMemo(() => sortSamples(recs), [recs]);
5750
5851 const setSettings = (s: AnalysisSettings) => {
5952 setSettingsState(s);
@@ -68,7 +61,7 @@ export function App() {
6861 let live = true;
6962 (async () => {
7063 for (const m of recs) {
71- if (m.segmentManual || m.detectBand?.lo === energyLow && m.detectBand?.hi === energyHigh) continue;
64+ if (m.segmentManual || (m.detectBand?.lo === energyLow && m.detectBand?.hi === energyHigh)) continue;
7265 const x = await getAudio(m.id);
7366 if (!live) return;
7467 const band = { lo: energyLow, hi: energyHigh };
@@ -82,31 +75,33 @@ export function App() {
8275 };
8376 }, [loaded, recs, energyLow, energyHigh]);
8477
85- const onDone = async (speed: Speed, x: Float32Array, fs: number, info: CaptureInfo | null, fileName?: string) => {
78+ // A new take: either a new sample, or a replacement for `replaces` (keeping its name and notes).
79+ const onDone = async (replaces: RecordingMeta | null, x: Float32Array, fs: number, info: CaptureInfo | null, fileName?: string) => {
80+ const band = energyBand(settings);
8681 const meta: RecordingMeta = {
8782 id: newId(),
8883 createdAt: Date.now(),
89- label: speed.id,
90- notes: "",
84+ label: replaces?.label ?? "",
85+ notes: replaces?.notes ?? "",
9186 material: "paper",
9287 source: fileName ? "file" : "mic",
9388 fileName,
9489 sampleRate: fs,
9590 length: x.length,
96- segment: detectSegment(x, fs, energyBand(settings)),
91+ segment: detectSegment(x, fs, band),
9792 segmentManual: false,
98- detectBand: energyBand(settings),
93+ detectBand: band,
9994 capture: info ?? undefined,
10095 };
10196 await saveRecording(meta, x);
10297 putAudio(meta.id, x);
103- const old = bySpeed.get(speed.id);
104- if (old) {
105- await deleteRecording(old.id);
106- forgetAudio(old.id);
98+ if (replaces) {
99+ await deleteRecording(replaces.id);
100+ forgetAudio(replaces.id);
107101 }
108- setRecs((r) => [...r.filter((m) => m.id !== old?.id), meta]);
102+ setRecs((r) => [...r.filter((m) => m.id !== replaces?.id), meta]);
109103 setRerecording(null);
104+ setSelected(meta.id);
110105 };
111106
112107 const onUpdate = async (meta: RecordingMeta) => {
@@ -114,20 +109,18 @@ export function App() {
114109 setRecs((r) => r.map((m) => (m.id === meta.id ? meta : m)));
115110 };
116111
117- const remove = async (metas: RecordingMeta[]) => {
118- for (const m of metas) {
119- await deleteRecording(m.id);
120- forgetAudio(m.id);
121- }
122- const ids = new Set(metas.map((m) => m.id));
123- setRecs((r) => r.filter((m) => !ids.has(m.id)));
112+ const remove = async (m: RecordingMeta) => {
113+ if (!confirm(`Delete this sample (${sampleTitle(m)})? This cannot be undone.`)) return;
114+ await deleteRecording(m.id);
115+ forgetAudio(m.id);
116+ const rest = samples.filter((q) => q.id !== m.id);
117+ setRecs((r) => r.filter((q) => q.id !== m.id));
118+ setSelected(rest.length ? rest[Math.min(samples.indexOf(m), rest.length - 1)].id : NEW);
124119 };
125120
126- const speed = SPEEDS.find((s) => s.id === selected)!;
127- const current = bySpeed.get(selected) ?? null;
121+ const current = recs.find((r) => r.id === selected) ?? null;
128122 const th = readTheme(document.documentElement);
129- const idx = SPEEDS.indexOf(speed);
130- const next = SPEEDS[idx + 1];
123+ const dur = current ? tearDuration(current) : null;
131124
132125 return (
133126 <div className="app">
@@ -137,7 +130,7 @@ export function App() {
137130 {(
138131 [
139132 ["record", "Record"],
140- ["compare", "Compare"],
133+ ["compare", `Compare (${samples.length})`],
141134 ["about", "What this can tell you"],
142135 ] as [Tab, string][]
143136 ).map(([t, name]) => (
@@ -155,94 +148,102 @@ export function App() {
155148
156149 {tab === "record" && (
157150 <div className="layout">
158- <aside className="sidebar" aria-label="Speeds">
151+ <aside className="sidebar" aria-label="Samples">
159152 <div className="side-head">
160- Speeds <span className="muted">{recorded.length} of {SPEEDS.length} recorded</span>
153+ Samples <span className="muted">slowest first</span>
161154 </div>
162- {SPEEDS.map((s) => {
163- const r = bySpeed.get(s.id);
164- const st = speedStyle(s.id);
155+ <button
156+ className={`speed-item new-item ${selected === NEW ? "sel" : ""}`}
157+ onClick={() => {
158+ setSelected(NEW);
159+ setRerecording(null);
160+ }}
161+ >
162+ <span className="plus">+</span>
163+ <span className="speed-name">New sample</span>
164+ </button>
165+ {samples.map((m) => {
166+ const d = tearDuration(m);
165167 return (
166168 <button
167- key={s.id}
168- className={`speed-item ${s.id === selected ? "sel" : ""}`}
169+ key={m.id}
170+ className={`speed-item ${m.id === selected ? "sel" : ""}`}
169171 onClick={() => {
170- setSelected(s.id);
172+ setSelected(m.id);
171173 setRerecording(null);
172174 }}
173175 >
174- <span className={`dot ${r ? "done" : ""}`} style={r ? { background: colorFor(st.slot, th.series, th.muted) } : undefined} />
176+ <span className="dot done" style={{ background: durationColor(d, th) }} />
175177 <span className="speed-text">
176- <span className="speed-name">{s.name}</span>
177- <span className="muted small">
178- {s.target} · {r ? (r.segment ? `tear ${fmtSec(r.segment.end - r.segment.start)}` : "no tear marked") : "not recorded"}
178+ <span className="speed-name">
179+ {sampleTitle(m)}
180+ {d !== null && <span className="muted"> · {(settings.sheetLengthIn / d).toFixed(1)} in/s</span>}
179181 </span>
182+ <span className="muted small">{m.label || fmtDate(m.createdAt)}</span>
180183 </span>
181184 </button>
182185 );
183186 })}
187+ {loaded && !samples.length && <p className="muted pad small">No samples yet.</p>}
184188 <p className="muted pad small">Recordings are stored only in this browser.</p>
185- {others.length > 0 && (
186- <p className="pad small">
187- <span className="muted">{others.length} older recording{others.length > 1 ? "s" : ""} from a previous version are not used. </span>
188- <button
189- className="link"
190- onClick={() => confirm(`Delete ${others.length} unused recording(s)? This cannot be undone.`) && remove(others)}
191- >
192- Delete them
193- </button>
194- </p>
195- )}
196189 </aside>
197190
198191 <main className="main">
199- <div className="speed-head">
200- <div>
201- <h2>
202- {speed.name} <span className="muted">· target {speed.target}</span>
203- </h2>
204- <div className="muted small">
205- {current
206- ? `Recorded ${fmtDate(current.createdAt)} · ${fmtSec(current.length / current.sampleRate)} long${current.fileName ? ` · from ${current.fileName}` : ""}`
207- : "Not recorded yet"}
192+ {selected === NEW || !current ? (
193+ <>
194+ <div className="speed-head">
195+ <div>
196+ <h2>New sample</h2>
197+ <div className="muted small">Record a tear at any speed. It is added to the list when you stop.</div>
198+ </div>
208199 </div>
209- </div>
210- {current && rerecording !== speed.id && (
211- <div className="toolbar">
212- <button onClick={() => setRerecording(speed.id)}>Re-record</button>
213- <button
214- onClick={async () => {
215- const x = await getAudio(current.id);
216- download(encodeWavFloat32(x, current.sampleRate), `tear_${safeName(speed.name)}_${new Date(current.createdAt).toISOString().slice(0, 19).replace(/:/g, "-")}.wav`);
217- }}
218- >
219- Download WAV
220- </button>
221- <button
222- className="danger"
223- onClick={() => confirm(`Delete the ${speed.name.toLowerCase()} recording? This cannot be undone.`) && remove([current])}
224- >
225- Delete
226- </button>
227- {next && (
228- <button onClick={() => setSelected(next.id)} title={`Go to ${next.name}`}>
229- Next speed →
230- </button>
200+ {loaded && <RecordPanel key="new" replacing={false} onDone={(x, fs, info, fileName) => onDone(null, x, fs, info, fileName)} onCancel={null} />}
201+ </>
202+ ) : (
203+ <>
204+ <div className="speed-head">
205+ <div>
206+ <h2>
207+ {sampleTitle(current)}
208+ {dur !== null && <span className="muted"> · {(settings.sheetLengthIn / dur).toFixed(2)} in/s</span>}
209+ </h2>
210+ <div className="muted small">
211+ Recorded {fmtDate(current.createdAt)} · {fmtSec(current.length / current.sampleRate)} long
212+ {current.fileName ? ` · from ${current.fileName}` : ""}
213+ </div>
214+ </div>
215+ {rerecording !== current.id && (
216+ <div className="toolbar">
217+ <button onClick={() => setRerecording(current.id)}>Re-record</button>
218+ <button
219+ onClick={async () => {
220+ const x = await getAudio(current.id);
221+ const stamp = new Date(current.createdAt).toISOString().slice(0, 19).replace(/:/g, "-");
222+ download(encodeWavFloat32(x, current.sampleRate), `tear_${stamp}${current.label ? "_" + safeName(current.label) : ""}.wav`);
223+ }}
224+ >
225+ Download WAV
226+ </button>
227+ <button className="danger" onClick={() => remove(current)}>
228+ Delete
229+ </button>
230+ </div>
231231 )}
232232 </div>
233- )}
234- </div>
233+ <NameField key={current.id} meta={current} onUpdate={onUpdate} />
235234
236- {loaded && (!current || rerecording === speed.id) && (
237- <RecordPanel
238- key={speed.id}
239- speed={speed}
240- replacing={!!current}
241- onDone={(x, fs, info, fileName) => onDone(speed, x, fs, info, fileName)}
242- onCancel={current ? () => setRerecording(null) : null}
243- />
235+ {rerecording === current.id ? (
236+ <RecordPanel
237+ key={`re-${current.id}`}
238+ replacing
239+ onDone={(x, fs, info, fileName) => onDone(current, x, fs, info, fileName)}
240+ onCancel={() => setRerecording(null)}
241+ />
242+ ) : (
243+ <TearView key={current.id} meta={current} settings={settings} onUpdate={onUpdate} />
244+ )}
245+ </>
244246 )}
245- {current && rerecording !== speed.id && <TearView key={current.id} meta={current} settings={settings} onUpdate={onUpdate} />}
246247 </main>
247248 </div>
248249 )}
@@ -250,11 +251,11 @@ export function App() {
250251 {tab === "compare" && (
251252 <main className="main solo">
252253 <CompareView
253- recs={recorded}
254+ recs={samples}
254255 settings={settings}
255256 onOpen={(id) => {
256- const r = recs.find((m) => m.id === id);
257- if (r) setSelected(r.label);
257+ setSelected(id);
258+ setRerecording(null);
258259 setTab("record");
259260 }}
260261 />
@@ -269,6 +270,33 @@ export function App() {
269270 );
270271 }
271272
273+// Optional free-text name and notes for a sample.
274+function NameField({ meta, onUpdate }: { meta: RecordingMeta; onUpdate: (m: RecordingMeta) => void }) {
275+ const [label, setLabel] = useState(meta.label);
276+ const [notes, setNotes] = useState(meta.notes);
277+ return (
278+ <div className="name-row">
279+ <input
280+ value={label}
281+ placeholder="Name (optional)"
282+ onChange={(e) => setLabel(e.target.value)}
283+ onBlur={() => label !== meta.label && onUpdate({ ...meta, label: label.trim() })}
284+ onKeyDown={(e) => e.key === "Enter" && (e.target as HTMLInputElement).blur()}
285+ aria-label="Sample name"
286+ />
287+ <input
288+ className="notes-input"
289+ value={notes}
290+ placeholder="Notes (paper, how it was torn, anything unusual)"
291+ onChange={(e) => setNotes(e.target.value)}
292+ onBlur={() => notes !== meta.notes && onUpdate({ ...meta, notes })}
293+ onKeyDown={(e) => e.key === "Enter" && (e.target as HTMLInputElement).blur()}
294+ aria-label="Notes"
295+ />
296+ </div>
297+ );
298+}
299+
272300 function SettingsPanel({ settings, setSettings }: { settings: AnalysisSettings; setSettings: (s: AnalysisSettings) => void }) {
273301 const [d, setD] = useState(settings);
274302 const changed = JSON.stringify(d) !== JSON.stringify(settings);
src/components/About.tsxmodified+3−3View file
@@ -18,7 +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 in the energy band (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.
21+ <b>Tear segment</b>: found automatically as the loudest stretch well above the background in the energy band (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.
2222 </li>
2323 <li>
2424 <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
@@ -51,8 +51,8 @@ export function About({ settings }: { settings: AnalysisSettings }) {
5151 <b>Clipping ruins the energy.</b> If a tear is loud enough to hit full scale, its energy is underestimated. Clipped recordings are flagged.
5252 </li>
5353 <li>
54- <b>Run-to-run scatter.</b> Two tears at the same speed won't give identical numbers (paper varies, your hands vary). Make several tears per speed and
55- look at the spread before reading anything into a difference between speeds.
54+ <b>Run-to-run scatter.</b> Two tears at the same speed won't give identical numbers (paper varies, your hands vary). Record several tears at similar
55+ speeds and look at the spread before reading anything into a difference between speeds.
5656 </li>
5757 <li>
5858 <b>Not just the tear.</b> Hand and paper movement, the sheet flapping and the room all add sound. Most of this is at low frequencies, which is why energy is measured
src/components/CanvasPlot.tsxmodified+2−0View file
@@ -22,6 +22,7 @@ export interface Theme {
2222 axis: string;
2323 seg: string;
2424 series: string[];
25+ ramp: string[]; // sequential, weakest to strongest against the surface
2526 }
2627
2728 export function readTheme(el: Element): Theme {
@@ -36,6 +37,7 @@ export function readTheme(el: Element): Theme {
3637 axis: v("--axis"),
3738 seg: v("--seg"),
3839 series: [1, 2, 3, 4, 5, 6, 7, 8].map((i) => v(`--series-${i}`)),
40+ ramp: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map((i) => v(`--ramp-${i}`)),
3941 };
4042 }
4143
src/components/CompareView.tsxmodified+37−56View file
@@ -1,11 +1,11 @@
11 import { useCallback, useEffect, useMemo, useState } from "react";
2-import { CanvasPlot, drawLine, drawMarker, readTheme, type MarkerShape, type PointerInfo, type Scales, type Theme } from "./CanvasPlot.tsx";
2+import { CanvasPlot, drawLine, drawMarker, readTheme, 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, linearFit, SPEEDS, speedName, speedStyle } from "../model.ts";
5+import { db10, download, durationColor, fmtDate, fmtHz, fmtSec, getAnalysis, linearFit, sampleTitle } from "../model.ts";
66
77 interface Props {
8- recs: RecordingMeta[]; // at most one per speed, in speed order
8+ recs: RecordingMeta[]; // all samples, slowest first
99 settings: AnalysisSettings;
1010 onOpen: (id: string) => void;
1111 }
@@ -19,6 +19,7 @@ const powerOf = (a: Analysis) => db10(a.energy / a.duration);
1919 const fmtDbfs = (v: number) => `${v.toFixed(1)} dBFS`;
2020
2121 const energyOf = (a: Analysis) => db10(a.energy);
22+const rowName = (r: Row) => `${fmtSec(r.a.duration)} tear${r.meta.label ? ` · ${r.meta.label}` : ""}`;
2223 const fmtDb = (v: number) => `${v.toFixed(1)} dB`;
2324
2425 export function CompareView({ recs, settings, onOpen }: Props) {
@@ -39,7 +40,7 @@ export function CompareView({ recs, settings, onOpen }: Props) {
3940 await new Promise((r) => setTimeout(r, 0));
4041 }
4142 if (live) {
42- setRows(out);
43+ setRows(out.sort((p, q) => q.a.duration - p.a.duration));
4344 setReady(true);
4445 }
4546 })();
@@ -49,18 +50,16 @@ export function CompareView({ recs, settings, onOpen }: Props) {
4950 }, [recs, settings]);
5051
5152 const bandLabel = `${+(settings.energyLow / 1000).toFixed(2)}–${+(settings.energyHigh / 1000).toFixed(2)} kHz`;
52- const missing = SPEEDS.filter((s) => !recs.some((r) => r.label === s.id));
5353 const unusable = recs.filter((m) => !rows.some((r) => r.meta.id === m.id));
5454
55- if (!recs.length) return <div className="card empty">Nothing to compare yet. Record a tear at two or more speeds on the Record tab.</div>;
55+ if (!recs.length) return <div className="card empty">Nothing to compare yet. Record tears at a few different speeds on the Record tab.</div>;
5656 if (!ready) return <div className="card muted">Analysing…</div>;
5757
5858 return (
5959 <div className="compare">
60- {(missing.length > 0 || unusable.length > 0) && (
60+ {unusable.length > 0 && (
6161 <div className="card muted small">
62- {missing.length > 0 && <div>Not recorded yet: {missing.map((s) => s.name.toLowerCase()).join(", ")}.</div>}
63- {unusable.length > 0 && <div>Left out (no tear range or no sound above the background): {unusable.map((m) => speedName(m.label)).join(", ")}.</div>}
62+ Left out (no tear range or no sound above the background): {unusable.map((m) => m.label || `${sampleTitle(m)}, ${fmtDate(m.createdAt)}`).join("; ")}.
6463 </div>
6564 )}
6665
@@ -123,7 +122,7 @@ export function CompareView({ recs, settings, onOpen }: Props) {
123122 // ---------- summary ----------
124123
125124 function Summary({ rows, bandLabel }: { rows: Row[]; bandLabel: string }) {
126- if (rows.length < 2) return <div className="card muted">Record at least two speeds to compare them.</div>;
125+ if (rows.length < 2) return <div className="card muted">Record at least two samples at different speeds to compare them.</div>;
127126 const lx = rows.map((r) => Math.log10(r.a.duration));
128127 const e = rows.map((r) => db10(r.a.energy));
129128 const fe = linearFit(lx, e);
@@ -135,7 +134,7 @@ function Summary({ rows, bandLabel }: { rows: Row[]; bandLabel: string }) {
135134 <div className="q">
136135 <div className="q-title">Same total energy at every speed?</div>
137136 <div>
138- Across {rows.length} speeds the energy in {bandLabel} varies over a range of <b>{eRange.toFixed(1)} dB</b>.
137+ Across {rows.length} samples the energy in {bandLabel} varies over a range of <b>{eRange.toFixed(1)} dB</b>.
139138 {fe && (
140139 <>
141140 {" "}
@@ -152,10 +151,9 @@ function Summary({ rows, bandLabel }: { rows: Row[]; bandLabel: string }) {
152151 </div>
153152 </div>
154153 <p className="caption">
155- Tear durations span {span.toFixed(1)}×{span < 3 ? ", a narrow range, so trends will be hard to see" : ""}. Trends use measured durations, not the speed names.
156- With one tear per speed there is no way to tell how much two tears at the same speed would differ, so differences of a dB or two may just be
157- ordinary variation from tear to tear.
158- {fe ? "" : " A trend line needs at least three speeds."}
154+ Tear durations span {span.toFixed(1)}×{span < 3 ? ", a narrow range, so trends will be hard to see" : ""}. A few tears at similar speeds show how much tears vary on their own; differences smaller than that variation don't
155+ mean anything.
156+ {fe ? "" : " A trend line needs at least three samples."}
159157 </p>
160158 </section>
161159 );
@@ -213,10 +211,7 @@ function Scatter({
213211 drawLine(ctx, s, [xr[0], xr[1]], [yAt(xr[0]), yAt(xr[1])], th.ink2, 1.5, [2, 4]);
214212 }
215213 if (fit) drawLine(ctx, s, [xr[0], xr[1]], [fit.a + fit.b * Math.log10(xr[0]), fit.a + fit.b * Math.log10(xr[1])], th.muted, 1.5, [6, 4]);
216- for (const p of pts) {
217- const st = speedStyle(p.r.meta.label);
218- drawMarker(ctx, s.x(p.x), s.y(p.y), st.shape, colorFor(st.slot, th.series, th.muted), th.surface, 6);
219- }
214+ for (const p of pts) drawMarker(ctx, s.x(p.x), s.y(p.y), "circle", durationColor(p.x, th), th.surface, 6);
220215 },
221216 [pts, fit, xr, expectSlope],
222217 );
@@ -247,7 +242,7 @@ function Scatter({
247242 hover={(p) => {
248243 const q = near(p);
249244 if (!q) return null;
250- return { lines: [speedName(q.r.meta.label), `${fmtSec(q.x)} · ${yFmt(q.y)}`, "click to open"], x: q.x, y: q.y };
245+ return { lines: [rowName(q.r), `${yFmt(q.y)} · ${q.r.a.speedInPerSec.toFixed(2)} in/s`, "click to open"], x: q.x, y: q.y };
251246 }}
252247 onClick={(p) => {
253248 const q = near(p);
@@ -281,7 +276,7 @@ function SpectraOverlay({ rows, normalize, smoothing, settings }: { rows: Row[];
281276 rows.map((r) => {
282277 const scale = normalize ? 1 / r.a.shapeEnergy : 1;
283278 const sm = smoothLog(r.a.freqs, r.a.netEsd.map((v) => v * scale), fLo, fHi, smoothing);
284- return { label: r.meta.label, f: sm.f, db: sm.v.map((v) => (v > 0 ? 10 * Math.log10(v) : NaN)) };
279+ return { name: rowName(r), dur: r.a.duration, f: sm.f, db: sm.v.map((v) => (v > 0 ? 10 * Math.log10(v) : NaN)) };
285280 }),
286281 [rows, normalize, smoothing, fLo, fHi],
287282 );
@@ -302,10 +297,8 @@ function SpectraOverlay({ rows, normalize, smoothing, settings }: { rows: Row[];
302297 const bh = s.x(Math.min(settings.energyHigh, fHi));
303298 if (bh > bl) ctx.fillRect(bl, s.top, bh - bl, s.bottom - s.top);
304299 }
305- for (const l of lines) {
306- const st = speedStyle(l.label);
307- drawLine(ctx, s, l.f, l.db, colorFor(st.slot, th.series, th.muted), 2);
308- }
300+ // slowest first, so the fastest (strongest colour) are drawn on top
301+ for (const l of lines) drawLine(ctx, s, l.f, l.db, durationColor(l.dur, th), 2);
309302 },
310303 [lines, normalize, settings, fLo, fHi],
311304 );
@@ -325,7 +318,7 @@ function SpectraOverlay({ rows, normalize, smoothing, settings }: { rows: Row[];
325318 const f = lines[0].f;
326319 let i = 0;
327320 for (let k = 1; k < f.length; k++) if (Math.abs(Math.log(f[k] / p.xv)) < Math.abs(Math.log(f[i] / p.xv))) i = k;
328- return { lines: [fmtHz(f[i]), ...lines.map((l) => `${speedName(l.label)}: ${Number.isFinite(l.db[i]) ? l.db[i].toFixed(1) : "–"} dB`)], x: f[i] };
321+ return { lines: [fmtHz(f[i]), ...lines.map((l) => `${l.name}: ${Number.isFinite(l.db[i]) ? l.db[i].toFixed(1) : "–"} dB`)], x: f[i] };
329322 }}
330323 ariaLabel="Energy spectra of the tears, overlaid"
331324 />
@@ -336,23 +329,14 @@ function SpectraOverlay({ rows, normalize, smoothing, settings }: { rows: Row[];
336329
337330 // ---------- legend & table ----------
338331
339-function MarkerIcon({ shape, color, line }: { shape: MarkerShape; color: string; line?: boolean }) {
340- if (line)
341- return (
342- <svg width="18" height="10" aria-hidden>
343- <line x1="1" y1="5" x2="17" y2="5" stroke={color} strokeWidth="2.5" strokeLinecap="round" />
344- </svg>
345- );
346- const d: Record<MarkerShape, string> = {
347- circle: "M9,4 a5,5 0 1,0 0.01,0",
348- square: "M4.5,4.5 h9 v9 h-9 z",
349- triangle: "M9,3.5 L14.2,13 L3.8,13 z",
350- diamond: "M9,2.8 L14.2,9 L9,15.2 L3.8,9 z",
351- cross: "M7,4 h4 v3 h3 v4 h-3 v3 h-4 v-3 h-3 v-4 h3 z",
352- };
353- return (
354- <svg width="18" height="18" aria-hidden>
355- <path d={d[shape]} fill={color} />
332+function Swatch({ color, line }: { color: string; line?: boolean }) {
333+ return line ? (
334+ <svg width="18" height="10" aria-hidden>
335+ <line x1="1" y1="5" x2="17" y2="5" stroke={color} strokeWidth="2.5" strokeLinecap="round" />
336+ </svg>
337+ ) : (
338+ <svg width="14" height="14" aria-hidden>
339+ <circle cx="7" cy="7" r="5" fill={color} />
356340 </svg>
357341 );
358342 }
@@ -361,14 +345,12 @@ function Legend({ rows, lines, extra }: { rows: Row[]; lines?: boolean; extra?:
361345 const th = readTheme(document.documentElement);
362346 return (
363347 <div className="legend">
364- {rows.map((r) => {
365- const st = speedStyle(r.meta.label);
366- return (
367- <span key={r.meta.id}>
368- <MarkerIcon shape={st.shape} color={colorFor(st.slot, th.series, th.muted)} line={lines} /> {speedName(r.meta.label)}
369- </span>
370- );
371- })}
348+ <span className="muted">Colour = tear duration (stronger = faster):</span>
349+ {rows.map((r) => (
350+ <span key={r.meta.id}>
351+ <Swatch color={durationColor(r.a.duration, th)} line={lines} /> {rowName(r)}
352+ </span>
353+ ))}
372354 {extra && <span className="muted">{extra}</span>}
373355 </div>
374356 );
@@ -381,7 +363,7 @@ function Table({ rows, onOpen }: { rows: Row[]; onOpen: (id: string) => void })
381363 <table>
382364 <thead>
383365 <tr>
384- <th>Speed</th>
366+ <th>Sample</th>
385367 <th className="num">Tear duration</th>
386368 <th className="num">Speed (in/s)</th>
387369 <th className="num">Energy (dB)</th>
@@ -392,11 +374,10 @@ function Table({ rows, onOpen }: { rows: Row[]; onOpen: (id: string) => void })
392374 </thead>
393375 <tbody>
394376 {rows.map(({ meta, a }) => {
395- const st = speedStyle(meta.label);
396377 return (
397378 <tr key={meta.id} className="clickable" onClick={() => onOpen(meta.id)} title="Open on the Record tab">
398379 <td>
399- <MarkerIcon shape={st.shape} color={colorFor(st.slot, th.series, th.muted)} /> {speedName(meta.label)}
380+ <Swatch color={durationColor(a.duration, th)} /> {meta.label || fmtDate(meta.createdAt)}
400381 </td>
401382 <td className="num">{fmtSec(a.duration)}</td>
402383 <td className="num">{a.speedInPerSec.toFixed(2)}</td>
@@ -418,7 +399,7 @@ function Table({ rows, onOpen }: { rows: Row[]; onOpen: (id: string) => void })
418399
419400 function exportCsv(rows: Row[], settings: AnalysisSettings) {
420401 const head = [
421- "speed", "recorded", "source", "sample_rate", "tear_start_s", "tear_end_s", "range_set_by_hand", "duration_s", "speed_in_per_s",
402+ "name", "notes", "recorded", "source", "sample_rate", "tear_start_s", "tear_end_s", "range_set_by_hand", "duration_s", "speed_in_per_s",
422403 "energy_db", "energy_raw_db", "background_db", "above_background_db", "peak_dbfs", "near_clip_samples",
423404 "energy_band_low_hz", "energy_band_high_hz", "spectrum_band_low_hz", "spectrum_band_high_hz", "sheet_length_in",
424405 ];
@@ -430,7 +411,7 @@ function exportCsv(rows: Row[], settings: AnalysisSettings) {
430411 for (const { meta: m, a } of rows) {
431412 lines.push(
432413 [
433- m.label, new Date(m.createdAt).toISOString(), m.source, m.sampleRate, a.segment.start.toFixed(4), a.segment.end.toFixed(4), m.segmentManual,
414+ m.label, m.notes, new Date(m.createdAt).toISOString(), m.source, m.sampleRate, a.segment.start.toFixed(4), a.segment.end.toFixed(4), m.segmentManual,
434415 a.duration.toFixed(4), a.speedInPerSec.toFixed(4), db10(a.energy).toFixed(3), db10(a.energyRaw).toFixed(3), db10(a.energyNoise).toFixed(3),
435416 a.snrDb.toFixed(2), a.peakDbfs.toFixed(2), a.nearClip,
436417 settings.energyLow, settings.energyHigh, settings.shapeLow, settings.shapeHigh, settings.sheetLengthIn,
src/components/RecordPanel.tsxmodified+5−7View file
@@ -2,18 +2,16 @@ import { useEffect } from "react";
22 import { mic, useMic } from "../audio/mic.ts";
33 import type { CaptureInfo } from "../audio/recorder.ts";
44 import { decodeWav } from "../audio/wav.ts";
5-import type { Speed } from "../model.ts";
65
76 const MAX_SECONDS = 60;
87
98 interface Props {
10- speed: Speed;
11- replacing: boolean; // a recording already exists for this speed
9+ replacing: boolean; // re-recording an existing sample
1210 onDone: (samples: Float32Array, fs: number, info: CaptureInfo | null, fileName?: string) => Promise<void>;
1311 onCancel: (() => void) | null;
1412 }
1513
16-export function RecordPanel({ speed, replacing, onDone, onCancel }: Props) {
14+export function RecordPanel({ replacing, onDone, onCancel }: Props) {
1715 const m = useMic();
1816 const elapsed = m.status === "recording" ? (performance.now() - m.startedAt) / 1000 : 0;
1917
@@ -71,13 +69,13 @@ export function RecordPanel({ speed, replacing, onDone, onCancel }: Props) {
7169 <section className="card record-panel">
7270 {replacing && (
7371 <div className="replace-note">
74- Re-recording. The current recording stays until you finish; the new one then replaces it.
72+ Re-recording this sample. The current recording stays until you finish; the new one then replaces it.
7573 </div>
7674 )}
7775 <ol className="steps">
7876 <li>Press <b>Start</b> (or the space bar) and keep still for about a second.</li>
7977 <li>
80- Tear one strip off the full 11 inch sheet, taking <b>{speed.target}</b>.
78+ Tear one strip off the full 11 inch sheet, at whatever speed you want to study.
8179 </li>
8280 <li>Keep still for another second, then press <b>Stop</b>.</li>
8381 </ol>
@@ -141,7 +139,7 @@ export function RecordPanel({ speed, replacing, onDone, onCancel }: Props) {
141139 )}
142140
143141 <label className="file-link">
144- or load a WAV file for this speed
142+ or load a WAV file instead
145143 <input type="file" accept=".wav,audio/wav" onChange={(e) => loadFile(e.target.files?.[0])} />
146144 </label>
147145 </section>
src/components/TearView.tsxmodified+6−7View file
@@ -3,7 +3,7 @@ import { CanvasPlot, drawLine, readTheme, type PointerInfo, type Scales, type Th
33 import { bandLevels, detectSegment, energyBand, smoothLog, spectrogram, type Analysis, type AnalysisSettings, type Segment } from "../analysis/analyze.ts";
44 import type { RecordingMeta } from "../storage/db.ts";
55 import { play, stop as stopPlay, usePlayhead } from "../audio/player.ts";
6-import { colorFor, db10, fmtHz, fmtSec, getAnalysis, getAudio, speedStyle } from "../model.ts";
6+import { db10, fmtHz, fmtSec, getAnalysis, getAudio } from "../model.ts";
77 import { magma } from "../colormap.ts";
88
99 interface Props {
@@ -53,8 +53,7 @@ export function TearView({ meta, settings, onUpdate }: Props) {
5353 const levels = useMemo(() => (x ? bandLevels(x, fs, { lo: energyLow, hi: energyHigh }, 0.005) : null), [x, fs, energyLow, energyHigh]);
5454 const spec = useMemo(() => (x ? spectrogram(x, fs) : null), [x, fs]);
5555 const specImage = useMemo(() => (spec ? spectrogramImage(spec) : null), [spec]);
56- const { slot } = speedStyle(meta.label);
57- const mainColor = (th: Theme) => colorFor(slot, th.series, th.ink2);
56+ const mainColor = (th: Theme) => th.series[0];
5857
5958 const commitSeg = (s: Segment | null) => {
6059 setSeg(s);
@@ -154,7 +153,7 @@ export function TearView({ meta, settings, onUpdate }: Props) {
154153 drawPlayhead(ctx, s, th);
155154 },
156155 // eslint-disable-next-line react-hooks/exhaustive-deps
157- [levels, seg, slot, playhead],
156+ [levels, seg, playhead],
158157 );
159158
160159 // ---------- close-up ----------
@@ -258,7 +257,7 @@ export function TearView({ meta, settings, onUpdate }: Props) {
258257 drawPlayhead(ctx, s, th);
259258 },
260259 // eslint-disable-next-line react-hooks/exhaustive-deps
261- [x, view, fs, seg, slot, playhead],
260+ [x, view, fs, seg, playhead],
262261 );
263262
264263 const drawSpec = useCallback(
@@ -315,7 +314,7 @@ export function TearView({ meta, settings, onUpdate }: Props) {
315314 drawLine(ctx, s, specLines.f, specLines.tear, mainColor(th), 2);
316315 },
317316 // eslint-disable-next-line react-hooks/exhaustive-deps
318- [specLines, settings, fHi, slot],
317+ [specLines, settings, fHi],
319318 );
320319 const specHover = (p: PointerInfo) => {
321320 if (!specLines) return null;
@@ -482,7 +481,7 @@ export function TearView({ meta, settings, onUpdate }: Props) {
482481 />
483482 <div className="legend">
484483 <span>
485- <i className="swatch" style={{ background: colorFor(slot, th.series, th.ink2) }} /> tear
484+ <i className="swatch" style={{ background: th.series[0] }} /> tear
486485 </span>
487486 <span>
488487 <i className="swatch dashed" /> background alone, over the same duration
src/model.tsmodified+19−25View file
@@ -1,36 +1,30 @@
11 import { analyze, DEFAULT_SETTINGS, type Analysis, type AnalysisSettings } from "./analysis/analyze.ts";
22 import { loadAudio, type RecordingMeta } from "./storage/db.ts";
3-import type { MarkerShape } from "./components/CanvasPlot.tsx";
4-import { SHAPES } from "./components/CanvasPlot.tsx";
3+import type { Theme } from "./components/CanvasPlot.tsx";
54
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-}
5+// ---------- samples ----------
126
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" },
19-];
7+export const tearDuration = (m: RecordingMeta): number | null => (m.segment ? m.segment.end - m.segment.start : null);
208
21-export const speedName = (id: string) => {
22- const s = SPEEDS.find((v) => v.id === id);
23- return s ? `${s.name} (${s.target})` : id;
24-};
9+// Slowest first; samples without a tear range go last.
10+export function sortSamples(recs: RecordingMeta[]): RecordingMeta[] {
11+ return [...recs].sort((a, b) => (tearDuration(b) ?? -1) - (tearDuration(a) ?? -1) || a.createdAt - b.createdAt);
12+}
2513
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" };
14+export function sampleTitle(m: RecordingMeta): string {
15+ const d = tearDuration(m);
16+ return d === null ? "no tear marked" : `${fmtSec(d)} tear`;
3017 }
3118
32-export function colorFor(slot: number | null, series: string[], muted: string) {
33- return slot === null ? muted : series[slot];
19+// Colour encodes tear duration on a fixed log scale (0.2 s … 15 s), so a sample keeps its
20+// colour when others are added. Faster tears get the strongest colour.
21+export const DURATION_SCALE: [number, number] = [0.2, 15];
22+
23+export function durationColor(d: number | null, th: Theme): string {
24+ if (d === null || !th.ramp.length) return th.muted;
25+ const [lo, hi] = DURATION_SCALE;
26+ const t = Math.min(1, Math.max(0, Math.log(d / lo) / Math.log(hi / lo))); // 0 = fast, 1 = slow
27+ return th.ramp[Math.round((1 - t) * (th.ramp.length - 1))];
3428 }
3529
3630 // ---------- settings ----------
src/styles.cssmodified+42−0View file
@@ -24,6 +24,16 @@
2424 --series-6: #008300;
2525 --series-7: #6250d6;
2626 --series-8: #e34948;
27+ --ramp-0: #86b6ef;
28+ --ramp-1: #6da7ec;
29+ --ramp-2: #5598e7;
30+ --ramp-3: #3987e5;
31+ --ramp-4: #2a78d6;
32+ --ramp-5: #256abf;
33+ --ramp-6: #1c5cab;
34+ --ramp-7: #184f95;
35+ --ramp-8: #104281;
36+ --ramp-9: #0d366b;
2737 }
2838 @media (prefers-color-scheme: dark) {
2939 :root:not([data-theme="light"]) {
@@ -50,6 +60,16 @@
5060 --series-6: #008300;
5161 --series-7: #9085e9;
5262 --series-8: #e66767;
63+ --ramp-0: #184f95;
64+ --ramp-1: #1c5cab;
65+ --ramp-2: #256abf;
66+ --ramp-3: #2a78d6;
67+ --ramp-4: #3987e5;
68+ --ramp-5: #5598e7;
69+ --ramp-6: #6da7ec;
70+ --ramp-7: #86b6ef;
71+ --ramp-8: #9ec5f4;
72+ --ramp-9: #cde2fb;
5373 }
5474 }
5575
@@ -790,3 +810,25 @@ button.link {
790810 .settings-row > b {
791811 min-width: 110px;
792812 }
813+
814+.new-item .plus {
815+ width: 12px;
816+ text-align: center;
817+ font-weight: 700;
818+ color: var(--accent);
819+}
820+.new-item {
821+ border-bottom: 1px solid var(--border);
822+}
823+.name-row {
824+ display: flex;
825+ gap: 8px;
826+ flex-wrap: wrap;
827+}
828+.name-row input {
829+ width: 220px;
830+}
831+.name-row .notes-input {
832+ flex: 1;
833+ min-width: 220px;
834+}
↑↓ move↵openescclose