/ magland / rip-sound-analyzer
Sign in
magland / rip-sound-analyzer
rip-sound-analyzer / src / analysis / analyze.ts
413 lines · 13.5 KBCodeBlameHistory
d0a8b32Rip Sound Analyzer: record tears, inspect one, compare across speedsJeremy Magland 1import { fft, hann } from "./fft.ts";
3export interface Segment {
4 start: number; // seconds
5 end: number;
6}
8export interface AnalysisSettings {
751f8faSelect the tear on level, waveform or spectrogram; 10–20 kHz analysis bandJeremy Magland 9 // Analysis band: total energy, tear detection, level over time, the filtered waveform, the
10 // background comparison and spectrum normalisation. High frequencies, where the tear stands
11 // far above room and handling noise.
8bf83cfMeasure energy and find the tear in a 15–20 kHz bandJeremy Magland 12 energyLow: number; // Hz
13 energyHigh: number; // Hz
d0a8b32Rip Sound Analyzer: record tears, inspect one, compare across speedsJeremy Magland 14 sheetLengthIn: number; // length of the tear, inches
17export const DEFAULT_SETTINGS: AnalysisSettings = {
8bf83cfMeasure energy and find the tear in a 15–20 kHz bandJeremy Magland 19 energyHigh: 20000,
21};
8bf83cfMeasure energy and find the tear in a 15–20 kHz bandJeremy Magland 23export interface Band {
24 lo: number;
25 hi: number;
28export const energyBand = (s: AnalysisSettings): Band => ({ lo: s.energyLow, hi: s.energyHigh });
32// ---------- level over time ----------
34export interface Levels {
35 frameSec: number;
36 power: Float64Array; // mean square per frame (FS^2)
39export function frameLevels(x: Float32Array, fs: number, frameSec = 0.01): Levels {
40 const n = Math.max(1, Math.round(frameSec * fs));
41 const count = Math.ceil(x.length / n);
42 const power = new Float64Array(count);
43 for (let f = 0; f < count; f++) {
44 let s = 0;
45 const a = f * n;
46 const b = Math.min(x.length, a + n);
47 for (let i = a; i < b; i++) s += x[i] * x[i];
48 power[f] = s / Math.max(1, b - a);
49 }
50 return { frameSec: n / fs, power };
53function percentile(values: ArrayLike<number>, p: number): number {
54 const a = Array.from(values).sort((u, v) => u - v);
55 if (!a.length) return 0;
56 return a[Math.min(a.length - 1, Math.max(0, Math.floor(p * (a.length - 1))))];
8bf83cfMeasure energy and find the tear in a 15–20 kHz bandJeremy Magland 59// Mean-square level within a frequency band, from short Hann-windowed FFT frames
60// (512 samples) centred every `hopSec`. Calibrated so white noise gives its in-band power.
61export function bandLevels(x: Float32Array, fs: number, band: Band, hopSec = 0.005): Levels {
62 const n = 512;
63 const hop = Math.max(1, Math.round(hopSec * fs));
64 const count = Math.max(1, Math.ceil(x.length / hop));
65 const w = hann(n);
66 let u = 0;
67 for (let i = 0; i < n; i++) u += w[i] * w[i];
68 const df = fs / n;
69 const kLo = Math.max(1, Math.ceil(band.lo / df));
70 const kHi = Math.min(n / 2, Math.floor(Math.min(band.hi, fs / 2) / df));
71 const re = new Float64Array(n);
72 const im = new Float64Array(n);
73 const power = new Float64Array(count);
74 for (let f = 0; f < count; f++) {
75 const c = Math.round((f + 0.5) * hop) - n / 2;
76 im.fill(0);
77 for (let i = 0; i < n; i++) re[i] = (x[c + i] ?? 0) * w[i];
78 fft(re, im);
79 let p = 0;
80 for (let k = kLo; k <= kHi; k++) p += re[k] * re[k] + im[k] * im[k];
81 power[f] = (2 * p) / (fs * u) * df;
82 }
83 return { frameSec: hop / fs, power };
86// Finds the tear from the level in the given band: the most energetic stretch well above
87// the background, bridging gaps under 0.6 s. Returns null if nothing stands out.
88export function detectSegment(x: Float32Array, fs: number, band: Band): Segment | null {
89 const { frameSec, power } = bandLevels(x, fs, band, 0.005);
8bf83cfMeasure energy and find the tear in a 15–20 kHz bandJeremy Magland 91 if (m < 20) return null;
92 const smoothN = Math.max(1, Math.round(0.05 / frameSec)); // 50 ms moving average
d0a8b32Rip Sound Analyzer: record tears, inspect one, compare across speedsJeremy Magland 93 const s = new Float64Array(m);
94 let acc = 0;
95 for (let i = 0; i < m; i++) {
96 acc += power[i];
97 if (i >= smoothN) acc -= power[i - smoothN];
98 s[i] = acc / Math.min(i + 1, smoothN);
99 }
8bf83cfMeasure energy and find the tear in a 15–20 kHz bandJeremy Magland 100 const noise = Math.max(percentile(s, 0.1), 1e-20);
d0a8b32Rip Sound Analyzer: record tears, inspect one, compare across speedsJeremy Magland 101 const thresh = noise * 10 ** (12 / 10);
102 const maxGap = Math.round(0.6 / frameSec);
103 const regions: { a: number; b: number; e: number }[] = [];
104 let cur: { a: number; b: number; e: number } | null = null;
105 for (let i = 0; i < m; i++) {
106 if (s[i] > thresh) {
107 if (cur && i - cur.b <= maxGap) cur.b = i;
108 else {
109 if (cur) regions.push(cur);
110 cur = { a: i, b: i, e: 0 };
111 }
112 }
113 }
114 if (cur) regions.push(cur);
115 if (!regions.length) return null;
116 for (const r of regions) {
117 let e = 0;
118 for (let i = r.a; i <= r.b; i++) e += Math.max(0, power[i] - noise);
119 r.e = e;
120 }
121 regions.sort((u, v) => v.e - u.e);
122 const best = regions[0];
8bf83cfMeasure energy and find the tear in a 15–20 kHz bandJeremy Magland 123 // the moving average smears the edges; trim back to frames that are themselves above threshold
124 let a = Math.max(0, best.a - smoothN);
126 while (a < b && power[a] <= thresh) a++;
127 while (b > a && power[b] <= thresh) b--;
128 const pad = 0.03;
129 const dur = x.length / fs;
130 return {
131 start: Math.max(0, a * frameSec - pad),
132 end: Math.min(dur, (b + 1) * frameSec + pad),
133 };
136// ---------- spectra ----------
138// One-sided periodograms (FS^2/Hz) of Hann-windowed frames of x[a..b), hop = half frame.
139// Frames shorter than NFFT (only when the range itself is short) are zero-padded so the
140// frequency grid is always the same.
141function periodograms(x: Float32Array, fs: number, a: number, b: number, nfft: number): Float64Array[] {
142 const len = b - a;
143 if (len < 64) return [];
144 const frameLen = Math.min(nfft, len);
145 const hop = Math.max(1, Math.floor(frameLen / 2));
146 const w = hann(frameLen);
147 let u = 0;
148 for (let i = 0; i < frameLen; i++) u += w[i] * w[i];
149 const nb = nfft / 2 + 1;
150 const out: Float64Array[] = [];
151 const re = new Float64Array(nfft);
152 const im = new Float64Array(nfft);
153 const count = Math.max(1, Math.floor((len - frameLen) / hop) + 1);
154 // spread frames to cover the full range evenly
155 const span = len - frameLen;
156 for (let f = 0; f < count; f++) {
157 const off = a + (count > 1 ? Math.round((f * span) / (count - 1)) : 0);
158 re.fill(0);
159 im.fill(0);
160 for (let i = 0; i < frameLen; i++) re[i] = x[off + i] * w[i];
161 fft(re, im);
162 const p = new Float64Array(nb);
163 for (let k = 0; k < nb; k++) {
164 const v = (re[k] * re[k] + im[k] * im[k]) / (fs * u);
165 p[k] = k === 0 || k === nfft / 2 ? v : 2 * v;
166 }
167 out.push(p);
168 }
169 return out;
172function meanOf(ps: Float64Array[], nb: number): Float64Array {
173 const out = new Float64Array(nb);
174 for (const p of ps) for (let k = 0; k < nb; k++) out[k] += p[k];
175 for (let k = 0; k < nb; k++) out[k] /= ps.length;
176 return out;
179// Per-bin median divided by ln 2 (median of an exponential distribution is mean * ln 2).
180// Robust to occasional transients such as a key press.
181function medianOf(ps: Float64Array[], nb: number): Float64Array {
182 const out = new Float64Array(nb);
183 const tmp = new Float64Array(ps.length);
184 for (let k = 0; k < nb; k++) {
185 for (let j = 0; j < ps.length; j++) tmp[j] = ps[j][k];
186 tmp.sort();
187 const mid = ps.length >> 1;
188 const med = ps.length % 2 ? tmp[mid] : 0.5 * (tmp[mid - 1] + tmp[mid]);
189 out[k] = med / Math.LN2;
190 }
191 return out;
194export interface Analysis {
195 segment: Segment;
196 duration: number; // s
197 speedInPerSec: number;
198 fs: number;
199 df: number;
200 freqs: Float64Array;
201 esd: Float64Array; // energy spectral density of the tear segment, FS^2·s/Hz
202 noiseEsd: Float64Array | null; // background PSD × segment duration (what background alone would contribute)
203 netEsd: Float64Array; // max(esd - noiseEsd, 0)
204 noiseSeconds: number; // how much background audio the noise estimate is based on
751f8faSelect the tear on level, waveform or spectrogram; 10–20 kHz analysis bandJeremy Magland 205 energyRaw: number; // in the analysis band, FS^2·s
207 energy: number; // energyRaw - energyNoise
208 snrDb: number; // 10 log10(energyRaw / energyNoise)
209 peakDbfs: number; // in the segment
210 nearClip: number; // samples with |x| >= 0.99 in the segment
751f8faSelect the tear on level, waveform or spectrogram; 10–20 kHz analysis bandJeremy Magland 211 backgroundDbfs: number | null; // RMS level of background in the analysis band
214export function analyze(
215 x: Float32Array,
216 fs: number,
217 segment: Segment,
218 settings: AnalysisSettings,
219): Analysis {
220 const nfft = NFFT;
221 const nb = nfft / 2 + 1;
222 const df = fs / nfft;
223 const freqs = new Float64Array(nb);
224 for (let k = 0; k < nb; k++) freqs[k] = k * df;
226 const a = Math.max(0, Math.floor(segment.start * fs));
227 const b = Math.min(x.length, Math.ceil(segment.end * fs));
228 const duration = (b - a) / fs;
230 const tearPs = periodograms(x, fs, a, b, nfft);
231 const psd = tearPs.length ? meanOf(tearPs, nb) : new Float64Array(nb);
232 const esd = psd.map((v) => v * duration);
234 // background: everything outside the segment, keeping clear of its edges and the file ends
235 const margin = Math.round(0.05 * fs);
236 const noisePs: Float64Array[] = [];
237 let noiseSamples = 0;
238 const ranges: [number, number][] = [
239 [margin, a - margin],
240 [b + margin, x.length - margin],
241 ];
242 for (const [ra, rb] of ranges) {
243 if (rb - ra >= nfft) {
244 noisePs.push(...periodograms(x, fs, ra, rb, nfft));
245 noiseSamples += rb - ra;
246 }
247 }
248 let noiseEsd: Float64Array | null = null;
249 if (noisePs.length >= 3) noiseEsd = medianOf(noisePs, nb).map((v) => v * duration);
8bf83cfMeasure energy and find the tear in a 15–20 kHz bandJeremy Magland 251 const bins = (lo: number, hi: number) => [Math.max(1, Math.ceil(lo / df)), Math.min(nb - 1, Math.floor(Math.min(hi, fs / 2) / df))];
252 const [kLo, kHi] = bins(settings.energyLow, settings.energyHigh);
d0a8b32Rip Sound Analyzer: record tears, inspect one, compare across speedsJeremy Magland 253 const netEsd = new Float64Array(nb);
254 let energyRaw = 0;
255 let energyNoise = 0;
256 for (let k = 0; k < nb; k++) {
257 netEsd[k] = Math.max(0, esd[k] - (noiseEsd ? noiseEsd[k] : 0));
258 if (k >= kLo && k <= kHi) {
259 energyRaw += esd[k] * df;
260 if (noiseEsd) energyNoise += noiseEsd[k] * df;
261 }
262 }
263 const energy = energyRaw - energyNoise;
266 let peak = 0;
267 let nearClip = 0;
268 for (let i = a; i < b; i++) {
269 const v = Math.abs(x[i]);
270 if (v > peak) peak = v;
271 if (v >= 0.99) nearClip++;
272 }
274 let backgroundDbfs: number | null = null;
275 if (noiseEsd) {
276 let p = 0;
277 for (let k = kLo; k <= kHi; k++) p += (noiseEsd[k] / duration) * df;
278 backgroundDbfs = 10 * Math.log10(Math.max(p, 1e-20));
279 }
281 return {
282 segment: { start: a / fs, end: b / fs },
283 duration,
284 speedInPerSec: settings.sheetLengthIn / duration,
285 fs,
286 df,
287 freqs,
288 esd,
289 noiseEsd,
290 netEsd,
291 noiseSeconds: noiseSamples / fs,
292 energyRaw,
293 energyNoise,
294 energy,
295 snrDb: noiseEsd ? 10 * Math.log10(energyRaw / Math.max(energyNoise, 1e-30)) : Infinity,
296 peakDbfs: 20 * Math.log10(Math.max(peak, 1e-10)),
297 nearClip,
298 backgroundDbfs,
299 };
302// Fractional-octave smoothing onto a log-spaced grid, for readable overlays.
303export function smoothLog(
304 freqs: Float64Array,
305 values: Float64Array,
306 fLo: number,
307 fHi: number,
308 fraction: number, // e.g. 1/6 octave; 0 = no smoothing (returns raw bins in range)
309): { f: number[]; v: number[] } {
310 if (fraction <= 0) {
311 const f: number[] = [];
312 const v: number[] = [];
313 for (let k = 0; k < freqs.length; k++)
314 if (freqs[k] >= fLo && freqs[k] <= fHi) {
315 f.push(freqs[k]);
316 v.push(values[k]);
317 }
318 return { f, v };
319 }
320 const df = freqs[1] - freqs[0];
321 const points = Math.ceil(Math.log2(fHi / fLo) / fraction) * 2 + 1;
322 const f: number[] = [];
323 const v: number[] = [];
324 for (let i = 0; i < points; i++) {
325 const fc = fLo * 2 ** ((i * Math.log2(fHi / fLo)) / (points - 1));
326 const lo = fc * 2 ** (-fraction / 2);
327 const hi = fc * 2 ** (fraction / 2);
328 let ka = Math.ceil(lo / df);
329 let kb = Math.floor(hi / df);
330 if (kb < ka) ka = kb = Math.round(fc / df);
331 ka = Math.max(0, ka);
332 kb = Math.min(freqs.length - 1, kb);
333 let s = 0;
334 for (let k = ka; k <= kb; k++) s += values[k];
335 f.push(fc);
336 v.push(s / (kb - ka + 1));
337 }
338 return { f, v };
341// ---------- spectrogram ----------
343export interface Spectrogram {
344 cols: number;
345 bins: number;
346 dt: number; // seconds per column
347 t0: number; // centre time of first column
348 df: number;
349 db: Float32Array; // cols × bins, column-major (col * bins + bin), dB re FS^2/Hz
350 maxDb: number;
353export function spectrogram(x: Float32Array, fs: number, nfft = 1024, maxCols = 3000): Spectrogram {
354 const hop = Math.max(nfft / 4, Math.ceil(x.length / maxCols));
355 const cols = Math.max(1, Math.floor((x.length - nfft) / hop) + 1);
356 const bins = nfft / 2 + 1;
357 const w = hann(nfft);
358 let u = 0;
359 for (let i = 0; i < nfft; i++) u += w[i] * w[i];
360 const db = new Float32Array(cols * bins);
361 const re = new Float64Array(nfft);
362 const im = new Float64Array(nfft);
363 let maxDb = -Infinity;
364 for (let c = 0; c < cols; c++) {
365 const off = c * hop;
366 im.fill(0);
367 for (let i = 0; i < nfft; i++) re[i] = (x[off + i] ?? 0) * w[i];
368 fft(re, im);
369 for (let k = 0; k < bins; k++) {
370 const p = (2 * (re[k] * re[k] + im[k] * im[k])) / (fs * u);
371 const d = 10 * Math.log10(p + 1e-20);
372 db[c * bins + k] = d;
373 if (d > maxDb) maxDb = d;
374 }
375 }
376 return { cols, bins, dt: hop / fs, t0: nfft / 2 / fs, df: fs / nfft, db, maxDb };
379// ---------- band-pass filter ----------
381// Zero-phase band-pass via FFT of the whole signal, with raised-cosine edges (`taper` Hz wide)
382// to limit ringing. Timing is preserved exactly, which matters for lining up with the raw signal.
383export function bandpass(x: Float32Array, fs: number, band: Band, taper = 500): Float32Array {
384 let n = 1;
385 while (n < x.length) n *= 2;
386 const re = new Float64Array(n);
387 const im = new Float64Array(n);
388 re.set(x);
389 fft(re, im);
390 const gain = (f: number) => {
391 const lo = band.lo;
392 const hi = Math.min(band.hi, fs / 2);
393 if (f < lo - taper / 2 || f > hi + taper / 2) return 0;
394 if (f < lo + taper / 2) return 0.5 - 0.5 * Math.cos((Math.PI * (f - (lo - taper / 2))) / taper);
395 if (f > hi - taper / 2) return 0.5 - 0.5 * Math.cos((Math.PI * (hi + taper / 2 - f)) / taper);
396 return 1;
397 };
398 for (let k = 0; k <= n / 2; k++) {
399 const g = gain((k * fs) / n);
400 re[k] *= g;
401 im[k] *= g;
402 if (k > 0 && k < n / 2) {
403 re[n - k] *= g;
404 im[n - k] *= g;
405 }
406 }
407 // inverse FFT via conjugation
408 for (let k = 0; k < n; k++) im[k] = -im[k];
409 fft(re, im);
410 const out = new Float32Array(x.length);
411 for (let i = 0; i < x.length; i++) out[i] = re[i] / n;
412 return out;
↑↓ move↵openescclose