/ music / acoustic-base
Sign in
music / acoustic-base
acoustic-base / src / core / dsp.ts
217 lines · 10.3 KBCodeBlameHistory
087c169Physically simulated pizzicato double bass and an SF2 built from itJeremy Magland 1// Signal helpers shared by the app and the scripts: decimation, WAV encoding, FFT, and the
2// analyses used to compare the simulation with the reference (spectrum, spectrogram, partial decay).
4/** Decimate by an integer factor with a windowed-sinc low-pass (cutoff 0.45 of the output rate). */
5export function decimate(x: Float64Array, factor: number): Float64Array {
6 if (factor <= 1) return Float64Array.from(x);
7 const taps = 32 * factor + 1, half = (taps - 1) / 2;
8 const fc = 0.45 / factor; // cycles per input sample
9 const h = new Float64Array(taps);
10 let s = 0;
11 for (let i = 0; i < taps; i++) {
12 const t = i - half;
13 const sinc = t === 0 ? 2 * fc : Math.sin(2 * Math.PI * fc * t) / (Math.PI * t);
14 const win = 0.42 - 0.5 * Math.cos((2 * Math.PI * i) / (taps - 1)) + 0.08 * Math.cos((4 * Math.PI * i) / (taps - 1));
15 h[i] = sinc * win; s += h[i];
16 }
17 for (let i = 0; i < taps; i++) h[i] /= s;
18 const n = Math.floor(x.length / factor);
19 const y = new Float64Array(n);
20 for (let j = 0; j < n; j++) {
21 const c = j * factor;
22 let acc = 0;
23 const i0 = Math.max(0, c - half), i1 = Math.min(x.length - 1, c + half);
24 for (let i = i0; i <= i1; i++) acc += h[i - c + half] * x[i];
25 y[j] = acc;
26 }
27 return y;
30/** 16-bit PCM mono WAV (or 32-bit float if float = true). */
31export function encodeWav(x: ArrayLike<number>, fs: number, opts: { float?: boolean; scale?: number } = {}): Uint8Array {
32 const n = x.length, flt = !!opts.float, bps = flt ? 4 : 2;
33 const scale = opts.scale ?? 1;
34 const b = new Uint8Array(44 + bps * n);
35 const v = new DataView(b.buffer);
36 const str = (o: number, s: string) => { for (let i = 0; i < s.length; i++) b[o + i] = s.charCodeAt(i); };
37 str(0, "RIFF"); v.setUint32(4, 36 + bps * n, true); str(8, "WAVEfmt "); v.setUint32(16, 16, true);
38 v.setUint16(20, flt ? 3 : 1, true); v.setUint16(22, 1, true); v.setUint32(24, fs, true); v.setUint32(28, fs * bps, true);
39 v.setUint16(32, bps, true); v.setUint16(34, 8 * bps, true); str(36, "data"); v.setUint32(40, bps * n, true);
40 for (let i = 0; i < n; i++) {
41 const s = x[i] * scale;
42 if (flt) v.setFloat32(44 + 4 * i, s, true);
43 else v.setInt16(44 + 2 * i, Math.round(Math.max(-1, Math.min(1, s)) * 32767), true);
44 }
45 return b;
48/** Decode a PCM16 / float32 mono or stereo WAV (first channel). */
49export function decodeWav(buf: Uint8Array): { x: Float64Array; fs: number } {
50 const v = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
51 let o = 12, fmt = 1, ch = 1, fs = 44100, bits = 16;
52 while (o + 8 <= buf.length) {
53 const id = String.fromCharCode(buf[o], buf[o + 1], buf[o + 2], buf[o + 3]);
54 const sz = v.getUint32(o + 4, true);
55 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); }
56 if (id === "data") {
57 const bps = bits / 8, n = Math.floor(sz / (bps * ch));
58 const x = new Float64Array(n);
59 for (let i = 0; i < n; i++) {
60 const p = o + 8 + i * bps * ch;
61 x[i] = fmt === 3 ? v.getFloat32(p, true) : v.getInt16(p, true) / 32768;
62 }
63 return { x, fs };
64 }
65 o += 8 + sz + (sz & 1);
66 }
67 throw new Error("no data chunk");
70/** In-place radix-2 complex FFT. */
71export function fft(re: Float64Array, im: Float64Array): void {
72 const n = re.length;
73 for (let i = 1, j = 0; i < n; i++) {
74 let bit = n >> 1;
75 for (; j & bit; bit >>= 1) j ^= bit;
76 j ^= bit;
77 if (i < j) { [re[i], re[j]] = [re[j], re[i]]; [im[i], im[j]] = [im[j], im[i]]; }
78 }
79 for (let len = 2; len <= n; len <<= 1) {
80 const ang = (-2 * Math.PI) / len, wr = Math.cos(ang), wi = Math.sin(ang);
81 for (let i = 0; i < n; i += len) {
82 let cr = 1, ci = 0;
83 for (let j = 0; j < len / 2; j++) {
84 const a = i + j, b = a + len / 2;
85 const tr = re[b] * cr - im[b] * ci, ti = re[b] * ci + im[b] * cr;
86 re[b] = re[a] - tr; im[b] = im[a] - ti; re[a] += tr; im[a] += ti;
87 const t = cr * wr - ci * wi; ci = cr * wi + ci * wr; cr = t;
88 }
89 }
90 }
93/** Magnitude spectrum (dB) of a Hann-windowed frame starting at `start`, length n (power of 2). */
94export function spectrumDb(x: ArrayLike<number>, start: number, n: number): Float64Array {
95 const re = new Float64Array(n), im = new Float64Array(n);
96 for (let i = 0; i < n; i++) {
97 const v = start + i < x.length ? x[start + i] : 0;
98 re[i] = v * (0.5 - 0.5 * Math.cos((2 * Math.PI * i) / n));
99 }
100 fft(re, im);
101 const out = new Float64Array(n / 2);
102 for (let i = 0; i < n / 2; i++) out[i] = 10 * Math.log10(re[i] * re[i] + im[i] * im[i] + 1e-30);
103 return out;
106/** Spectrogram: frames x bins (dB), hop in samples. */
107export function spectrogram(x: ArrayLike<number>, n: number, hop: number): { frames: Float64Array[]; hop: number; n: number } {
108 const frames: Float64Array[] = [];
109 for (let s = 0; s + n <= x.length; s += hop) frames.push(spectrumDb(x, s, n));
110 return { frames, hop, n };
113/**
114 * Track partials near multiples of f1 (allowing inharmonicity) and estimate each one's level at
115 * the start and its decay (T60, from a line fit to the dB envelope over the window where it is
116 * above the noise floor).
117 */
118export function partialDecay(x: ArrayLike<number>, fs: number, f1: number, maxPartials = 30, maxF = 8000): { n: number; f: number; levelDb: number; t60: number }[] {
119 const n = 8192, hop = 1024;
120 const sg = spectrogram(x, n, hop);
121 if (sg.frames.length < 3) return [];
122 const df = fs / n;
123 const res: { n: number; f: number; levelDb: number; t60: number }[] = [];
124 for (let k = 1; k <= maxPartials; k++) {
125 const fGuess = k * f1;
126 if (fGuess > maxF) break;
127 // refine the frequency on the first frames
128 const lo = Math.max(1, Math.floor((fGuess * 0.97) / df)), hi = Math.ceil((fGuess * 1.06) / df);
129 let best = lo, bv = -Infinity;
130 const f0 = sg.frames[1];
131 for (let b = lo; b <= hi && b < f0.length; b++) if (f0[b] > bv) { bv = f0[b]; best = b; }
132 const env: number[] = sg.frames.map((fr) => Math.max(fr[best - 1] ?? -300, fr[best], fr[best + 1] ?? -300));
133 const peak = Math.max(...env.slice(0, 4));
134 // fit over frames from the peak until 40 dB down (or the end)
135 const i0 = env.indexOf(peak);
136 let i1 = i0;
137 while (i1 + 1 < env.length && env[i1 + 1] > peak - 40) i1++;
138 if (i1 - i0 < 2) { res.push({ n: k, f: best * df, levelDb: peak, t60: NaN }); continue; }
139 let sx = 0, sy = 0, sxx = 0, sxy = 0, cnt = 0;
140 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++; }
141 const slope = (cnt * sxy - sx * sy) / (cnt * sxx - sx * sx);
142 res.push({ n: k, f: best * df, levelDb: peak, t60: slope < 0 ? -60 / slope : Infinity });
143 }
144 return res;
147/** RMS over [t0, t1) seconds. */
148export function rms(x: ArrayLike<number>, fs: number, t0 = 0, t1 = Infinity): number {
149 const i0 = Math.max(0, Math.floor(t0 * fs)), i1 = Math.min(x.length, Math.floor(t1 * fs));
150 let s = 0;
151 for (let i = i0; i < i1; i++) s += x[i] * x[i];
152 return Math.sqrt(s / Math.max(1, i1 - i0));
155/** Spectral centroid (Hz) over [t0, t1) seconds. */
156export function centroid(x: ArrayLike<number>, fs: number, t0: number, t1: number): number {
157 const n = 8192;
158 const start = Math.floor(t0 * fs), end = Math.floor(t1 * fs);
159 let num = 0, den = 0;
160 for (let s = start; s + n <= Math.max(end, start + n) && s + n <= x.length; s += n / 2) {
161 const sp = spectrumDb(x, s, n);
162 for (let b = 1; b < sp.length; b++) { const pw = Math.pow(10, sp[b] / 10); num += pw * (b * fs) / n; den += pw; }
163 }
164 return den > 0 ? num / den : 0;
167/** Energy decay: time for the RMS envelope (50 ms windows) to fall 20 dB and 40 dB from its peak. */
168export function envelopeDecay(x: ArrayLike<number>, fs: number): { t20: number; t40: number; envDb: number[]; win: number } {
169 const win = Math.round(0.05 * fs);
170 const envDb: number[] = [];
171 for (let s = 0; s + win <= x.length; s += win) {
172 let e = 0;
173 for (let i = s; i < s + win; i++) e += x[i] * x[i];
174 envDb.push(10 * Math.log10(e / win + 1e-30));
175 }
176 const pk = Math.max(...envDb), ip = envDb.indexOf(pk);
177 const find = (db: number) => { for (let i = ip; i < envDb.length; i++) if (envDb[i] < pk - db) return (i * win) / fs; return NaN; };
178 return { t20: find(20), t40: find(40), envDb, win: win / fs };
181/**
182 * Frequency of the strongest spectral peak within +-3 % of f, over [t0, t0 + win) seconds (Hann
183 * window, 8x zero padding, parabolic interpolation on the log magnitude). Returns 0 if none.
184 */
185export function peakFrequency(x: ArrayLike<number>, fs: number, f: number, t0: number, win: number): number {
186 const w = Math.round(win * fs), s = Math.round(t0 * fs);
187 const n = 1 << Math.ceil(Math.log2(w * 8));
188 const re = new Float64Array(n), im = new Float64Array(n);
189 for (let i = 0; i < w; i++) re[i] = (x[s + i] ?? 0) * (0.5 - 0.5 * Math.cos((2 * Math.PI * i) / w));
190 fft(re, im);
191 const b0 = Math.max(1, Math.floor((f * 0.97 * n) / fs)), b1 = Math.ceil((f * 1.03 * n) / fs);
192 let bb = -1, bv = 0;
193 for (let b = b0; b <= b1; b++) { const v = Math.hypot(re[b], im[b]); if (v > bv) { bv = v; bb = b; } }
194 if (bb < 1 || bv === 0) return 0;
195 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);
196 const d = (0.5 * (l - r)) / (l - 2 * c + r);
197 return ((bb + (isFinite(d) ? d : 0)) * fs) / n;
200/**
201 * The perceived frequency of a (possibly split, beating) partial near f: the power-weighted mean
202 * frequency of the spectrum within +-rel of f, over bins within 30 dB of the band's maximum
203 * (Hann window over [t0, t0 + win), 8x zero padding).
204 */
205export function bandFrequency(x: ArrayLike<number>, fs: number, f: number, t0: number, win: number, rel = 0.04): number {
206 const w = Math.round(win * fs), s = Math.round(t0 * fs);
207 const n = 1 << Math.ceil(Math.log2(w * 8));
208 const re = new Float64Array(n), im = new Float64Array(n);
209 for (let i = 0; i < w; i++) re[i] = (x[s + i] ?? 0) * (0.5 - 0.5 * Math.cos((2 * Math.PI * i) / w));
210 fft(re, im);
211 const b0 = Math.max(1, Math.floor((f * (1 - rel) * n) / fs)), b1 = Math.ceil((f * (1 + rel) * n) / fs);
212 let mx = 0;
213 for (let b = b0; b <= b1; b++) mx = Math.max(mx, re[b] * re[b] + im[b] * im[b]);
214 let num = 0, den = 0;
215 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; } }
216 return den > 0 ? ((num / den) * fs) / n : 0;
↑↓ move↵openescclose