import { fft, hann } from "./fft.ts"; export interface Segment { start: number; // seconds end: number; } export interface AnalysisSettings { // Analysis band: total energy, tear detection, level over time, the filtered waveform, the // background comparison and spectrum normalisation. High frequencies, where the tear stands // far above room and handling noise. energyLow: number; // Hz energyHigh: number; // Hz sheetLengthIn: number; // length of the tear, inches } export const DEFAULT_SETTINGS: AnalysisSettings = { energyLow: 10000, energyHigh: 20000, sheetLengthIn: 11, }; export interface Band { lo: number; hi: number; } export const energyBand = (s: AnalysisSettings): Band => ({ lo: s.energyLow, hi: s.energyHigh }); export const NFFT = 2048; // ---------- level over time ---------- export interface Levels { frameSec: number; power: Float64Array; // mean square per frame (FS^2) } export function frameLevels(x: Float32Array, fs: number, frameSec = 0.01): Levels { const n = Math.max(1, Math.round(frameSec * fs)); const count = Math.ceil(x.length / n); const power = new Float64Array(count); for (let f = 0; f < count; f++) { let s = 0; const a = f * n; const b = Math.min(x.length, a + n); for (let i = a; i < b; i++) s += x[i] * x[i]; power[f] = s / Math.max(1, b - a); } return { frameSec: n / fs, power }; } function percentile(values: ArrayLike, p: number): number { const a = Array.from(values).sort((u, v) => u - v); if (!a.length) return 0; return a[Math.min(a.length - 1, Math.max(0, Math.floor(p * (a.length - 1))))]; } // Mean-square level within a frequency band, from short Hann-windowed FFT frames // (512 samples) centred every `hopSec`. Calibrated so white noise gives its in-band power. export function bandLevels(x: Float32Array, fs: number, band: Band, hopSec = 0.005): Levels { const n = 512; const hop = Math.max(1, Math.round(hopSec * fs)); const count = Math.max(1, Math.ceil(x.length / hop)); const w = hann(n); let u = 0; for (let i = 0; i < n; i++) u += w[i] * w[i]; const df = fs / n; const kLo = Math.max(1, Math.ceil(band.lo / df)); const kHi = Math.min(n / 2, Math.floor(Math.min(band.hi, fs / 2) / df)); const re = new Float64Array(n); const im = new Float64Array(n); const power = new Float64Array(count); for (let f = 0; f < count; f++) { const c = Math.round((f + 0.5) * hop) - n / 2; im.fill(0); for (let i = 0; i < n; i++) re[i] = (x[c + i] ?? 0) * w[i]; fft(re, im); let p = 0; for (let k = kLo; k <= kHi; k++) p += re[k] * re[k] + im[k] * im[k]; power[f] = (2 * p) / (fs * u) * df; } return { frameSec: hop / fs, power }; } // ---------- finding the tear ---------- // Bump when the detector changes, so ranges found by an older version are found again. export const DETECT_VERSION = 2; export interface TearDetection { segment: Segment | null; sigma: number; // background RMS of the filtered waveform threshold: number; // |amplitude| of the filtered waveform that counts as a click leftOut: Segment[]; // other sounds above the threshold that were not taken as the tear } const DETECT = { k: 6, // click threshold, in background RMS (Gaussian noise passes 6 sigma about once in 5e8 samples) blockSec: 0.01, // blocks for the background estimate mergeSec: 0.01, // crossings closer than this belong to one event tailSec: 0.005, // energy counted after an event's last crossing maxGapSec: 1, // quieter stretches up to this long stay inside one tear isoMinSec: 0.15, // a short sound at either end must be at least this far from the rest to be left out... isoFactor: 8, // ...and this many times the typical gap between the rest's events edgeMaxSec: 0.25, // only sounds shorter than this are left out from the ends preSec: 0.01, // margin before the first click postSec: 0.02, // margin after the last click (its decay) }; interface Ev { a: number; // first sample above threshold b: number; // last sample above threshold e: number; // energy above background } function median(v: number[]): number { if (!v.length) return 0; const a = [...v].sort((p, q) => p - q); const m = a.length >> 1; return a.length % 2 ? a[m] : (a[m - 1] + a[m]) / 2; } // Finds the tear from the clicks in the waveform filtered to the band. The background RMS // is taken from the quietest 10 ms blocks; every stretch where the filtered waveform // exceeds 6x that is a click event. Events closer than 1 s form one sound; the sound with // the most energy is the tear. Short sounds at its ends that stand apart from the rest // (a key press, a click of the trackpad) are left out. `xf` can pass in the filtered // waveform if it is already at hand. export function detectTear(x: Float32Array, fs: number, band: Band, xf?: Float32Array): TearDetection { const y = xf ?? bandpass(x, fs, band); const n = y.length; const none = (sigma = 0, threshold = 0): TearDetection => ({ segment: null, sigma, threshold, leftOut: [] }); const bn = Math.max(16, Math.round(DETECT.blockSec * fs)); const blocks = Math.floor(n / bn); if (blocks < 10) return none(); const rms = new Float64Array(blocks); for (let k = 0; k < blocks; k++) { let s = 0; for (let i = k * bn; i < (k + 1) * bn; i++) s += y[i] * y[i]; rms[k] = Math.sqrt(s / bn); } const sigma = Math.max(percentile(rms, 0.1), 1e-12); const thr = DETECT.k * sigma; const s2 = sigma * sigma; // click events const merge = Math.round(DETECT.mergeSec * fs); const tail = Math.round(DETECT.tailSec * fs); const evs: Ev[] = []; let cur: Ev | null = null; for (let i = 0; i < n; i++) { if (Math.abs(y[i]) <= thr) continue; if (cur && i - cur.b <= merge) cur.b = i; else { if (cur) evs.push(cur); cur = { a: i, b: i, e: 0 }; } } if (cur) evs.push(cur); if (!evs.length) return none(sigma, thr); for (const ev of evs) { let e = 0; const b = Math.min(n, ev.b + tail); for (let i = ev.a; i < b; i++) e += y[i] * y[i] - s2; ev.e = Math.max(0, e); } // sounds: events chained by gaps up to maxGap; the most energetic one is the tear const maxGap = DETECT.maxGapSec * fs; const sounds: Ev[][] = []; for (const ev of evs) { const last = sounds[sounds.length - 1]; if (last && ev.a - last[last.length - 1].b <= maxGap) last.push(ev); else sounds.push([ev]); } const energy = (g: Ev[]) => g.reduce((t, ev) => t + ev.e, 0); let best = 0; for (let i = 1; i < sounds.length; i++) if (energy(sounds[i]) > energy(sounds[best])) best = i; let tear = sounds[best]; const leftOut: Ev[][] = sounds.filter((_, i) => i !== best); // leave out short, separate sounds at either end. "Separate" is judged against the typical // spacing of clicks within the sound: the median of the gaps between events, where a // stretch of clicks that ran together counts as one 10 ms gap per 10 ms. A dense tear // then sets a short spacing however few events it was split into, and a sparse tear // sets the spacing of its own clicks. const spacing = (g: Ev[]) => { const gaps: number[] = []; g.forEach((ev, i) => { if (i > 0) gaps.push(ev.a - g[i - 1].b); for (let k = Math.floor((ev.b - ev.a) / merge); k > 0; k--) gaps.push(merge); }); return median(gaps); }; const split = (g: Ev[], fromEnd: boolean): [Ev[], Ev[]] | null => { const iso = Math.max(DETECT.isoMinSec * fs, DETECT.isoFactor * spacing(g)); for (let j = 0; j < g.length - 1; j++) { const [edge, rest] = fromEnd ? [g.slice(g.length - 1 - j), g.slice(0, g.length - 1 - j)] : [g.slice(0, j + 1), g.slice(j + 1)]; const span = edge[edge.length - 1].b - edge[0].a; if (span > DETECT.edgeMaxSec * fs) return null; const gap = fromEnd ? edge[0].a - rest[rest.length - 1].b : rest[0].a - edge[edge.length - 1].b; if (gap >= iso && energy(edge) < energy(rest)) return [edge, rest]; } return null; }; for (;;) { const lead = split(tear, false); const trail = split(tear, true); const pick = lead && trail ? (energy(lead[0]) <= energy(trail[0]) ? lead : trail) : (lead ?? trail); if (!pick) break; leftOut.push(pick[0]); tear = pick[1]; } const dur = n / fs; const toSeg = (g: Ev[]): Segment => ({ start: Math.max(0, g[0].a / fs - DETECT.preSec), end: Math.min(dur, (g[g.length - 1].b + 1) / fs + DETECT.postSec), }); return { segment: toSeg(tear), sigma, threshold: thr, leftOut: leftOut.map(toSeg).sort((p, q) => p.start - q.start), }; } export function detectSegment(x: Float32Array, fs: number, band: Band): Segment | null { return detectTear(x, fs, band).segment; } // ---------- spectra ---------- // One-sided periodograms (FS^2/Hz) of Hann-windowed frames of x[a..b), hop = half frame. // Frames shorter than NFFT (only when the range itself is short) are zero-padded so the // frequency grid is always the same. function periodograms(x: Float32Array, fs: number, a: number, b: number, nfft: number): Float64Array[] { const len = b - a; if (len < 64) return []; const frameLen = Math.min(nfft, len); const hop = Math.max(1, Math.floor(frameLen / 2)); const w = hann(frameLen); let u = 0; for (let i = 0; i < frameLen; i++) u += w[i] * w[i]; const nb = nfft / 2 + 1; const out: Float64Array[] = []; const re = new Float64Array(nfft); const im = new Float64Array(nfft); const count = Math.max(1, Math.floor((len - frameLen) / hop) + 1); // spread frames to cover the full range evenly const span = len - frameLen; for (let f = 0; f < count; f++) { const off = a + (count > 1 ? Math.round((f * span) / (count - 1)) : 0); re.fill(0); im.fill(0); for (let i = 0; i < frameLen; i++) re[i] = x[off + i] * w[i]; fft(re, im); const p = new Float64Array(nb); for (let k = 0; k < nb; k++) { const v = (re[k] * re[k] + im[k] * im[k]) / (fs * u); p[k] = k === 0 || k === nfft / 2 ? v : 2 * v; } out.push(p); } return out; } // Energy spectral density (FS^2·s/Hz) of x[a..b) on the NFFT grid, from one FFT of the whole // range (no window) whose fine bins are summed into the coarser NFFT bins. By Parseval the // total is exactly the range's energy, and each click counts in full wherever it sits in the // range. (Averaging windowed frames instead weights a click by where it falls under the // windows: near the range edges it nearly vanishes, and even inside it varies by ±2 dB.) function segmentEsd(x: Float32Array, fs: number, a: number, b: number, nfft: number): Float64Array { const nb = nfft / 2 + 1; const out = new Float64Array(nb); const len = b - a; if (len <= 0) return out; let n = nfft; while (n < len) n *= 2; const re = new Float64Array(n); const im = new Float64Array(n); for (let i = 0; i < len; i++) re[i] = x[a + i]; fft(re, im); const per = n / nfft; // fine bins per coarse bin const df = fs / nfft; for (let j = 0; j <= n / 2; j++) { const v = ((j === 0 || j === n / 2 ? 1 : 2) * (re[j] * re[j] + im[j] * im[j])) / (n * fs); out[Math.min(nb - 1, Math.round(j / per))] += v / df; } return out; } // Per-bin median divided by ln 2 (median of an exponential distribution is mean * ln 2). // Robust to occasional transients such as a key press. function medianOf(ps: Float64Array[], nb: number): Float64Array { const out = new Float64Array(nb); const tmp = new Float64Array(ps.length); for (let k = 0; k < nb; k++) { for (let j = 0; j < ps.length; j++) tmp[j] = ps[j][k]; tmp.sort(); const mid = ps.length >> 1; const med = ps.length % 2 ? tmp[mid] : 0.5 * (tmp[mid - 1] + tmp[mid]); out[k] = med / Math.LN2; } return out; } export interface Analysis { segment: Segment; duration: number; // s speedInPerSec: number; fs: number; df: number; freqs: Float64Array; esd: Float64Array; // energy spectral density of the tear segment, FS^2·s/Hz noiseEsd: Float64Array | null; // background PSD × segment duration (what background alone would contribute) netEsd: Float64Array; // max(esd - noiseEsd, 0) noiseSeconds: number; // how much background audio the noise estimate is based on energyRaw: number; // in the analysis band, FS^2·s energyNoise: number; energy: number; // energyRaw - energyNoise snrDb: number; // 10 log10(energyRaw / energyNoise) peakDbfs: number; // in the segment nearClip: number; // samples with |x| >= 0.99 in the segment backgroundDbfs: number | null; // RMS level of background in the analysis band } export function analyze( x: Float32Array, fs: number, segment: Segment, settings: AnalysisSettings, ): Analysis { const nfft = NFFT; const nb = nfft / 2 + 1; const df = fs / nfft; const freqs = new Float64Array(nb); for (let k = 0; k < nb; k++) freqs[k] = k * df; const a = Math.max(0, Math.floor(segment.start * fs)); const b = Math.min(x.length, Math.ceil(segment.end * fs)); const duration = (b - a) / fs; const esd = segmentEsd(x, fs, a, b, nfft); // background: everything outside the segment, keeping clear of its edges and the file ends const margin = Math.round(0.05 * fs); const noisePs: Float64Array[] = []; let noiseSamples = 0; const ranges: [number, number][] = [ [margin, a - margin], [b + margin, x.length - margin], ]; for (const [ra, rb] of ranges) { if (rb - ra >= nfft) { noisePs.push(...periodograms(x, fs, ra, rb, nfft)); noiseSamples += rb - ra; } } let noiseEsd: Float64Array | null = null; if (noisePs.length >= 3) noiseEsd = medianOf(noisePs, nb).map((v) => v * duration); 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))]; const [kLo, kHi] = bins(settings.energyLow, settings.energyHigh); const netEsd = new Float64Array(nb); let energyRaw = 0; let energyNoise = 0; for (let k = 0; k < nb; k++) { netEsd[k] = Math.max(0, esd[k] - (noiseEsd ? noiseEsd[k] : 0)); if (k >= kLo && k <= kHi) { energyRaw += esd[k] * df; if (noiseEsd) energyNoise += noiseEsd[k] * df; } } const energy = energyRaw - energyNoise; let peak = 0; let nearClip = 0; for (let i = a; i < b; i++) { const v = Math.abs(x[i]); if (v > peak) peak = v; if (v >= 0.99) nearClip++; } let backgroundDbfs: number | null = null; if (noiseEsd) { let p = 0; for (let k = kLo; k <= kHi; k++) p += (noiseEsd[k] / duration) * df; backgroundDbfs = 10 * Math.log10(Math.max(p, 1e-20)); } return { segment: { start: a / fs, end: b / fs }, duration, speedInPerSec: settings.sheetLengthIn / duration, fs, df, freqs, esd, noiseEsd, netEsd, noiseSeconds: noiseSamples / fs, energyRaw, energyNoise, energy, snrDb: noiseEsd ? 10 * Math.log10(energyRaw / Math.max(energyNoise, 1e-30)) : Infinity, peakDbfs: 20 * Math.log10(Math.max(peak, 1e-10)), nearClip, backgroundDbfs, }; } // Fractional-octave smoothing onto a log-spaced grid, for readable overlays. export function smoothLog( freqs: Float64Array, values: Float64Array, fLo: number, fHi: number, fraction: number, // e.g. 1/6 octave; 0 = no smoothing (returns raw bins in range) ): { f: number[]; v: number[] } { if (fraction <= 0) { const f: number[] = []; const v: number[] = []; for (let k = 0; k < freqs.length; k++) if (freqs[k] >= fLo && freqs[k] <= fHi) { f.push(freqs[k]); v.push(values[k]); } return { f, v }; } const df = freqs[1] - freqs[0]; const points = Math.ceil(Math.log2(fHi / fLo) / fraction) * 2 + 1; const f: number[] = []; const v: number[] = []; for (let i = 0; i < points; i++) { const fc = fLo * 2 ** ((i * Math.log2(fHi / fLo)) / (points - 1)); const lo = fc * 2 ** (-fraction / 2); const hi = fc * 2 ** (fraction / 2); let ka = Math.ceil(lo / df); let kb = Math.floor(hi / df); if (kb < ka) ka = kb = Math.round(fc / df); ka = Math.max(0, ka); kb = Math.min(freqs.length - 1, kb); let s = 0; for (let k = ka; k <= kb; k++) s += values[k]; f.push(fc); v.push(s / (kb - ka + 1)); } return { f, v }; } // ---------- spectrogram ---------- export interface Spectrogram { cols: number; bins: number; dt: number; // seconds per column t0: number; // centre time of first column df: number; db: Float32Array; // cols × bins, column-major (col * bins + bin), dB re FS^2/Hz maxDb: number; } export function spectrogram(x: Float32Array, fs: number, nfft = 1024, maxCols = 3000): Spectrogram { const hop = Math.max(nfft / 4, Math.ceil(x.length / maxCols)); const cols = Math.max(1, Math.floor((x.length - nfft) / hop) + 1); const bins = nfft / 2 + 1; const w = hann(nfft); let u = 0; for (let i = 0; i < nfft; i++) u += w[i] * w[i]; const db = new Float32Array(cols * bins); const re = new Float64Array(nfft); const im = new Float64Array(nfft); let maxDb = -Infinity; for (let c = 0; c < cols; c++) { const off = c * hop; im.fill(0); for (let i = 0; i < nfft; i++) re[i] = (x[off + i] ?? 0) * w[i]; fft(re, im); for (let k = 0; k < bins; k++) { const p = (2 * (re[k] * re[k] + im[k] * im[k])) / (fs * u); const d = 10 * Math.log10(p + 1e-20); db[c * bins + k] = d; if (d > maxDb) maxDb = d; } } return { cols, bins, dt: hop / fs, t0: nfft / 2 / fs, df: fs / nfft, db, maxDb }; } // ---------- band-pass filter ---------- // Zero-phase band-pass via FFT of the whole signal, with raised-cosine edges (`taper` Hz wide) // to limit ringing. Timing is preserved exactly, which matters for lining up with the raw signal. export function bandpass(x: Float32Array, fs: number, band: Band, taper = 500): Float32Array { let n = 1; while (n < x.length) n *= 2; const re = new Float64Array(n); const im = new Float64Array(n); re.set(x); fft(re, im); const gain = (f: number) => { const lo = band.lo; const hi = Math.min(band.hi, fs / 2); if (f < lo - taper / 2 || f > hi + taper / 2) return 0; if (f < lo + taper / 2) return 0.5 - 0.5 * Math.cos((Math.PI * (f - (lo - taper / 2))) / taper); if (f > hi - taper / 2) return 0.5 - 0.5 * Math.cos((Math.PI * (hi + taper / 2 - f)) / taper); return 1; }; for (let k = 0; k <= n / 2; k++) { const g = gain((k * fs) / n); re[k] *= g; im[k] *= g; if (k > 0 && k < n / 2) { re[n - k] *= g; im[n - k] *= g; } } // inverse FFT via conjugation for (let k = 0; k < n; k++) im[k] = -im[k]; fft(re, im); const out = new Float32Array(x.length); for (let i = 0; i < x.length; i++) out[i] = re[i] / n; return out; }