/ magland / rip-sound-analyzer
Sign in
magland / rip-sound-analyzer
rip-sound-analyzer / src / model.ts
147 lines · 4.5 KBBlameHistoryRaw
1import { analyze, DEFAULT_SETTINGS, type Analysis, type AnalysisSettings } from "./analysis/analyze.ts";
2import { loadAudio, type RecordingMeta } from "./storage/db.ts";
3import type { MarkerShape } from "./components/CanvasPlot.tsx";
4import { SHAPES } from "./components/CanvasPlot.tsx";
6export 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)",
12];
14// Groups in display order: presets first (slow to fast), then custom labels by first use.
15export 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;
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.
24export 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] };
34export function colorFor(slot: number | null, series: string[], muted: string) {
35 return slot === null ? muted : series[slot];
38// ---------- settings ----------
40const SETTINGS_KEY = "rsa-settings";
42export function loadSettings(): AnalysisSettings {
43 try {
44 const s = JSON.parse(localStorage.getItem(SETTINGS_KEY) ?? "null");
45 if (s) return { ...DEFAULT_SETTINGS, ...s };
46 } catch {
47 /* ignore */
48 }
49 return { ...DEFAULT_SETTINGS };
52export function storeSettings(s: AnalysisSettings) {
53 try {
54 localStorage.setItem(SETTINGS_KEY, JSON.stringify(s));
55 } catch {
56 /* ignore */
57 }
60// ---------- audio + analysis caches ----------
62const audioCache = new Map<string, Promise<Float32Array>>();
64export function getAudio(id: string): Promise<Float32Array> {
65 let p = audioCache.get(id);
66 if (!p) {
67 p = loadAudio(id);
68 audioCache.set(id, p);
69 }
70 return p;
73export function putAudio(id: string, x: Float32Array) {
74 audioCache.set(id, Promise.resolve(x));
77export function forgetAudio(id: string) {
78 audioCache.delete(id);
81const analysisCache = new Map<string, Analysis>();
83function key(m: RecordingMeta, s: AnalysisSettings) {
84 return JSON.stringify([m.id, m.segment, s]);
87export async function getAnalysis(m: RecordingMeta, s: AnalysisSettings): Promise<Analysis | null> {
88 if (!m.segment) return null;
89 const k = key(m, s);
90 const hit = analysisCache.get(k);
91 if (hit) return hit;
92 const x = await getAudio(m.id);
93 const a = analyze(x, m.sampleRate, m.segment, s);
94 analysisCache.set(k, a);
95 return a;
98// ---------- formatting ----------
100export const db10 = (v: number) => 10 * Math.log10(Math.max(v, 1e-30));
102export function fmtHz(v: number) {
103 if (!Number.isFinite(v)) return "–";
104 return v >= 1000 ? `${(v / 1000).toFixed(2)} kHz` : `${v.toFixed(0)} Hz`;
107export function fmtSec(v: number) {
108 return v < 1 ? `${(v * 1000).toFixed(0)} ms` : `${v.toFixed(2)} s`;
111export function fmtDate(t: number) {
112 return new Date(t).toLocaleString(undefined, { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", second: "2-digit" });
115export function download(blob: Blob, name: string) {
116 const url = URL.createObjectURL(blob);
117 const a = document.createElement("a");
118 a.href = url;
119 a.download = name;
120 a.click();
121 setTimeout(() => URL.revokeObjectURL(url), 1000);
124export function safeName(s: string) {
125 return s.replace(/[^a-z0-9.~-]+/gi, "_").replace(/^_+|_+$/g, "");
128// Simple least-squares fit y = a + b x, with standard error of b.
129export function linearFit(xs: number[], ys: number[]): { a: number; b: number; seB: number; n: number } | null {
130 const n = xs.length;
131 if (n < 3) return null;
132 const mx = xs.reduce((s, v) => s + v, 0) / n;
133 const my = ys.reduce((s, v) => s + v, 0) / n;
134 let sxx = 0;
135 let sxy = 0;
136 for (let i = 0; i < n; i++) {
137 sxx += (xs[i] - mx) ** 2;
138 sxy += (xs[i] - mx) * (ys[i] - my);
139 }
140 if (sxx <= 0) return null;
141 const b = sxy / sxx;
142 const a = my - b * mx;
143 let sse = 0;
144 for (let i = 0; i < n; i++) sse += (ys[i] - a - b * xs[i]) ** 2;
145 const seB = Math.sqrt(sse / (n - 2) / sxx);
146 return { a, b, seB, n };
↑↓ move↵openescclose