/ magland / rip-sound-analyzer
Sign in
magland / rip-sound-analyzer
Export/import the whole dataset; filtered waveform by default
Export writes one uncompressed zip: dataset.json (samples and analysis settings) plus a float32 WAV per sample. Import replaces everything in the browser after confirming, checking checksums and that each WAV matches its description.
Jeremy Magland <jmagland@flatironinstitute.org> committed commit bf56870c6478 parent 751f8fa Browse files
7 changed files+292−9
README.mdmodified+3−2View file
@@ -25,9 +25,10 @@ Open the printed localhost URL in Chrome. Everything runs in the browser; record
2525 ## What it does
2626
2727 - **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:
28- - **Tear range**: level in the analysis band, waveform (raw, or filtered to the analysis band) and spectrogram on one zoomable time axis. The range is found automatically; drag across any of the three plots to mark it again, drag its edges, or type start/end times. Play the tear (with a moving playhead) or the whole recording.
28+ - **Tear range**: level in the analysis band, waveform (filtered to the analysis band by default, or raw) and spectrogram on one zoomable time axis. The range is found automatically; drag across any of the three plots 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 - **Frequency makeup**: the tear's energy spectrum against the background.
31+- **Export / import**: “Export dataset” saves every sample and the analysis settings to one .zip (`dataset.json` plus a 32-bit float WAV per sample). “Import dataset…” replaces everything in the browser with such a file, after confirming.
3132 - **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.
3233
3334 Analysis band (set under Analysis settings), default 10–20 kHz: used for total energy, finding the tear, the level plot, the optional filtered waveform, the background comparison and normalising spectra, because lower frequencies carry much more room and handling noise. Spectra are still drawn over the full range for context.
@@ -38,5 +39,5 @@ The “What this can tell you” tab in the app explains the method and its limi
3839
3940 - `src/analysis/` – FFT, tear detection, Welch spectra, energy and spectral statistics
4041 - `src/audio/` – microphone capture, WAV encode/decode, synthetic tears
41-- `src/storage/` – IndexedDB
42+- `src/storage/` – IndexedDB, dataset export/import (uncompressed zip)
4243 - `src/components/` – UI, including a small canvas plotting component
scripts/check-analysis.tsmodified+20−0View file
@@ -2,6 +2,8 @@
22 import { analyze, detectSegment, DEFAULT_SETTINGS, energyBand, bandLevels, bandpass, smoothLog } from "../src/analysis/analyze.ts";
33 import { syntheticTear } from "../src/audio/synthetic.ts";
44 import { decodeWav, encodeWavFloat32 } from "../src/audio/wav.ts";
5+import { exportDataset, readDataset } from "../src/storage/dataset.ts";
6+import type { RecordingMeta } from "../src/storage/db.ts";
57
68 let failed = 0;
79 function check(name: string, ok: boolean, detail = "") {
@@ -79,6 +81,24 @@ check("synthetic spectrum shape independent of duration (1/3 octave, 1–20 kHz,
7981 check("WAV float32 round trip", !!d && d.sampleRate === fs && d.samples.length === x.length && d.samples.every((v, i) => v === x[i]));
8082 }
8183
84+// Dataset export/import round trip
85+{
86+ const audio = new Map<string, Float32Array>();
87+ const recs: RecordingMeta[] = [0.4, 2].map((T, i) => {
88+ const x = syntheticTear({ tearSeconds: T, seed: i });
89+ const id = `id-${i}`;
90+ audio.set(id, x);
91+ return { id, createdAt: 1700000000000 + i, label: i ? "second" : "", notes: "n", material: "paper", source: "mic", sampleRate: fs, length: x.length, segment: { start: 1, end: 1 + T }, segmentManual: i === 1 };
92+ });
93+ const blob = await exportDataset(recs, DEFAULT_SETTINGS, async (id) => audio.get(id)!);
94+ const ds = await readDataset(new File([blob], "d.zip"));
95+ const same =
96+ ds.samples.length === 2 &&
97+ ds.samples.every(({ meta, audio: x }, i) => JSON.stringify(meta) === JSON.stringify(recs[i]) && x.every((v, j) => v === audio.get(meta.id)![j])) &&
98+ JSON.stringify(ds.settings) === JSON.stringify(DEFAULT_SETTINGS);
99+ check("dataset export/import round trip", same);
100+}
101+
82102 if (failed) {
83103 console.log(`${failed} check(s) failed`);
84104 throw new Error("checks failed");
src/App.tsxmodified+67−5View file
@@ -7,6 +7,7 @@ import { readTheme } from "./components/CanvasPlot.tsx";
77 import { DEFAULT_SETTINGS, detectSegment, energyBand } from "./analysis/analyze.ts";
88 import type { CaptureInfo } from "./audio/recorder.ts";
99 import { encodeWavFloat32 } from "./audio/wav.ts";
10+import { exportDataset, readDataset } from "./storage/dataset.ts";
1011 import { clearAll, deleteRecording, listRecordings, newId, saveRecording, updateMeta, type RecordingMeta } from "./storage/db.ts";
1112 import {
1213 download,
@@ -129,6 +130,51 @@ export function App() {
129130 setSelected(NEW);
130131 };
131132
133+ const [busy, setBusy] = useState<string | null>(null);
134+
135+ const doExport = async () => {
136+ setBusy("Exporting…");
137+ try {
138+ const blob = await exportDataset(samples, settings, getAudio);
139+ download(blob, `rip-sound-dataset-${new Date().toISOString().slice(0, 10)}.zip`);
140+ } catch (e) {
141+ alert(`Export failed: ${(e as Error).message}`);
142+ } finally {
143+ setBusy(null);
144+ }
145+ };
146+
147+ const doImport = async (file: File | undefined) => {
148+ if (!file) return;
149+ setBusy("Reading…");
150+ try {
151+ const ds = await readDataset(file);
152+ const n = ds.samples.length;
153+ const when = ds.exportedAt ? ` (exported ${fmtDate(Date.parse(ds.exportedAt))})` : "";
154+ const msg =
155+ `Replace everything in this browser with “${file.name}”${when}?\n\n` +
156+ `${samples.length} current sample${samples.length === 1 ? "" : "s"} will be deleted and ${n} sample${n === 1 ? "" : "s"} loaded from the file. ` +
157+ "The analysis settings saved in the file will be restored too. This cannot be undone.";
158+ if (!confirm(msg)) return;
159+ setBusy("Importing…");
160+ await clearAll();
161+ forgetAllAudio();
162+ for (const { meta, audio } of ds.samples) {
163+ await saveRecording(meta, audio);
164+ putAudio(meta.id, audio);
165+ }
166+ if (ds.settings) setSettings({ ...DEFAULT_SETTINGS, ...ds.settings });
167+ const metas = ds.samples.map((d) => d.meta);
168+ setRecs(metas);
169+ setRerecording(null);
170+ setSelected(metas.length ? sortSamples(metas)[0].id : NEW);
171+ } catch (e) {
172+ alert(`Could not import “${file.name}”: ${(e as Error).message}`);
173+ } finally {
174+ setBusy(null);
175+ }
176+ };
177+
132178 const current = recs.find((r) => r.id === selected) ?? null;
133179 const th = readTheme(document.documentElement);
134180 const dur = current ? tearDuration(current) : null;
@@ -197,13 +243,29 @@ export function App() {
197243 })}
198244 {loaded && !samples.length && <p className="muted pad small">No samples yet.</p>}
199245 <p className="muted pad small">Recordings are stored only in this browser.</p>
200- {samples.length > 0 && (
201- <p className="pad small">
202- <button className="danger" onClick={clearEverything}>
246+ <div className="data-actions pad">
247+ <button onClick={doExport} disabled={!samples.length || !!busy} title="Save every sample and the analysis settings to one .zip file">
248+ Export dataset
249+ </button>
250+ <label className={`button-like ${busy ? "disabled" : ""}`} title="Replace everything in this browser with a dataset file">
251+ Import dataset…
252+ <input
253+ type="file"
254+ accept=".zip,application/zip"
255+ disabled={!!busy}
256+ onChange={(e) => {
257+ void doImport(e.target.files?.[0]);
258+ e.target.value = "";
259+ }}
260+ />
261+ </label>
262+ {samples.length > 0 && (
263+ <button className="danger" onClick={clearEverything} disabled={!!busy}>
203264 Clear all data…
204265 </button>
205- </p>
206- )}
266+ )}
267+ {busy && <span className="muted small">{busy}</span>}
268+ </div>
207269 </aside>
208270
209271 <main className="main">
src/components/TearView.tsxmodified+2−2View file
@@ -202,9 +202,9 @@ export function TearView({ meta, settings, onUpdate }: Props) {
202202 // ---------- waveform (raw or band-passed) ----------
203203 const [filtered, setFilteredState] = useState(() => {
204204 try {
205- return localStorage.getItem("rsa-filter-wave") === "1";
205+ return localStorage.getItem("rsa-filter-wave") !== "0"; // filtered unless turned off
206206 } catch {
207- return false;
207+ return true;
208208 }
209209 });
210210 const setFiltered = (v: boolean) => {
src/storage/dataset.tsadded+63−0View file
@@ -0,0 +1,63 @@
1+// Whole-dataset export/import: a zip holding dataset.json (sample information and analysis
2+// settings) plus one 32-bit float WAV per sample with the exact recorded samples.
3+
4+import type { AnalysisSettings } from "../analysis/analyze.ts";
5+import { decodeWav, encodeWavFloat32 } from "../audio/wav.ts";
6+import type { RecordingMeta } from "./db.ts";
7+import { readZip, writeZip, type ZipEntry } from "./zip.ts";
8+
9+const FORMAT = "rip-sound-analyzer-dataset";
10+const VERSION = 1;
11+
12+interface DatasetJson {
13+ format: string;
14+ version: number;
15+ exportedAt: string;
16+ settings: AnalysisSettings;
17+ samples: (RecordingMeta & { audioFile: string })[];
18+}
19+
20+export async function exportDataset(
21+ recs: RecordingMeta[],
22+ settings: AnalysisSettings,
23+ getAudio: (id: string) => Promise<Float32Array>,
24+): Promise<Blob> {
25+ const entries: ZipEntry[] = [];
26+ const samples: DatasetJson["samples"] = [];
27+ for (const [i, m] of recs.entries()) {
28+ const audioFile = `audio/${String(i + 1).padStart(3, "0")}_${m.id}.wav`;
29+ const x = await getAudio(m.id);
30+ entries.push({ name: audioFile, data: new Uint8Array(await encodeWavFloat32(x, m.sampleRate).arrayBuffer()) });
31+ samples.push({ ...m, audioFile });
32+ }
33+ const json: DatasetJson = { format: FORMAT, version: VERSION, exportedAt: new Date().toISOString(), settings, samples };
34+ entries.unshift({ name: "dataset.json", data: new TextEncoder().encode(JSON.stringify(json, null, 2)) });
35+ return writeZip(entries);
36+}
37+
38+export interface ImportedDataset {
39+ settings: AnalysisSettings | null;
40+ samples: { meta: RecordingMeta; audio: Float32Array }[];
41+ exportedAt: string;
42+}
43+
44+export async function readDataset(file: File): Promise<ImportedDataset> {
45+ const files = readZip(await file.arrayBuffer());
46+ const raw = files.get("dataset.json");
47+ if (!raw) throw new Error("This zip has no dataset.json, so it is not a dataset exported by this app.");
48+ const json = JSON.parse(new TextDecoder().decode(raw)) as DatasetJson;
49+ if (json.format !== FORMAT) throw new Error("dataset.json is not a Rip Sound Analyzer dataset.");
50+ if (json.version > VERSION) throw new Error("This dataset was written by a newer version of the app.");
51+ const samples: ImportedDataset["samples"] = [];
52+ for (const s of json.samples) {
53+ const wavBytes = files.get(s.audioFile);
54+ if (!wavBytes) throw new Error(`Missing audio file ${s.audioFile}.`);
55+ const d = decodeWav(wavBytes.slice().buffer);
56+ if (!d) throw new Error(`Could not read ${s.audioFile}.`);
57+ if (d.sampleRate !== s.sampleRate || d.samples.length !== s.length) throw new Error(`${s.audioFile} does not match its description.`);
58+ const { audioFile: _unused, ...meta } = s;
59+ void _unused;
60+ samples.push({ meta, audio: d.samples });
61+ }
62+ return { settings: json.settings ?? null, samples, exportedAt: json.exportedAt };
63+}
src/storage/zip.tsadded+112−0View file
@@ -0,0 +1,112 @@
1+// Minimal uncompressed ("stored") zip writer and reader. Enough for dataset files:
2+// audio is already raw float samples and would barely compress anyway.
3+
4+const CRC_TABLE = (() => {
5+ const t = new Uint32Array(256);
6+ for (let n = 0; n < 256; n++) {
7+ let c = n;
8+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
9+ t[n] = c >>> 0;
10+ }
11+ return t;
12+})();
13+
14+export function crc32(data: Uint8Array): number {
15+ let c = 0xffffffff;
16+ for (let i = 0; i < data.length; i++) c = CRC_TABLE[(c ^ data[i]) & 0xff] ^ (c >>> 8);
17+ return (c ^ 0xffffffff) >>> 0;
18+}
19+
20+export interface ZipEntry {
21+ name: string;
22+ data: Uint8Array;
23+}
24+
25+export function writeZip(entries: ZipEntry[]): Blob {
26+ const enc = new TextEncoder();
27+ const now = new Date();
28+ const dosTime = (now.getHours() << 11) | (now.getMinutes() << 5) | (now.getSeconds() >> 1);
29+ const dosDate = ((now.getFullYear() - 1980) << 9) | ((now.getMonth() + 1) << 5) | now.getDate();
30+ const parts: BlobPart[] = [];
31+ const central: Uint8Array[] = [];
32+ let offset = 0;
33+ for (const e of entries) {
34+ const name = enc.encode(e.name);
35+ const crc = crc32(e.data);
36+ const local = new DataView(new ArrayBuffer(30));
37+ local.setUint32(0, 0x04034b50, true);
38+ local.setUint16(4, 20, true); // version needed
39+ local.setUint16(6, 0x0800, true); // UTF-8 names
40+ local.setUint16(8, 0, true); // stored
41+ local.setUint16(10, dosTime, true);
42+ local.setUint16(12, dosDate, true);
43+ local.setUint32(14, crc, true);
44+ local.setUint32(18, e.data.length, true);
45+ local.setUint32(22, e.data.length, true);
46+ local.setUint16(26, name.length, true);
47+ local.setUint16(28, 0, true);
48+ parts.push(local.buffer, name as Uint8Array<ArrayBuffer>, e.data as Uint8Array<ArrayBuffer>);
49+
50+ const c = new DataView(new ArrayBuffer(46 + name.length));
51+ c.setUint32(0, 0x02014b50, true);
52+ c.setUint16(4, 20, true);
53+ c.setUint16(6, 20, true);
54+ c.setUint16(8, 0x0800, true);
55+ c.setUint16(10, 0, true);
56+ c.setUint16(12, dosTime, true);
57+ c.setUint16(14, dosDate, true);
58+ c.setUint32(16, crc, true);
59+ c.setUint32(20, e.data.length, true);
60+ c.setUint32(24, e.data.length, true);
61+ c.setUint16(28, name.length, true);
62+ c.setUint32(42, offset, true);
63+ new Uint8Array(c.buffer).set(name, 46);
64+ central.push(new Uint8Array(c.buffer));
65+ offset += 30 + name.length + e.data.length;
66+ }
67+ const cdSize = central.reduce((s, c) => s + c.length, 0);
68+ const end = new DataView(new ArrayBuffer(22));
69+ end.setUint32(0, 0x06054b50, true);
70+ end.setUint16(8, entries.length, true);
71+ end.setUint16(10, entries.length, true);
72+ end.setUint32(12, cdSize, true);
73+ end.setUint32(16, offset, true);
74+ return new Blob([...parts, ...(central as Uint8Array<ArrayBuffer>[]), end.buffer], { type: "application/zip" });
75+}
76+
77+// Reads stored (uncompressed) entries; throws on anything else.
78+export function readZip(buf: ArrayBuffer): Map<string, Uint8Array> {
79+ const v = new DataView(buf);
80+ const bytes = new Uint8Array(buf);
81+ const dec = new TextDecoder();
82+ let eocd = -1;
83+ for (let i = buf.byteLength - 22; i >= Math.max(0, buf.byteLength - 22 - 65535); i--) {
84+ if (v.getUint32(i, true) === 0x06054b50) {
85+ eocd = i;
86+ break;
87+ }
88+ }
89+ if (eocd < 0) throw new Error("Not a zip file.");
90+ const count = v.getUint16(eocd + 10, true);
91+ let p = v.getUint32(eocd + 16, true);
92+ const out = new Map<string, Uint8Array>();
93+ for (let i = 0; i < count; i++) {
94+ if (v.getUint32(p, true) !== 0x02014b50) throw new Error("Damaged zip file.");
95+ const method = v.getUint16(p + 10, true);
96+ const crc = v.getUint32(p + 16, true);
97+ const size = v.getUint32(p + 20, true);
98+ const nameLen = v.getUint16(p + 28, true);
99+ const extraLen = v.getUint16(p + 30, true);
100+ const commentLen = v.getUint16(p + 32, true);
101+ const local = v.getUint32(p + 42, true);
102+ const name = dec.decode(bytes.subarray(p + 46, p + 46 + nameLen));
103+ p += 46 + nameLen + extraLen + commentLen;
104+ if (name.endsWith("/")) continue;
105+ if (method !== 0) throw new Error(`“${name}” is compressed. Use a dataset file exported by this app, without re-zipping it.`);
106+ const start = local + 30 + v.getUint16(local + 26, true) + v.getUint16(local + 28, true);
107+ const data = bytes.subarray(start, start + size);
108+ if (crc32(data) !== crc) throw new Error(`“${name}” is damaged (checksum mismatch).`);
109+ out.set(name, data);
110+ }
111+ return out;
112+}
src/styles.cssmodified+25−0View file
@@ -832,3 +832,28 @@ button.link {
832832 flex: 1;
833833 min-width: 220px;
834834 }
835+
836+.data-actions {
837+ display: flex;
838+ flex-direction: column;
839+ align-items: flex-start;
840+ gap: 6px;
841+}
842+.button-like {
843+ display: inline-block;
844+ background: var(--surface);
845+ border: 1px solid var(--border);
846+ border-radius: 6px;
847+ padding: 4px 10px;
848+ cursor: pointer;
849+}
850+.button-like:hover {
851+ background: var(--hover);
852+}
853+.button-like.disabled {
854+ opacity: 0.45;
855+ pointer-events: none;
856+}
857+.button-like input {
858+ display: none;
859+}
↑↓ move↵openescclose