/ magland / rip-sound-analyzer
Sign in
magland / rip-sound-analyzer
rip-sound-analyzer / src / model.ts
145 lines · 4.3 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";
6// The fixed set of speeds. `id` is what is stored as a recording's label.
7export interface Speed {
8 id: string;
9 name: string;
10 target: string; // intended tear duration
13export 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];
21export const speedName = (id: string) => {
22 const s = SPEEDS.find((v) => v.id === id);
23 return s ? `${s.name} (${s.target})` : id;
24};
26// Colour and marker follow the speed, never its position in a filtered list.
27export 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" };
32export function colorFor(slot: number | null, series: string[], muted: string) {
33 return slot === null ? muted : series[slot];
36// ---------- settings ----------
38const SETTINGS_KEY = "rsa-settings";
40export function loadSettings(): AnalysisSettings {
41 try {
42 const s = JSON.parse(localStorage.getItem(SETTINGS_KEY) ?? "null");
43 if (s) return { ...DEFAULT_SETTINGS, ...s };
44 } catch {
45 /* ignore */
46 }
47 return { ...DEFAULT_SETTINGS };
50export function storeSettings(s: AnalysisSettings) {
51 try {
52 localStorage.setItem(SETTINGS_KEY, JSON.stringify(s));
53 } catch {
54 /* ignore */
55 }
58// ---------- audio + analysis caches ----------
60const audioCache = new Map<string, Promise<Float32Array>>();
62export function getAudio(id: string): Promise<Float32Array> {
63 let p = audioCache.get(id);
64 if (!p) {
65 p = loadAudio(id);
66 audioCache.set(id, p);
67 }
68 return p;
71export function putAudio(id: string, x: Float32Array) {
72 audioCache.set(id, Promise.resolve(x));
75export function forgetAudio(id: string) {
76 audioCache.delete(id);
79const analysisCache = new Map<string, Analysis>();
81function key(m: RecordingMeta, s: AnalysisSettings) {
82 return JSON.stringify([m.id, m.segment, s]);
85export async function getAnalysis(m: RecordingMeta, s: AnalysisSettings): Promise<Analysis | null> {
86 if (!m.segment) return null;
87 const k = key(m, s);
88 const hit = analysisCache.get(k);
89 if (hit) return hit;
90 const x = await getAudio(m.id);
91 const a = analyze(x, m.sampleRate, m.segment, s);
92 analysisCache.set(k, a);
93 return a;
96// ---------- formatting ----------
98export const db10 = (v: number) => 10 * Math.log10(Math.max(v, 1e-30));
100export function fmtHz(v: number) {
101 if (!Number.isFinite(v)) return "–";
102 return v >= 1000 ? `${(v / 1000).toFixed(2)} kHz` : `${v.toFixed(0)} Hz`;
105export function fmtSec(v: number) {
106 return v < 1 ? `${(v * 1000).toFixed(0)} ms` : `${v.toFixed(2)} s`;
109export function fmtDate(t: number) {
110 return new Date(t).toLocaleString(undefined, { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", second: "2-digit" });
113export function download(blob: Blob, name: string) {
114 const url = URL.createObjectURL(blob);
115 const a = document.createElement("a");
116 a.href = url;
117 a.download = name;
118 a.click();
119 setTimeout(() => URL.revokeObjectURL(url), 1000);
122export function safeName(s: string) {
123 return s.replace(/[^a-z0-9.~-]+/gi, "_").replace(/^_+|_+$/g, "");
126// Simple least-squares fit y = a + b x, with standard error of b.
127export function linearFit(xs: number[], ys: number[]): { a: number; b: number; seB: number; n: number } | null {
128 const n = xs.length;
129 if (n < 3) return null;
130 const mx = xs.reduce((s, v) => s + v, 0) / n;
131 const my = ys.reduce((s, v) => s + v, 0) / n;
132 let sxx = 0;
133 let sxy = 0;
134 for (let i = 0; i < n; i++) {
135 sxx += (xs[i] - mx) ** 2;
136 sxy += (xs[i] - mx) * (ys[i] - my);
137 }
138 if (sxx <= 0) return null;
139 const b = sxy / sxx;
140 const a = my - b * mx;
141 let sse = 0;
142 for (let i = 0; i < n; i++) sse += (ys[i] - a - b * xs[i]) ** 2;
143 const seB = Math.sqrt(sse / (n - 2) / sxx);
144 return { a, b, seB, n };
↑↓ move↵openescclose