/ magland / rip-sound-analyzer
Sign in
magland / rip-sound-analyzer
rip-sound-analyzer / src / model.ts
143 lines · 4.3 KBCodeBlameHistory
d0a8b32Rip Sound Analyzer: record tears, inspect one, compare across speedsJeremy Magland 1import { analyze, DEFAULT_SETTINGS, type Analysis, type AnalysisSettings } from "./analysis/analyze.ts";
2import { loadAudio, type RecordingMeta } from "./storage/db.ts";
09371b0Open-ended samples instead of fixed speedsJeremy Magland 3import type { Theme } from "./components/CanvasPlot.tsx";
5// ---------- samples ----------
7export const tearDuration = (m: RecordingMeta): number | null => (m.segment ? m.segment.end - m.segment.start : null);
9// Slowest first; samples without a tear range go last.
10export function sortSamples(recs: RecordingMeta[]): RecordingMeta[] {
11 return [...recs].sort((a, b) => (tearDuration(b) ?? -1) - (tearDuration(a) ?? -1) || a.createdAt - b.createdAt);
09371b0Open-ended samples instead of fixed speedsJeremy Magland 14export function sampleTitle(m: RecordingMeta): string {
15 const d = tearDuration(m);
16 return d === null ? "no tear marked" : `${fmtSec(d)} tear`;
09371b0Open-ended samples instead of fixed speedsJeremy Magland 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.
21export const DURATION_SCALE: [number, number] = [0.2, 15];
23export 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))];
30// ---------- settings ----------
751f8faSelect the tear on level, waveform or spectrogram; 10–20 kHz analysis bandJeremy Magland 32const SETTINGS_KEY = "rsa-settings-v3";
34export function loadSettings(): AnalysisSettings {
35 try {
36 const s = JSON.parse(localStorage.getItem(SETTINGS_KEY) ?? "null");
37 if (s) return { ...DEFAULT_SETTINGS, ...s };
38 } catch {
39 /* ignore */
40 }
41 return { ...DEFAULT_SETTINGS };
44export function storeSettings(s: AnalysisSettings) {
45 try {
46 localStorage.setItem(SETTINGS_KEY, JSON.stringify(s));
47 } catch {
48 /* ignore */
49 }
52// ---------- audio + analysis caches ----------
54const audioCache = new Map<string, Promise<Float32Array>>();
56export function getAudio(id: string): Promise<Float32Array> {
57 let p = audioCache.get(id);
58 if (!p) {
59 p = loadAudio(id);
60 audioCache.set(id, p);
61 }
62 return p;
65export function putAudio(id: string, x: Float32Array) {
66 audioCache.set(id, Promise.resolve(x));
69export function forgetAudio(id: string) {
70 audioCache.delete(id);
135ff3aAdd a button to clear all samples from the browserJeremy Magland 73export function forgetAllAudio() {
74 audioCache.clear();
d0a8b32Rip Sound Analyzer: record tears, inspect one, compare across speedsJeremy Magland 77const analysisCache = new Map<string, Analysis>();
79function key(m: RecordingMeta, s: AnalysisSettings) {
80 return JSON.stringify([m.id, m.segment, s]);
83export async function getAnalysis(m: RecordingMeta, s: AnalysisSettings): Promise<Analysis | null> {
84 if (!m.segment) return null;
85 const k = key(m, s);
86 const hit = analysisCache.get(k);
87 if (hit) return hit;
88 const x = await getAudio(m.id);
89 const a = analyze(x, m.sampleRate, m.segment, s);
90 analysisCache.set(k, a);
91 return a;
94// ---------- formatting ----------
96export const db10 = (v: number) => 10 * Math.log10(Math.max(v, 1e-30));
98export function fmtHz(v: number) {
99 if (!Number.isFinite(v)) return "–";
100 return v >= 1000 ? `${(v / 1000).toFixed(2)} kHz` : `${v.toFixed(0)} Hz`;
103export function fmtSec(v: number) {
104 return v < 1 ? `${(v * 1000).toFixed(0)} ms` : `${v.toFixed(2)} s`;
107export function fmtDate(t: number) {
108 return new Date(t).toLocaleString(undefined, { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", second: "2-digit" });
111export function download(blob: Blob, name: string) {
112 const url = URL.createObjectURL(blob);
113 const a = document.createElement("a");
114 a.href = url;
115 a.download = name;
116 a.click();
117 setTimeout(() => URL.revokeObjectURL(url), 1000);
120export function safeName(s: string) {
121 return s.replace(/[^a-z0-9.~-]+/gi, "_").replace(/^_+|_+$/g, "");
124// Simple least-squares fit y = a + b x, with standard error of b.
125export function linearFit(xs: number[], ys: number[]): { a: number; b: number; seB: number; n: number } | null {
126 const n = xs.length;
127 if (n < 3) return null;
128 const mx = xs.reduce((s, v) => s + v, 0) / n;
129 const my = ys.reduce((s, v) => s + v, 0) / n;
130 let sxx = 0;
131 let sxy = 0;
132 for (let i = 0; i < n; i++) {
133 sxx += (xs[i] - mx) ** 2;
134 sxy += (xs[i] - mx) * (ys[i] - my);
135 }
136 if (sxx <= 0) return null;
137 const b = sxy / sxx;
138 const a = my - b * mx;
139 let sse = 0;
140 for (let i = 0; i < n; i++) sse += (ys[i] - a - b * xs[i]) ** 2;
141 const seB = Math.sqrt(sse / (n - 2) / sxx);
142 return { a, b, seB, n };
↑↓ move↵openescclose