@audio/denoise-core 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/ar.js ADDED
@@ -0,0 +1,131 @@
1
+ // Auto-regressive modelling for click/click-burst interpolation and de-clip extrapolation.
2
+ // - Levinson-Durbin recursion → AR(p) coefficients from autocorrelation
3
+ // - LS interpolation of missing samples from neighbouring AR predictions
4
+ // - Forward AR extrapolation (used by de-clip)
5
+ //
6
+ // Reference: Godsill & Rayner (1998), "Digital Audio Restoration", §5.
7
+
8
+ // Biased autocorrelation R[0..p]. Bias is preferable for short windows (Toeplitz PSD).
9
+ export function autocorr(x, p) {
10
+ let n = x.length, R = new Float64Array(p + 1)
11
+ for (let k = 0; k <= p; k++) {
12
+ let s = 0
13
+ for (let i = 0; i + k < n; i++) s += x[i] * x[i + k]
14
+ R[k] = s
15
+ }
16
+ return R
17
+ }
18
+
19
+ // Levinson-Durbin: solve Toeplitz Yule-Walker for AR(p) coefficients.
20
+ // Returns { a: Float64Array(p+1), e: residual variance }. a[0] = 1 by convention.
21
+ export function levinson(R, p) {
22
+ let a = new Float64Array(p + 1)
23
+ let prev = new Float64Array(p + 1)
24
+ a[0] = 1
25
+ let e = R[0]
26
+ if (e <= 0) return { a, e: 0 }
27
+
28
+ for (let i = 1; i <= p; i++) {
29
+ let k = -R[i]
30
+ for (let j = 1; j < i; j++) k -= a[j] * R[i - j]
31
+ k /= e
32
+ for (let j = 0; j <= i; j++) prev[j] = a[j]
33
+ a[i] = k
34
+ for (let j = 1; j < i; j++) a[j] = prev[j] + k * prev[i - j]
35
+ e *= 1 - k * k
36
+ if (e <= 0) { e = 0; break }
37
+ }
38
+ return { a, e }
39
+ }
40
+
41
+ // Convenience: AR fit on a window.
42
+ export function arFit(x, p) {
43
+ return levinson(autocorr(x, p), p)
44
+ }
45
+
46
+ // Predict next sample via AR(p): x̂[n] = -∑ a[k]·x[n-k], k=1..p.
47
+ export function arPredict(a, hist) {
48
+ let p = a.length - 1, s = 0
49
+ for (let k = 1; k <= p; k++) s -= a[k] * hist[hist.length - k]
50
+ return s
51
+ }
52
+
53
+ // Forward AR extrapolation by m samples beyond context tail.
54
+ // Used for de-clip: fit AR on un-clipped neighbourhood, project into clipped region.
55
+ export function arExtrapolate(context, a, m) {
56
+ let p = a.length - 1
57
+ let buf = new Float64Array(p + m)
58
+ for (let i = 0; i < p; i++) buf[i] = context[context.length - p + i]
59
+ for (let i = 0; i < m; i++) {
60
+ let s = 0
61
+ for (let k = 1; k <= p; k++) s -= a[k] * buf[p + i - k]
62
+ buf[p + i] = s
63
+ }
64
+ return buf.subarray(p)
65
+ }
66
+
67
+ // Least-squares interpolation of indices `gap` (sorted ints) inside x using AR(p).
68
+ // Solves Bᵀ B · u = -Bᵀ A · k, where u = unknowns, k = knowns,
69
+ // (B,A) split of the AR convolution matrix on (gap, ¬gap).
70
+ //
71
+ // Direct sparse Gauss-Seidel is enough for clusters up to ~50 samples; very small
72
+ // gaps (≤8) reduce to a few iterations and are dominated by the AR fit cost itself.
73
+ export function arInterpolate(x, gap, a) {
74
+ let p = a.length - 1
75
+ let n = x.length, m = gap.length
76
+ if (m === 0) return x
77
+
78
+ let inGap = new Uint8Array(n)
79
+ for (let i = 0; i < m; i++) inGap[gap[i]] = 1
80
+
81
+ // M = sum over t of (sum_{k:t-k∈gap} a[k] * a[k - (t - gap_j)]) — assemble m×m system implicitly.
82
+ // For practicality, use Jacobi iteration: x_g = -∑_{j≠g} M[g,j]/M[g,g] · x_j + b/M[g,g]
83
+ // with M[g,g] = ∑_k a[k]² for k where g+k≤n+p
84
+ // and forcing term computed from neighbours.
85
+ let mdiag = new Float64Array(m)
86
+ for (let i = 0; i < m; i++) {
87
+ let g = gap[i], s = 0
88
+ for (let k = 0; k <= p; k++) {
89
+ let t = g + k
90
+ if (t >= 0 && t < n + p) s += a[k] * a[k]
91
+ }
92
+ mdiag[i] = s || 1
93
+ }
94
+
95
+ // initial: linear interpolation between gap boundaries
96
+ for (let i = 0; i < m; i++) {
97
+ let g = gap[i]
98
+ let lo = g, hi = g
99
+ while (lo > 0 && inGap[lo - 1]) lo--
100
+ while (hi < n - 1 && inGap[hi + 1]) hi++
101
+ let xLo = lo > 0 ? x[lo - 1] : 0
102
+ let xHi = hi < n - 1 ? x[hi + 1] : 0
103
+ x[g] = xLo + (xHi - xLo) * (g - lo + 1) / (hi - lo + 2)
104
+ }
105
+
106
+ // 30 Gauss-Seidel sweeps converge well past audible accuracy for short gaps
107
+ let iter = 30
108
+ for (let it = 0; it < iter; it++) {
109
+ for (let i = 0; i < m; i++) {
110
+ let g = gap[i]
111
+ // residual r[t] = ∑_k a[k] x[t-k] for t = g..g+p; gradient wrt x[g] is
112
+ // ∑_k a[k] r[g+k]; setting it to zero gives the update.
113
+ let num = 0
114
+ for (let k = 0; k <= p; k++) {
115
+ let t = g + k
116
+ if (t < 0 || t >= n + p) continue
117
+ let rt = 0
118
+ for (let j = 0; j <= p; j++) {
119
+ let idx = t - j
120
+ if (idx < 0 || idx >= n) continue
121
+ rt += a[j] * x[idx]
122
+ }
123
+ // remove self-contribution so we can solve for x[g]
124
+ rt -= a[k] * x[g]
125
+ num -= a[k] * rt
126
+ }
127
+ x[g] = num / mdiag[i]
128
+ }
129
+ }
130
+ return x
131
+ }
package/index.js ADDED
@@ -0,0 +1,6 @@
1
+ export * from './stft.js'
2
+ export * from './util.js'
3
+ export * from './noise.js'
4
+ export * from './vad.js'
5
+ export * from './ar.js'
6
+ export * from './quality.js'
package/noise.js ADDED
@@ -0,0 +1,119 @@
1
+ // Noise PSD estimators feeding the statistical denoisers (Wiener, OM-LSA, MMSE).
2
+ // - profile: average |X|² over a user-chosen quiet segment (manual baseline)
3
+ // - minimumStatistics: Martin (2001) — track minima of smoothed |X|² in sliding window
4
+ // - imcra: Cohen (2003) — Improved MCRA, two-iteration smoothing + speech-presence-driven
5
+ //
6
+ // All estimators are stateful: pass the same params object across frames in stream mode.
7
+
8
+ import { stftAnalyse } from './stft.js'
9
+
10
+ // One-shot batch profile from a quiet segment of `data`. Returns Float64Array(N/2+1).
11
+ export function noiseProfile(data, opts = {}) {
12
+ let N = opts.frameSize || 2048
13
+ let hop = opts.hopSize || (N >> 2)
14
+ let half = N >> 1
15
+ let from = Math.max(0, opts.from ?? 0)
16
+ let to = Math.min(data.length, opts.to ?? Math.min(data.length, from + N * 8))
17
+ let seg = data.subarray(from, to)
18
+ let psd = new Float64Array(half + 1)
19
+ let count = 0
20
+ stftAnalyse(seg, mag => {
21
+ for (let k = 0; k <= half; k++) psd[k] += mag[k] * mag[k]
22
+ count++
23
+ }, { frameSize: N, hopSize: hop })
24
+ let scale = count ? 1 / count : 0
25
+ for (let k = 0; k <= half; k++) psd[k] *= scale
26
+ return psd
27
+ }
28
+
29
+ // Minimum Statistics (Martin 2001) — frame-by-frame online updater.
30
+ // Keeps a rolling D-frame minimum of smoothed PSD per bin; multiplies by a bias
31
+ // compensation factor so the minimum tracks E{|N|²} rather than the lower-tail.
32
+ //
33
+ // Usage:
34
+ // let est = minStats(half, { D: 96 })
35
+ // stftAnalyse(data, m => est.update(m))
36
+ // let psd = est.psd // current noise PSD
37
+ //
38
+ // D ≈ 1.5 s of frames at hop = N/4 ≈ 96 frames @ 44.1k / N=2048.
39
+ export function minStats(half, opts = {}) {
40
+ let D = opts.D || 96
41
+ let alpha = opts.alpha ?? 0.7 // smoothing on PSD
42
+ let bias = opts.bias ?? 1.5 // empirical comp from Martin §VII
43
+ let smoothed = new Float64Array(half + 1)
44
+ let psd = new Float64Array(half + 1)
45
+ let buf = [] // ring of recent smoothed frames
46
+
47
+ return {
48
+ psd,
49
+ update(mag) {
50
+ let p = new Float64Array(half + 1)
51
+ for (let k = 0; k <= half; k++) {
52
+ let pk = mag[k] * mag[k]
53
+ smoothed[k] = alpha * smoothed[k] + (1 - alpha) * pk
54
+ p[k] = smoothed[k]
55
+ }
56
+ buf.push(p)
57
+ if (buf.length > D) buf.shift()
58
+ for (let k = 0; k <= half; k++) {
59
+ let mn = Infinity
60
+ for (let i = 0; i < buf.length; i++) if (buf[i][k] < mn) mn = buf[i][k]
61
+ psd[k] = mn * bias
62
+ }
63
+ }
64
+ }
65
+ }
66
+
67
+ // IMCRA — Improved Minima Controlled Recursive Averaging (Cohen 2003).
68
+ // Drives noise PSD via speech-presence probability (SPP) so it stops updating
69
+ // during voiced regions. SPP itself is supplied by the caller (see vad.js spp())
70
+ // or computed internally from the smoothed-to-min PSD ratio.
71
+ export function imcra(half, opts = {}) {
72
+ let alpha = opts.alpha ?? 0.92
73
+ let alphaD = opts.alphaD ?? 0.85
74
+ let beta = opts.beta ?? 1.47
75
+ let psd = new Float64Array(half + 1)
76
+ let psdInit = false
77
+ let smoothed = new Float64Array(half + 1)
78
+ let mins = new Float64Array(half + 1)
79
+ let prevMins = new Float64Array(half + 1)
80
+ let frameCount = 0
81
+ let resetEvery = opts.resetEvery || 80 // ≈ 0.9 s @ 44.1k, hop=512
82
+
83
+ return {
84
+ psd,
85
+ update(mag, sppOverride) {
86
+ let init = !psdInit
87
+ for (let k = 0; k <= half; k++) {
88
+ let pk = mag[k] * mag[k]
89
+ smoothed[k] = init ? pk : alpha * smoothed[k] + (1 - alpha) * pk
90
+ if (init || smoothed[k] < mins[k]) mins[k] = smoothed[k]
91
+ if (!init && smoothed[k] < prevMins[k]) prevMins[k] = smoothed[k]
92
+ }
93
+ frameCount++
94
+ if (frameCount >= resetEvery) {
95
+ for (let k = 0; k <= half; k++) {
96
+ let mn = Math.min(mins[k], prevMins[k])
97
+ prevMins[k] = mins[k]
98
+ mins[k] = smoothed[k]
99
+ // bias-compensated minimum tracker
100
+ if (init) psd[k] = mn * beta
101
+ }
102
+ frameCount = 0
103
+ psdInit = true
104
+ }
105
+
106
+ if (!psdInit) return
107
+
108
+ for (let k = 0; k <= half; k++) {
109
+ let mn = Math.min(mins[k], prevMins[k]) * beta
110
+ // SPP from local SNR vs minimum: high if smoothed >> minimum.
111
+ let snr = smoothed[k] / Math.max(mn, 1e-30)
112
+ let p = sppOverride !== undefined ? sppOverride : 1 / (1 + Math.exp(-3 * (snr - 5)))
113
+ let alphaTilde = alphaD + (1 - alphaD) * p
114
+ let pk = mag[k] * mag[k]
115
+ psd[k] = alphaTilde * psd[k] + (1 - alphaTilde) * pk
116
+ }
117
+ }
118
+ }
119
+ }
package/package.json ADDED
@@ -0,0 +1,55 @@
1
+ {
2
+ "name": "@audio/denoise-core",
3
+ "version": "0.1.0",
4
+ "description": "Shared restoration primitives — STFT (batch/stream/analyse), noise estimation (min-stats, IMCRA), VAD, AR modeling, quality metrics",
5
+ "type": "module",
6
+ "sideEffects": false,
7
+ "main": "index.js",
8
+ "exports": {
9
+ ".": "./index.js",
10
+ "./package.json": "./package.json",
11
+ "./stft": "./stft.js",
12
+ "./util": "./util.js",
13
+ "./noise": "./noise.js",
14
+ "./vad": "./vad.js",
15
+ "./ar": "./ar.js",
16
+ "./quality": "./quality.js"
17
+ },
18
+ "files": [
19
+ "index.js",
20
+ "stft.js",
21
+ "util.js",
22
+ "noise.js",
23
+ "vad.js",
24
+ "ar.js",
25
+ "quality.js"
26
+ ],
27
+ "dependencies": {
28
+ "fourier-transform": "^2.0.0"
29
+ },
30
+ "keywords": [
31
+ "audio",
32
+ "dsp",
33
+ "denoise",
34
+ "stft",
35
+ "vad",
36
+ "noise-estimation"
37
+ ],
38
+ "license": "MIT",
39
+ "author": "Dmitry Iv. <dfcreative@gmail.com>",
40
+ "repository": {
41
+ "type": "git",
42
+ "url": "git+https://github.com/audiojs/denoise.git",
43
+ "directory": "packages/denoise-core"
44
+ },
45
+ "homepage": "https://github.com/audiojs/denoise/tree/main/packages/denoise-core",
46
+ "bugs": {
47
+ "url": "https://github.com/audiojs/denoise/issues"
48
+ },
49
+ "engines": {
50
+ "node": ">=18"
51
+ },
52
+ "publishConfig": {
53
+ "access": "public"
54
+ }
55
+ }
package/quality.js ADDED
@@ -0,0 +1,115 @@
1
+ // Objective quality metrics for denoise evaluation.
2
+ // - snr: global signal-to-noise ratio (dB) given clean reference
3
+ // - segSnr: segmental SNR — frame-averaged, perceptually closer than global
4
+ // - lsd: log-spectral distance (dB) — spectral colouration regression
5
+ // - nrr: noise reduction ratio (dB) — how much energy was removed below threshold
6
+ // - speechAttenuation: how much speech energy was removed (dB) — speech-distortion proxy
7
+ //
8
+ // All metrics expect equal-length Float32Array inputs; trim/align caller-side.
9
+
10
+ import { fft } from 'fourier-transform'
11
+ import { hannWindow, lin2db } from './util.js'
12
+
13
+ // Global SNR (dB). Clean = reference, denoised = output. SNR = 10·log10(∑clean² / ∑(clean-out)²)
14
+ export function snr(clean, denoised) {
15
+ let n = Math.min(clean.length, denoised.length)
16
+ let s = 0, e = 0
17
+ for (let i = 0; i < n; i++) {
18
+ let c = clean[i], d = c - denoised[i]
19
+ s += c * c
20
+ e += d * d
21
+ }
22
+ return e > 0 ? 10 * Math.log10(s / e) : Infinity
23
+ }
24
+
25
+ // Segmental SNR — average per-frame SNR clamped to [-10, 35] dB (PESQ-style).
26
+ // Drops silent frames (energy < floor) so silence doesn't bias the mean.
27
+ export function segSnr(clean, denoised, opts = {}) {
28
+ let N = opts.frameSize || 512
29
+ let hop = opts.hopSize || (N >> 1)
30
+ let floor = opts.floor ?? 1e-5
31
+ let n = Math.min(clean.length, denoised.length)
32
+ let sum = 0, frames = 0
33
+ for (let pos = 0; pos + N <= n; pos += hop) {
34
+ let s = 0, e = 0
35
+ for (let i = 0; i < N; i++) {
36
+ let c = clean[pos + i], d = c - denoised[pos + i]
37
+ s += c * c
38
+ e += d * d
39
+ }
40
+ if (s < floor * N) continue
41
+ let snr = 10 * Math.log10(s / Math.max(e, 1e-30))
42
+ sum += Math.max(-10, Math.min(35, snr))
43
+ frames++
44
+ }
45
+ return frames ? sum / frames : 0
46
+ }
47
+
48
+ // Log-spectral distance (dB), frame-averaged. Lower is better (~1 dB transparent).
49
+ export function lsd(a, b, opts = {}) {
50
+ let N = opts.frameSize || 1024
51
+ let hop = opts.hopSize || (N >> 1)
52
+ let floor = opts.floor ?? 1e-5
53
+ let win = hannWindow(N)
54
+ let half = N >> 1
55
+ let mx = new Float64Array(half + 1), my = new Float64Array(half + 1)
56
+ let n = Math.min(a.length, b.length)
57
+ let sum = 0, frames = 0
58
+ for (let pos = 0; pos + N <= n; pos += hop) {
59
+ let ex = magFrame(a, pos, win, N, half, mx)
60
+ let ey = magFrame(b, pos, win, N, half, my)
61
+ if (ex < floor && ey < floor) continue
62
+ let peak = 0
63
+ for (let k = 0; k <= half; k++) {
64
+ if (mx[k] > peak) peak = mx[k]
65
+ if (my[k] > peak) peak = my[k]
66
+ }
67
+ let mfloor = peak * 1e-3 + 1e-12
68
+ let acc = 0
69
+ for (let k = 0; k <= half; k++) {
70
+ let d = 20 * Math.log10((mx[k] + mfloor) / (my[k] + mfloor))
71
+ acc += d * d
72
+ }
73
+ sum += Math.sqrt(acc / (half + 1))
74
+ frames++
75
+ }
76
+ return frames ? sum / frames : 0
77
+ }
78
+
79
+ let _scratch = new Map()
80
+ function magFrame(data, pos, win, N, half, magOut) {
81
+ let f = _scratch.get(N)
82
+ if (!f) { f = new Float64Array(N); _scratch.set(N, f) }
83
+ let e = 0
84
+ for (let i = 0; i < N; i++) {
85
+ let v = (data[pos + i] || 0) * win[i]
86
+ f[i] = v
87
+ e += v * v
88
+ }
89
+ let [re, im] = fft(f)
90
+ for (let k = 0; k <= half; k++) magOut[k] = Math.sqrt(re[k] * re[k] + im[k] * im[k])
91
+ return e
92
+ }
93
+
94
+ // Noise reduction ratio (dB): drop in noise-floor RMS after processing.
95
+ // Caller selects a quiet segment by index. Positive = suppression worked.
96
+ export function nrr(noisy, denoised, from = 0, to) {
97
+ to = to ?? Math.min(noisy.length, denoised.length)
98
+ let nIn = 0, nOut = 0, len = to - from
99
+ for (let i = from; i < to; i++) { nIn += noisy[i] * noisy[i]; nOut += denoised[i] * denoised[i] }
100
+ let inDb = lin2db(Math.sqrt(nIn / len))
101
+ let outDb = lin2db(Math.sqrt(nOut / len))
102
+ return inDb - outDb
103
+ }
104
+
105
+ // Speech attenuation (dB): drop in clean-signal-active RMS — should be near 0.
106
+ // Pass a clean-segment index range so we measure speech retention.
107
+ export function speechAttenuation(clean, denoised, from = 0, to) {
108
+ to = to ?? Math.min(clean.length, denoised.length)
109
+ let cIn = 0, cOut = 0, len = to - from
110
+ for (let i = from; i < to; i++) {
111
+ cIn += clean[i] * clean[i]
112
+ cOut += denoised[i] * denoised[i]
113
+ }
114
+ return lin2db(Math.sqrt(cIn / len)) - lin2db(Math.sqrt(cOut / len))
115
+ }
package/stft.js ADDED
@@ -0,0 +1,134 @@
1
+ // STFT analysis-modification-synthesis with OLA reconstruction.
2
+ // `process(mag, phase, state, ctx)` returns { mag, phase } for synthesis.
3
+ // State persists across frames; OLA divides by ∑win² to make windowing transparent.
4
+ //
5
+ // Two flavours:
6
+ // stftBatch — process whole signal, return Float32Array
7
+ // stftStream — write(chunk) / write() pull-based wrapper for real-time
8
+
9
+ import { fft, ifft } from 'fourier-transform'
10
+ import { hannWindow, makeStreamBufs, appendIn, growOut, compactIn, take, normFloor, PI2 } from './util.js'
11
+
12
+ export function wrapPhase(p) { return p - Math.round(p / PI2) * PI2 }
13
+
14
+ function frame(data, pos, win, half, process, state, ctx, sc) {
15
+ let N = win.length, f = sc.f
16
+ for (let i = 0; i < N; i++) f[i] = (data[pos + i] || 0) * win[i]
17
+
18
+ let [re, im] = fft(f)
19
+ let mag = sc.mag, phase = sc.phase
20
+ for (let k = 0; k <= half; k++) {
21
+ mag[k] = Math.sqrt(re[k] * re[k] + im[k] * im[k])
22
+ phase[k] = Math.atan2(im[k], re[k])
23
+ }
24
+
25
+ let r = process(mag, phase, state, ctx)
26
+ let r2 = sc.r2, i2 = sc.i2
27
+ for (let k = 0; k <= half; k++) {
28
+ r2[k] = r.mag[k] * Math.cos(r.phase[k])
29
+ i2[k] = r.mag[k] * Math.sin(r.phase[k])
30
+ }
31
+ return ifft(r2, i2)
32
+ }
33
+
34
+ function scratch(N, half) {
35
+ return {
36
+ f: new Float64Array(N),
37
+ mag: new Float64Array(half + 1),
38
+ phase: new Float64Array(half + 1),
39
+ r2: new Float64Array(half + 1),
40
+ i2: new Float64Array(half + 1)
41
+ }
42
+ }
43
+
44
+ export function stftBatch(data, process, opts) {
45
+ let N = opts?.frameSize || 2048
46
+ let hop = opts?.hopSize || (N >> 2)
47
+ let half = N >> 1
48
+ let win = hannWindow(N)
49
+ let ctx = { hop, half, N, fs: opts?.fs || 44100, freqPerBin: PI2 / N }
50
+
51
+ let outLen = data.length
52
+ let out = new Float32Array(outLen)
53
+ let norm = new Float32Array(outLen)
54
+ let state = {}
55
+ let sc = scratch(N, half)
56
+ let pos = 0
57
+
58
+ while (pos + N <= outLen + hop) {
59
+ let sf = frame(data, pos, win, half, process, state, ctx, sc)
60
+ for (let i = 0; i < N && pos + i < outLen; i++) {
61
+ out[pos + i] += sf[i] * win[i]
62
+ norm[pos + i] += win[i] * win[i]
63
+ }
64
+ pos += hop
65
+ }
66
+
67
+ let nf = normFloor(win, hop)
68
+ for (let i = 0; i < outLen; i++) {
69
+ let n = Math.max(norm[i], nf)
70
+ if (n > 1e-8) out[i] /= n
71
+ }
72
+ return out
73
+ }
74
+
75
+ export function stftStream(process, opts) {
76
+ let N = opts?.frameSize || 2048
77
+ let hop = opts?.hopSize || (N >> 2)
78
+ let half = N >> 1
79
+ let win = hannWindow(N)
80
+ let ctx = { hop, half, N, fs: opts?.fs || 44100, freqPerBin: PI2 / N }
81
+ let state = {}, sc = scratch(N, half)
82
+ let nf = normFloor(win, hop)
83
+
84
+ let st = makeStreamBufs(N, nf)
85
+ let aPos = 0, flushed = false
86
+
87
+ function run() {
88
+ while (aPos + N <= st.il) {
89
+ let sf = frame(st.ib, aPos, win, half, process, state, ctx, sc)
90
+ growOut(st, st.pos + N)
91
+ let ob = st.ob, nb = st.nb, base = st.pos
92
+ for (let i = 0; i < N; i++) {
93
+ ob[base + i] += sf[i] * win[i]
94
+ nb[base + i] += win[i] * win[i]
95
+ }
96
+ aPos += hop
97
+ st.pos += hop
98
+ }
99
+ if (aPos > N * 2) { compactIn(st, aPos - N); aPos -= aPos - N }
100
+ }
101
+
102
+ return {
103
+ write(chunk) {
104
+ appendIn(st, chunk); run()
105
+ return take(st, Math.max(0, st.pos - N + hop))
106
+ },
107
+ flush() {
108
+ if (!flushed) { appendIn(st, new Float32Array(N)); flushed = true }
109
+ run()
110
+ return take(st, st.pos)
111
+ }
112
+ }
113
+ }
114
+
115
+ // Analysis-only sweep — visit every frame's magnitude+phase but produce no output.
116
+ // Used by VAD, noise-profile estimators, dereverb late-tail estimation.
117
+ export function stftAnalyse(data, visit, opts) {
118
+ let N = opts?.frameSize || 2048
119
+ let hop = opts?.hopSize || (N >> 2)
120
+ let half = N >> 1
121
+ let win = hannWindow(N)
122
+ let f = new Float64Array(N)
123
+ let mag = new Float64Array(half + 1), phase = new Float64Array(half + 1)
124
+
125
+ for (let pos = 0; pos + N <= data.length; pos += hop) {
126
+ for (let i = 0; i < N; i++) f[i] = data[pos + i] * win[i]
127
+ let [re, im] = fft(f)
128
+ for (let k = 0; k <= half; k++) {
129
+ mag[k] = Math.sqrt(re[k] * re[k] + im[k] * im[k])
130
+ phase[k] = Math.atan2(im[k], re[k])
131
+ }
132
+ visit(mag, phase, pos)
133
+ }
134
+ }
package/util.js ADDED
@@ -0,0 +1,182 @@
1
+ // Shared helpers: window functions, dB conversions, biquad cascade, streaming buffers.
2
+
3
+ export const PI2 = Math.PI * 2
4
+
5
+ export function clamp(v, min, max) { return v < min ? min : v > max ? max : v }
6
+
7
+ export function db2lin(db) { return Math.pow(10, db / 20) }
8
+ export function lin2db(x) { return 20 * Math.log10(Math.max(x, 1e-30)) }
9
+
10
+ let _hannCache = new Map()
11
+ export function hannWindow(N) {
12
+ let w = _hannCache.get(N)
13
+ if (w) return w
14
+ w = new Float64Array(N)
15
+ for (let i = 0; i < N; i++) w[i] = 0.5 * (1 - Math.cos(PI2 * i / N))
16
+ _hannCache.set(N, w)
17
+ return w
18
+ }
19
+
20
+ let _sqrtHannCache = new Map()
21
+ export function sqrtHannWindow(N) {
22
+ let w = _sqrtHannCache.get(N)
23
+ if (w) return w
24
+ let h = hannWindow(N)
25
+ w = new Float64Array(N)
26
+ for (let i = 0; i < N; i++) w[i] = Math.sqrt(h[i])
27
+ _sqrtHannCache.set(N, w)
28
+ return w
29
+ }
30
+
31
+ // Wrap stream { write, flush } into write(chunk) → process, write() → flush
32
+ export function writer(s) { return chunk => chunk ? s.write(chunk) : s.flush() }
33
+
34
+ // Apply a single biquad section in-place, persisting state in s = [z1, z2].
35
+ export function biquad(data, b0, b1, b2, a1, a2, s) {
36
+ let z1 = s[0], z2 = s[1]
37
+ for (let i = 0, l = data.length; i < l; i++) {
38
+ let x = data[i]
39
+ let y = b0 * x + z1
40
+ z1 = b1 * x - a1 * y + z2
41
+ z2 = b2 * x - a2 * y
42
+ data[i] = y
43
+ }
44
+ s[0] = z1; s[1] = z2
45
+ }
46
+
47
+ // Cascade of biquad sections. coefs: array of {b0,b1,b2,a1,a2}. state: 2-num arrays per section.
48
+ export function biquadCascade(data, coefs, state) {
49
+ for (let i = 0; i < coefs.length; i++) {
50
+ let c = coefs[i]
51
+ biquad(data, c.b0, c.b1, c.b2, c.a1, c.a2, state[i])
52
+ }
53
+ }
54
+
55
+ // RBJ notch (peak-rejection) at fc with quality Q. Normalized a0 = 1.
56
+ export function notchCoefs(fc, Q, fs) {
57
+ let w = PI2 * fc / fs
58
+ let cw = Math.cos(w), sw = Math.sin(w)
59
+ let alpha = sw / (2 * Q)
60
+ let a0 = 1 + alpha
61
+ return {
62
+ b0: 1 / a0,
63
+ b1: -2 * cw / a0,
64
+ b2: 1 / a0,
65
+ a1: -2 * cw / a0,
66
+ a2: (1 - alpha) / a0
67
+ }
68
+ }
69
+
70
+ // RBJ high-pass at fc, Q.
71
+ export function highpassCoefs(fc, Q, fs) {
72
+ let w = PI2 * fc / fs
73
+ let cw = Math.cos(w), sw = Math.sin(w)
74
+ let alpha = sw / (2 * Q)
75
+ let a0 = 1 + alpha
76
+ return {
77
+ b0: (1 + cw) / 2 / a0,
78
+ b1: -(1 + cw) / a0,
79
+ b2: (1 + cw) / 2 / a0,
80
+ a1: -2 * cw / a0,
81
+ a2: (1 - alpha) / a0
82
+ }
83
+ }
84
+
85
+ // RBJ low-pass at fc, Q.
86
+ export function lowpassCoefs(fc, Q, fs) {
87
+ let w = PI2 * fc / fs
88
+ let cw = Math.cos(w), sw = Math.sin(w)
89
+ let alpha = sw / (2 * Q)
90
+ let a0 = 1 + alpha
91
+ return {
92
+ b0: (1 - cw) / 2 / a0,
93
+ b1: (1 - cw) / a0,
94
+ b2: (1 - cw) / 2 / a0,
95
+ a1: -2 * cw / a0,
96
+ a2: (1 - alpha) / a0
97
+ }
98
+ }
99
+
100
+ // RBJ peaking EQ at fc, Q, gain in dB.
101
+ export function peakingCoefs(fc, Q, gainDb, fs) {
102
+ let A = Math.pow(10, gainDb / 40)
103
+ let w = PI2 * fc / fs
104
+ let cw = Math.cos(w), sw = Math.sin(w)
105
+ let alpha = sw / (2 * Q)
106
+ let a0 = 1 + alpha / A
107
+ return {
108
+ b0: (1 + alpha * A) / a0,
109
+ b1: -2 * cw / a0,
110
+ b2: (1 - alpha * A) / a0,
111
+ a1: -2 * cw / a0,
112
+ a2: (1 - alpha / A) / a0
113
+ }
114
+ }
115
+
116
+ // Streaming buffer state: input ring (grow-on-demand), output OLA buffer + norm buffer.
117
+ // Plain data + free functions — no accessors/closures, stays in the jz subset.
118
+ export function makeStreamBufs(N, nf = 0) {
119
+ return {
120
+ N, nf,
121
+ ib: new Float32Array(N * 4), il: 0,
122
+ ob: new Float32Array(N * 8), nb: new Float32Array(N * 8),
123
+ pos: 0, oread: 0
124
+ }
125
+ }
126
+
127
+ export function appendIn(st, chunk) {
128
+ let need = st.il + chunk.length
129
+ if (need > st.ib.length) {
130
+ let b = new Float32Array(Math.max(need * 2, st.ib.length * 2))
131
+ b.set(st.ib.subarray(0, st.il)); st.ib = b
132
+ }
133
+ st.ib.set(chunk, st.il); st.il += chunk.length
134
+ }
135
+
136
+ export function growOut(st, need) {
137
+ if (need <= st.ob.length) return
138
+ let len = Math.max(need * 2, st.ob.length * 2)
139
+ let o = new Float32Array(len), n = new Float32Array(len)
140
+ o.set(st.ob); n.set(st.nb); st.ob = o; st.nb = n
141
+ }
142
+
143
+ export function compactIn(st, trim) {
144
+ if (trim <= 0) return
145
+ st.ib.copyWithin(0, trim, st.il); st.il -= trim
146
+ }
147
+
148
+ export function take(st, upTo) {
149
+ upTo = Math.min(upTo, st.pos)
150
+ if (upTo <= st.oread) return new Float32Array(0)
151
+ let len = Math.floor(upTo - st.oread)
152
+ let out = new Float32Array(len)
153
+ for (let i = 0; i < len; i++) {
154
+ let j = st.oread + i, n = st.nf > 0 ? Math.max(st.nb[j], st.nf) : st.nb[j]
155
+ out[i] = n > 1e-8 ? st.ob[j] / n : 0
156
+ }
157
+ st.oread += len
158
+ if (st.oread > st.N * 8) {
159
+ st.ob.copyWithin(0, st.oread); st.nb.copyWithin(0, st.oread)
160
+ st.pos -= st.oread; st.oread = 0
161
+ st.ob.fill(0, st.pos); st.nb.fill(0, st.pos)
162
+ }
163
+ return out
164
+ }
165
+
166
+ // Steady-state win² sum — floor prevents amplification at OLA boundaries.
167
+ export function normFloor(win, hop) {
168
+ let N = win.length, min = Infinity
169
+ for (let i = 0; i < hop; i++) {
170
+ let s = 0
171
+ for (let j = i; j < N; j += hop) s += win[j] * win[j]
172
+ if (s > 0 && s < min) min = s
173
+ }
174
+ return min === Infinity ? 0 : min
175
+ }
176
+
177
+ // In-place RMS (per chunk).
178
+ export function rms(data) {
179
+ let s = 0
180
+ for (let i = 0; i < data.length; i++) s += data[i] * data[i]
181
+ return Math.sqrt(s / data.length)
182
+ }
package/vad.js ADDED
@@ -0,0 +1,91 @@
1
+ // Voice Activity Detection + Speech Presence Probability.
2
+ // - vad: hard 0/1 decision per frame from energy + spectral flatness + ZCR
3
+ // - spp: soft probability per bin from a-priori SNR (drives OM-LSA, IMCRA)
4
+ //
5
+ // Use vad() for gating decisions (debreath, gate); spp() for spectral denoise gain.
6
+
7
+ import { stftAnalyse } from './stft.js'
8
+ import { lin2db } from './util.js'
9
+
10
+ // Returns { active: Uint8Array(frames), times: Float32Array(frames) of frame-start sec }.
11
+ // Active iff energy is N dB above the rolling noise floor AND spectral flatness < flatTh.
12
+ //
13
+ // Floor estimation: minimum of energy over a sliding D-frame window with bias
14
+ // correction — Martin-style minimum tracking. This avoids the "speech eats its own
15
+ // floor" failure mode of plain exponential smoothing.
16
+ //
17
+ // flatTh ≈ 0.4 — speech is tonal (low flatness), noise is flat (high flatness).
18
+ export function vad(data, opts = {}) {
19
+ let N = opts.frameSize || 1024
20
+ let hop = opts.hopSize || (N >> 1)
21
+ let fs = opts.fs || 44100
22
+ let snrTh = opts.snrTh ?? 6 // dB above floor
23
+ let flatTh = opts.flatTh ?? 0.4 // spectral flatness threshold
24
+ let D = opts.window || 64 // frames in min-tracker window
25
+ let bias = opts.bias ?? 5 // dB — added to min to estimate true floor
26
+
27
+ let frames = Math.max(0, Math.floor((data.length - N) / hop) + 1)
28
+ let active = new Uint8Array(frames)
29
+ let times = new Float32Array(frames)
30
+ let energies = new Float64Array(frames)
31
+ let flats = new Float64Array(frames)
32
+ let i = 0
33
+
34
+ stftAnalyse(data, (mag, _phase, pos) => {
35
+ let half = mag.length - 1, e = 0
36
+ let logSum = 0, linSum = 0, nz = 0
37
+ for (let k = 1; k <= half; k++) {
38
+ let p = mag[k] * mag[k]
39
+ e += p
40
+ if (p > 1e-30) { logSum += Math.log(p); nz++ }
41
+ linSum += p
42
+ }
43
+ let geom = nz ? Math.exp(logSum / nz) : 0
44
+ let arith = linSum / Math.max(half, 1)
45
+ flats[i] = arith > 1e-30 ? geom / arith : 1
46
+ energies[i] = lin2db(Math.sqrt(e / N))
47
+ times[i] = pos / fs
48
+ i++
49
+ }, { frameSize: N, hopSize: hop })
50
+
51
+ // Global noise floor = 10th-percentile energy + bias. Robust on signals where
52
+ // any short window may be entirely speech.
53
+ let sorted = Float64Array.from(energies).sort()
54
+ let floor = sorted[Math.floor(sorted.length * 0.1)] + bias
55
+
56
+ for (let j = 0; j < frames; j++) {
57
+ active[j] = (energies[j] - floor > snrTh && flats[j] < flatTh) ? 1 : 0
58
+ }
59
+ return { active, times, hop, frameSize: N }
60
+ }
61
+
62
+ // Per-bin Speech Presence Probability from a-priori SNR ξ:
63
+ // p = ξ / (1 + ξ) (Bayesian formulation under Gaussian model, q-prior = 0.5)
64
+ // Bind to a noise PSD source (e.g. minStats.psd or imcra.psd) and an a-priori SNR estimate.
65
+ export function spp(mag, noisePsd, opts = {}) {
66
+ let xiMin = opts.xiMin ?? 0.0316 // -15 dB floor
67
+ let half = mag.length - 1
68
+ let p = new Float64Array(half + 1)
69
+ for (let k = 0; k <= half; k++) {
70
+ let post = (mag[k] * mag[k]) / Math.max(noisePsd[k], 1e-30) - 1
71
+ let xi = Math.max(xiMin, post)
72
+ p[k] = xi / (1 + xi)
73
+ }
74
+ return p
75
+ }
76
+
77
+ // Decision-Directed a-priori SNR (Ephraim-Malah 1984), recursive smoothing.
78
+ // ξ̂[k] = α · |X̂_prev[k]|² / N̂[k] + (1-α) · max(γ-1, 0)
79
+ // γ = posterior SNR = |Y[k]|² / N̂[k]. Used by Wiener, MMSE, OM-LSA gain rules.
80
+ export function ddSnr(mag, noisePsd, prevGain, prevMag, alpha = 0.98) {
81
+ let half = mag.length - 1
82
+ let xi = new Float64Array(half + 1)
83
+ for (let k = 0; k <= half; k++) {
84
+ let n = Math.max(noisePsd[k], 1e-30)
85
+ let post = (mag[k] * mag[k]) / n
86
+ let g = prevGain[k] * prevMag[k]
87
+ let prev = (g * g) / n
88
+ xi[k] = Math.max(0.0316, alpha * prev + (1 - alpha) * Math.max(post - 1, 0))
89
+ }
90
+ return xi
91
+ }