import { test, expect } from "bun:test"; import { resample } from "../../src/dsp/resample.ts"; // Reference: the direct windowed-sinc evaluation (the original implementation), used to check the cached path is exact. function reference(x: Float32Array, from: number, to: number): Float32Array { const sinc = (v: number) => (v === 0 ? 1 : Math.sin(Math.PI * v) / (Math.PI * v)); const ratio = to / from, outLen = Math.round(x.length * ratio), out = new Float32Array(outLen); const cutoff = Math.min(1, ratio), half = 16 / cutoff; for (let j = 0; j < outLen; j++) { const t = j / ratio; const lo = Math.max(0, Math.ceil(t - half)), hi = Math.min(x.length - 1, Math.floor(t + half)); let acc = 0, wsum = 0; for (let i = lo; i <= hi; i++) { const d = i - t; const w = 0.42 + 0.5 * Math.cos((Math.PI * d) / half) + 0.08 * Math.cos((2 * Math.PI * d) / half); const k = cutoff * sinc(cutoff * d) * w; acc += x[i]! * k; wsum += k; } out[j] = wsum !== 0 ? acc / wsum : 0; } return out; } const noise = (n: number) => { let s = 1; return Float32Array.from({ length: n }, () => ((s = (s * 16807) % 2147483647) / 2147483647) * 2 - 1); }; test("2:1 decimation is bit-identical to the direct evaluation and much faster", () => { const x = noise(44100); expect(Array.from(resample(x, 44100, 22050))).toEqual(Array.from(reference(x, 44100, 22050))); const big = noise(44100 * 10); const time = (f: () => unknown) => { const t0 = performance.now(); f(); return performance.now() - t0; }; time(() => resample(big, 44100, 22050)); // warm-up (JIT) const fast = time(() => resample(big, 44100, 22050)), slow = time(() => reference(big, 44100, 22050)); // measured ~40x; a 4x margin keeps this robust on a loaded machine expect(fast * 4).toBeLessThan(slow); }); test("non-integer ratios are unchanged", () => { const x = noise(4800); expect(Array.from(resample(x, 48000, 44100))).toEqual(Array.from(reference(x, 48000, 44100))); expect(Array.from(resample(x, 22050, 44100))).toEqual(Array.from(reference(x, 22050, 44100))); });