// Signal helpers shared by the app and the scripts: decimation, WAV encoding, FFT, and the // analyses used to compare the simulation with the reference (spectrum, spectrogram, partial decay). /** Decimate by an integer factor with a windowed-sinc low-pass (cutoff 0.45 of the output rate). */ export function decimate(x: Float64Array, factor: number): Float64Array { if (factor <= 1) return Float64Array.from(x); const taps = 32 * factor + 1, half = (taps - 1) / 2; const fc = 0.45 / factor; // cycles per input sample const h = new Float64Array(taps); let s = 0; for (let i = 0; i < taps; i++) { const t = i - half; const sinc = t === 0 ? 2 * fc : Math.sin(2 * Math.PI * fc * t) / (Math.PI * t); const win = 0.42 - 0.5 * Math.cos((2 * Math.PI * i) / (taps - 1)) + 0.08 * Math.cos((4 * Math.PI * i) / (taps - 1)); h[i] = sinc * win; s += h[i]; } for (let i = 0; i < taps; i++) h[i] /= s; const n = Math.floor(x.length / factor); const y = new Float64Array(n); for (let j = 0; j < n; j++) { const c = j * factor; let acc = 0; const i0 = Math.max(0, c - half), i1 = Math.min(x.length - 1, c + half); for (let i = i0; i <= i1; i++) acc += h[i - c + half] * x[i]; y[j] = acc; } return y; } /** 16-bit PCM mono WAV (or 32-bit float if float = true). */ export function encodeWav(x: ArrayLike, fs: number, opts: { float?: boolean; scale?: number } = {}): Uint8Array { const n = x.length, flt = !!opts.float, bps = flt ? 4 : 2; const scale = opts.scale ?? 1; const b = new Uint8Array(44 + bps * n); const v = new DataView(b.buffer); const str = (o: number, s: string) => { for (let i = 0; i < s.length; i++) b[o + i] = s.charCodeAt(i); }; str(0, "RIFF"); v.setUint32(4, 36 + bps * n, true); str(8, "WAVEfmt "); v.setUint32(16, 16, true); v.setUint16(20, flt ? 3 : 1, true); v.setUint16(22, 1, true); v.setUint32(24, fs, true); v.setUint32(28, fs * bps, true); v.setUint16(32, bps, true); v.setUint16(34, 8 * bps, true); str(36, "data"); v.setUint32(40, bps * n, true); for (let i = 0; i < n; i++) { const s = x[i] * scale; if (flt) v.setFloat32(44 + 4 * i, s, true); else v.setInt16(44 + 2 * i, Math.round(Math.max(-1, Math.min(1, s)) * 32767), true); } return b; } /** Decode a PCM16 / float32 mono or stereo WAV (first channel). */ export function decodeWav(buf: Uint8Array): { x: Float64Array; fs: number } { const v = new DataView(buf.buffer, buf.byteOffset, buf.byteLength); let o = 12, fmt = 1, ch = 1, fs = 44100, bits = 16; while (o + 8 <= buf.length) { const id = String.fromCharCode(buf[o], buf[o + 1], buf[o + 2], buf[o + 3]); const sz = v.getUint32(o + 4, true); if (id === "fmt ") { fmt = v.getUint16(o + 8, true); ch = v.getUint16(o + 10, true); fs = v.getUint32(o + 12, true); bits = v.getUint16(o + 22, true); } if (id === "data") { const bps = bits / 8, n = Math.floor(sz / (bps * ch)); const x = new Float64Array(n); for (let i = 0; i < n; i++) { const p = o + 8 + i * bps * ch; x[i] = fmt === 3 ? v.getFloat32(p, true) : v.getInt16(p, true) / 32768; } return { x, fs }; } o += 8 + sz + (sz & 1); } throw new Error("no data chunk"); } /** In-place radix-2 complex FFT. */ export function fft(re: Float64Array, im: Float64Array): void { const n = re.length; for (let i = 1, j = 0; i < n; i++) { let bit = n >> 1; for (; j & bit; bit >>= 1) j ^= bit; j ^= bit; if (i < j) { [re[i], re[j]] = [re[j], re[i]]; [im[i], im[j]] = [im[j], im[i]]; } } for (let len = 2; len <= n; len <<= 1) { const ang = (-2 * Math.PI) / len, wr = Math.cos(ang), wi = Math.sin(ang); for (let i = 0; i < n; i += len) { let cr = 1, ci = 0; for (let j = 0; j < len / 2; j++) { const a = i + j, b = a + len / 2; const tr = re[b] * cr - im[b] * ci, ti = re[b] * ci + im[b] * cr; re[b] = re[a] - tr; im[b] = im[a] - ti; re[a] += tr; im[a] += ti; const t = cr * wr - ci * wi; ci = cr * wi + ci * wr; cr = t; } } } } /** Magnitude spectrum (dB) of a Hann-windowed frame starting at `start`, length n (power of 2). */ export function spectrumDb(x: ArrayLike, start: number, n: number): Float64Array { const re = new Float64Array(n), im = new Float64Array(n); for (let i = 0; i < n; i++) { const v = start + i < x.length ? x[start + i] : 0; re[i] = v * (0.5 - 0.5 * Math.cos((2 * Math.PI * i) / n)); } fft(re, im); const out = new Float64Array(n / 2); for (let i = 0; i < n / 2; i++) out[i] = 10 * Math.log10(re[i] * re[i] + im[i] * im[i] + 1e-30); return out; } /** Spectrogram: frames x bins (dB), hop in samples. */ export function spectrogram(x: ArrayLike, n: number, hop: number): { frames: Float64Array[]; hop: number; n: number } { const frames: Float64Array[] = []; for (let s = 0; s + n <= x.length; s += hop) frames.push(spectrumDb(x, s, n)); return { frames, hop, n }; } /** * Track partials near multiples of f1 (allowing inharmonicity) and estimate each one's level at * the start and its decay (T60, from a line fit to the dB envelope over the window where it is * above the noise floor). */ export function partialDecay(x: ArrayLike, fs: number, f1: number, maxPartials = 30, maxF = 8000): { n: number; f: number; levelDb: number; t60: number }[] { const n = 8192, hop = 1024; const sg = spectrogram(x, n, hop); if (sg.frames.length < 3) return []; const df = fs / n; const res: { n: number; f: number; levelDb: number; t60: number }[] = []; for (let k = 1; k <= maxPartials; k++) { const fGuess = k * f1; if (fGuess > maxF) break; // refine the frequency on the first frames const lo = Math.max(1, Math.floor((fGuess * 0.97) / df)), hi = Math.ceil((fGuess * 1.06) / df); let best = lo, bv = -Infinity; const f0 = sg.frames[1]; for (let b = lo; b <= hi && b < f0.length; b++) if (f0[b] > bv) { bv = f0[b]; best = b; } const env: number[] = sg.frames.map((fr) => Math.max(fr[best - 1] ?? -300, fr[best], fr[best + 1] ?? -300)); const peak = Math.max(...env.slice(0, 4)); // fit over frames from the peak until 40 dB down (or the end) const i0 = env.indexOf(peak); let i1 = i0; while (i1 + 1 < env.length && env[i1 + 1] > peak - 40) i1++; if (i1 - i0 < 2) { res.push({ n: k, f: best * df, levelDb: peak, t60: NaN }); continue; } let sx = 0, sy = 0, sxx = 0, sxy = 0, cnt = 0; for (let i = i0; i <= i1; i++) { const t = (i * hop) / fs; sx += t; sy += env[i]; sxx += t * t; sxy += t * env[i]; cnt++; } const slope = (cnt * sxy - sx * sy) / (cnt * sxx - sx * sx); res.push({ n: k, f: best * df, levelDb: peak, t60: slope < 0 ? -60 / slope : Infinity }); } return res; } /** RMS over [t0, t1) seconds. */ export function rms(x: ArrayLike, fs: number, t0 = 0, t1 = Infinity): number { const i0 = Math.max(0, Math.floor(t0 * fs)), i1 = Math.min(x.length, Math.floor(t1 * fs)); let s = 0; for (let i = i0; i < i1; i++) s += x[i] * x[i]; return Math.sqrt(s / Math.max(1, i1 - i0)); } /** Spectral centroid (Hz) over [t0, t1) seconds. */ export function centroid(x: ArrayLike, fs: number, t0: number, t1: number): number { const n = 8192; const start = Math.floor(t0 * fs), end = Math.floor(t1 * fs); let num = 0, den = 0; for (let s = start; s + n <= Math.max(end, start + n) && s + n <= x.length; s += n / 2) { const sp = spectrumDb(x, s, n); for (let b = 1; b < sp.length; b++) { const pw = Math.pow(10, sp[b] / 10); num += pw * (b * fs) / n; den += pw; } } return den > 0 ? num / den : 0; } /** Energy decay: time for the RMS envelope (50 ms windows) to fall 20 dB and 40 dB from its peak. */ export function envelopeDecay(x: ArrayLike, fs: number): { t20: number; t40: number; envDb: number[]; win: number } { const win = Math.round(0.05 * fs); const envDb: number[] = []; for (let s = 0; s + win <= x.length; s += win) { let e = 0; for (let i = s; i < s + win; i++) e += x[i] * x[i]; envDb.push(10 * Math.log10(e / win + 1e-30)); } const pk = Math.max(...envDb), ip = envDb.indexOf(pk); const find = (db: number) => { for (let i = ip; i < envDb.length; i++) if (envDb[i] < pk - db) return (i * win) / fs; return NaN; }; return { t20: find(20), t40: find(40), envDb, win: win / fs }; } /** * Frequency of the strongest spectral peak within +-3 % of f, over [t0, t0 + win) seconds (Hann * window, 8x zero padding, parabolic interpolation on the log magnitude). Returns 0 if none. */ export function peakFrequency(x: ArrayLike, fs: number, f: number, t0: number, win: number): number { const w = Math.round(win * fs), s = Math.round(t0 * fs); const n = 1 << Math.ceil(Math.log2(w * 8)); const re = new Float64Array(n), im = new Float64Array(n); for (let i = 0; i < w; i++) re[i] = (x[s + i] ?? 0) * (0.5 - 0.5 * Math.cos((2 * Math.PI * i) / w)); fft(re, im); const b0 = Math.max(1, Math.floor((f * 0.97 * n) / fs)), b1 = Math.ceil((f * 1.03 * n) / fs); let bb = -1, bv = 0; for (let b = b0; b <= b1; b++) { const v = Math.hypot(re[b], im[b]); if (v > bv) { bv = v; bb = b; } } if (bb < 1 || bv === 0) return 0; const l = Math.log(Math.hypot(re[bb - 1], im[bb - 1]) + 1e-300), c = Math.log(bv), r = Math.log(Math.hypot(re[bb + 1], im[bb + 1]) + 1e-300); const d = (0.5 * (l - r)) / (l - 2 * c + r); return ((bb + (isFinite(d) ? d : 0)) * fs) / n; } /** * The perceived frequency of a (possibly split, beating) partial near f: the power-weighted mean * frequency of the spectrum within +-rel of f, over bins within 30 dB of the band's maximum * (Hann window over [t0, t0 + win), 8x zero padding). */ export function bandFrequency(x: ArrayLike, fs: number, f: number, t0: number, win: number, rel = 0.04): number { const w = Math.round(win * fs), s = Math.round(t0 * fs); const n = 1 << Math.ceil(Math.log2(w * 8)); const re = new Float64Array(n), im = new Float64Array(n); for (let i = 0; i < w; i++) re[i] = (x[s + i] ?? 0) * (0.5 - 0.5 * Math.cos((2 * Math.PI * i) / w)); fft(re, im); const b0 = Math.max(1, Math.floor((f * (1 - rel) * n) / fs)), b1 = Math.ceil((f * (1 + rel) * n) / fs); let mx = 0; for (let b = b0; b <= b1; b++) mx = Math.max(mx, re[b] * re[b] + im[b] * im[b]); let num = 0, den = 0; for (let b = b0; b <= b1; b++) { const pw = re[b] * re[b] + im[b] * im[b]; if (pw > mx * 1e-3) { num += pw * b; den += pw; } } return den > 0 ? ((num / den) * fs) / n : 0; }