FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
M7.7: audio-dsp: Premiere audio effect set (EQs, scientific/FFT filters, dynamics, multiband, modulation, delays, convolution/surround reverb, click remover, special/stereo)
Brandon Thomas9ef525441ab1
diff --git a/Cargo.toml b/Cargo.tomlindex fa73ed112..aa6515074 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -99,6 +99,10 @@ opt-level = 3[profile.dev.package.filmcraft-aac]opt-level = 3+# Audio effects: realtime-factor tests and long convolution / spectral runs.+[profile.dev.package.filmcraft-audio-dsp]+opt-level = 3+[profile.dev.package.filmcraft-opus]opt-level = 3diff --git a/crates/audio-dsp/README.md b/crates/audio-dsp/README.mdindex c86d548d1..886baccc5 100644--- a/crates/audio-dsp/README.md+++ b/crates/audio-dsp/README.md@@ -55,6 +55,37 @@ id, name, range, default, `Unit`, log-scale hint and choice labels so UIs can be| `dereverb` | STFT late-reverb suppression: λ_r(t) = e^{−2Δ·T_d}·λ_x(t − T_d) (Δ = 3 ln10 / `rt60`, T_d ≈ 50 ms), over-subtraction 1 + `amount`, gain floor down to −18 dB, smoothed gains (latency = FFT size) || `speech_enhance` | Enhance Speech DSP chain: 80 Hz HPF, de-mud cut (250 / 350 Hz −3 dB), presence (2.5 / 4 kHz +4 dB) and air (+2 dB @ 10 kHz) boosts by `tone`, downward expander below −50 dBFS (3:1, ≤ 18 dB), 3:1 soft-knee compressor above −24 dBFS, +3 dB make-up, `mix` || `stereo_width` | mid/side width 0–200 % (100 % = identity, 0 % = mono) |+| `graphic_eq_10/20/30` | constant-Q peaking bands at octave / half-octave / third-octave ISO centres (Q from the bandwidth), ±24 dB, master gain |+| `parametric_eq_full` | Premiere's Parametric Equalizer: master gain, high-pass and low-pass (12–48 dB/oct Butterworth cascades), low shelf, 5 peaking bands, high shelf |+| `notch_filter` | 6 constant-bandwidth cuts (`FilterType::Cut` = 1 + (g − 1)·BP: the width stays f/Q however deep), Narrow / Very Narrow / Super Narrow |+| `scientific_filter` | Bessel / Butterworth / Chebyshev I / elliptic, LP / HP / BP / BS, order 1–12 (`design`: analog prototype → frequency transform at pre-warped edges → bilinear → biquads; elliptic via Landen-transformation Jacobi functions after Orfanidis) |+| `fft_filter` | 8-point gain curve (log-frequency, linear or smoothstep), applied zero-phase by √Hann STFT at 75 % overlap (latency = FFT size) |+| `dynamics_rack` | Dynamics: auto gate (hold) → expander → compressor (auto make-up) → limiter (soft clip), stereo-linked; `transfer_db` gives the static curve |+| `multiband_compressor` | 4 bands with LR4 crossovers and all-pass phase compensation (bands sum to an all-pass: flat magnitude), per-band threshold/ratio/attack/release/gain/solo/bypass, output limiter, channel link |+| `tube_compressor` | RMS detector, 10 dB soft knee, program-dependent release, gentle `tanh(x/2)·2` saturation |+| `chorus_flanger` | chorus (3 voices, 15–35 ms) or flanger (0.3–5 ms, feedback), transience emphasis, mix |+| `flanger` | initial/final delay sweep, stereo phasing, ±feedback, inverted / special / sinusoidal modes |+| `phaser` | 2–12 swept first-order all-passes, depth (octaves below the upper frequency), feedback, stereo phase difference |+| `analog_delay` | Tape / Tape+Tube / Analog: low-passed, saturating feedback (bounded up to 200 %), trash, stereo spread |+| `multitap_delay` | 4 independent feedback taps, levels, mix |+| `convolution_reverb` | uniformly partitioned overlap-save convolution (256-sample partitions, latency 256) with 7 impulses generated here (noise with frequency-dependent exponential decay + early reflections, unit energy); room size (resampling), LF/HF damping, pre-delay, width |+| `surround_reverb` | early reflections + FDN late field, centre input, low/high cut, width, dry/wet (stereo rendering) |+| `click_remover` | LPC residual outlier detection (k·σ, σ from the median), AR forward/backward interpolation of ≤ 64-sample regions (latency 640) |+| `channel_mixer`, `stereo_expander`, `mute` | 2×2 matrix with inversion; mid/side expand + centre pan; ramped mute |+| `distortion`, `guitar_suite` | waveshaper (soft/hard/tube/foldback, asymmetry, tone); compressor → distortion → amp/cabinet voicing → filter |+| `mastering`, `vocal_enhancer` | EQ → reverb → exciter → widener → loudness maximiser (transparent at defaults); fixed Male/Female/Music voicings |+| `binauralizer` | ±angle virtual speakers through a spherical-head model (Woodworth ITD + Brown–Duda head shadow) |+| `ambisonics_panner` | rotates a ±30° source pair (pan/tilt/roll) and re-pans to stereo; identity at 0/0/0 |+| `loudness_meter` | pass-through BS.1770 meter (`LoudnessMeterFx::meter`) |++`AudioEffect::response_db(freq)` (EQs and filters) and `transfer_db(band, input_db)` (dynamics)+expose the analytic curves for the graphical effect editors. Modulation effects start their LFO+at the beginning of a chain, so a random-access render may differ in LFO phase from continuous+playback.++`effects::premiere_tests` checks every effect: neutral settings are (delayed) identity, output is+deterministic and latency constant (impulse lands at `latency()`), plus a level / frequency-response+test on generated tones, noise or impulses and a realtime-factor floor.Essential Sound builds on these (Repair: `denoise`, high-pass via `parametric_eq`, `dehum`,`deesser`, `dereverb`; Clarity: `compressor`, `simple_eq`, `speech_enhance`; Creative: `reverb`,diff --git a/crates/audio-dsp/src/biquad.rs b/crates/audio-dsp/src/biquad.rsindex b213d7b9f..55f0403ad 100644--- a/crates/audio-dsp/src/biquad.rs+++ b/crates/audio-dsp/src/biquad.rs@@ -14,6 +14,10 @@ pub enum FilterType {Notch,BandPass,AllPass,+ /// Constant-bandwidth cut: `1 + (g − 1)·BP(s)` — the −3 dB width of the band-pass stays+ /// `f/Q` however deep the cut (`gain_db` ≤ 0), unlike the RBJ peaking filter whose cut+ /// widens with depth. Used by the Notch Filter.+ Cut,}impl FilterType {@@ -58,6 +62,10 @@ impl Coeffs {FilterType::BandPass => Self::norm(alpha, 0.0, -alpha, 1.0 + alpha, -2.0 * cs, 1.0 - alpha),FilterType::Notch => Self::norm(1.0, -2.0 * cs, 1.0, 1.0 + alpha, -2.0 * cs, 1.0 - alpha),FilterType::AllPass => Self::norm(1.0 - alpha, -2.0 * cs, 1.0 + alpha, 1.0 + alpha, -2.0 * cs, 1.0 - alpha),+ FilterType::Cut => {+ let g = 10f64.powf(gain_db / 20.0);+ Self::norm(1.0 + g * alpha, -2.0 * cs, 1.0 - g * alpha, 1.0 + alpha, -2.0 * cs, 1.0 - alpha)+ }FilterType::Peaking => Self::norm(1.0 + alpha * a, -2.0 * cs, 1.0 - alpha * a, 1.0 + alpha / a, -2.0 * cs, 1.0 - alpha / a),FilterType::LowShelf => {let k = 2.0 * a.sqrt() * alpha;diff --git a/crates/audio-dsp/src/design.rs b/crates/audio-dsp/src/design.rsnew file mode 100644index 000000000..474be72b4--- /dev/null+++ b/crates/audio-dsp/src/design.rs@@ -0,0 +1,757 @@+//! IIR filter design from classical analog prototypes (Scientific Filter).+//!+//! Textbook method: a normalised low-pass prototype (zeros, poles, gain) — Butterworth, Bessel+//! (roots of the reverse Bessel polynomial, normalised to −3 dB at Ω = 1), Chebyshev type I and+//! elliptic (Cauer; Landen-transformation formulation of the Jacobi elliptic functions, after+//! S. J. Orfanidis, *Lecture Notes on Elliptic Filter Design*, 2006) — is transformed to+//! low-pass / high-pass / band-pass / band-stop at pre-warped analog frequencies, mapped to+//! the z-plane with the bilinear transform and factored into second-order sections.+//!+//! Everything works on fixed-size arrays so a design never allocates (it runs from+//! `set_param` on the audio thread).++use crate::biquad::Coeffs;+use std::f64::consts::PI;+use std::ops::{Add, Div, Mul, Neg, Sub};++/// Highest prototype order.+pub const MAX_ORDER: usize = 12;+/// Most second-order sections a design produces (band-pass/stop double the order).+pub const MAX_SECTIONS: usize = MAX_ORDER;+const MAX_ROOTS: usize = 2 * MAX_ORDER;++/// Minimal complex number.+#[derive(Clone, Copy, Debug, Default, PartialEq)]+pub struct C {+ pub re: f64,+ pub im: f64,+}++impl C {+ pub const fn new(re: f64, im: f64) -> C {+ C { re, im }+ }+ pub const fn real(re: f64) -> C {+ C { re, im: 0.0 }+ }+ pub fn scale(self, s: f64) -> C {+ C::new(self.re * s, self.im * s)+ }+ pub fn conj(self) -> C {+ C::new(self.re, -self.im)+ }+ pub fn abs(self) -> f64 {+ self.re.hypot(self.im)+ }+ pub fn sqrt(self) -> C {+ let r = self.abs();+ let re = ((r + self.re) * 0.5).max(0.0).sqrt();+ let im = ((r - self.re) * 0.5).max(0.0).sqrt();+ C::new(re, if self.im < 0.0 { -im } else { im })+ }+ pub fn exp(self) -> C {+ let e = self.re.exp();+ C::new(e * self.im.cos(), e * self.im.sin())+ }+ pub fn ln(self) -> C {+ C::new(self.abs().ln(), self.im.atan2(self.re))+ }+ pub fn cos(self) -> C {+ C::new(self.re.cos() * self.im.cosh(), -self.re.sin() * self.im.sinh())+ }+ pub fn sin(self) -> C {+ C::new(self.re.sin() * self.im.cosh(), self.re.cos() * self.im.sinh())+ }+ /// acos(w) = −j·ln(w + j·√(1 − w²)).+ pub fn acos(self) -> C {+ let one = C::real(1.0);+ let s = one.sub(self.mul(self)).sqrt();+ let v = self.add(C::new(-s.im, s.re)).ln();+ C::new(v.im, -v.re)+ }+}++impl Add for C {+ type Output = C;+ fn add(self, o: C) -> C {+ C::new(self.re + o.re, self.im + o.im)+ }+}++impl Sub for C {+ type Output = C;+ fn sub(self, o: C) -> C {+ C::new(self.re - o.re, self.im - o.im)+ }+}++impl Mul for C {+ type Output = C;+ fn mul(self, o: C) -> C {+ C::new(self.re * o.re - self.im * o.im, self.re * o.im + self.im * o.re)+ }+}++impl Div for C {+ type Output = C;+ fn div(self, o: C) -> C {+ let d = o.re * o.re + o.im * o.im;+ C::new((self.re * o.re + self.im * o.im) / d, (self.im * o.re - self.re * o.im) / d)+ }+}++impl Neg for C {+ type Output = C;+ fn neg(self) -> C {+ C::new(-self.re, -self.im)+ }+}++/// Fixed-capacity root list.+#[derive(Clone, Copy, Debug)]+struct Roots {+ v: [C; MAX_ROOTS],+ n: usize,+}++impl Roots {+ const fn new() -> Roots {+ Roots { v: [C { re: 0.0, im: 0.0 }; MAX_ROOTS], n: 0 }+ }+ fn push(&mut self, c: C) {+ if self.n < MAX_ROOTS {+ self.v[self.n] = c;+ self.n += 1;+ }+ }+ fn as_slice(&self) -> &[C] {+ &self.v[..self.n]+ }+ fn prod_neg(&self) -> C {+ self.as_slice().iter().fold(C::real(1.0), |a, &r| a.mul(r.neg()))+ }+}++/// Analog zeros/poles/gain.+#[derive(Clone, Copy, Debug)]+struct Zpk {+ z: Roots,+ p: Roots,+ k: f64,+}++/// Prototype family.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Family {+ Bessel,+ Butterworth,+ Chebyshev,+ Elliptic,+}++/// Response type.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Band {+ LowPass,+ HighPass,+ BandPass,+ BandStop,+}++/// A cascade of second-order sections.+#[derive(Clone, Copy, Debug)]+pub struct Sections {+ pub c: [Coeffs; MAX_SECTIONS],+ pub n: usize,+}++impl Sections {+ pub fn as_slice(&self) -> &[Coeffs] {+ &self.c[..self.n]+ }+ /// Magnitude of the cascade in dB.+ pub fn magnitude_db(&self, freq: f64, sample_rate: f64) -> f64 {+ self.as_slice().iter().map(|c| c.magnitude_db(freq, sample_rate)).sum()+ }+}++// ------------------------------------------------------------------------------- prototypes++fn butterworth(n: usize) -> Zpk {+ let mut p = Roots::new();+ for k in 0..n {+ let a = PI * (2 * k + n + 1) as f64 / (2 * n) as f64;+ p.push(C::new(a.cos(), a.sin()));+ }+ Zpk { z: Roots::new(), p, k: 1.0 }+}++fn chebyshev1(n: usize, rp: f64) -> Zpk {+ let eps = (10f64.powf(rp / 10.0) - 1.0).sqrt();+ let mu = (1.0 / eps).asinh() / n as f64;+ let mut p = Roots::new();+ for k in 0..n {+ let th = PI * (2 * k + 1) as f64 / (2 * n) as f64;+ p.push(C::new(-mu.sinh() * th.sin(), mu.cosh() * th.cos()));+ }+ let mut k = p.prod_neg().re;+ if n.is_multiple_of(2) {+ k /= (1.0 + eps * eps).sqrt();+ }+ Zpk { z: Roots::new(), p, k }+}++/// Roots of a monic polynomial (`c[i]` = coefficient of sⁱ, `c[n]` = 1) by Durand–Kerner.+fn poly_roots(c: &[f64], out: &mut Roots) {+ let n = c.len() - 1;+ let eval = |s: C| -> C {+ let mut acc = C::real(c[n]);+ for i in (0..n).rev() {+ acc = acc.mul(s).add(C::real(c[i]));+ }+ acc+ };+ // Initial guesses on a circle of the Cauchy-bound radius.+ let radius = 1.0 + c[..n].iter().fold(0.0f64, |m, v| m.max(v.abs())).powf(1.0 / n as f64);+ let mut r = [C::default(); MAX_ROOTS];+ for (i, ri) in r.iter_mut().enumerate().take(n) {+ let a = 2.0 * PI * i as f64 / n as f64 + 0.4;+ *ri = C::new(radius * a.cos(), radius * a.sin());+ }+ for _ in 0..500 {+ let mut delta = 0.0f64;+ for i in 0..n {+ let mut den = C::real(1.0);+ for j in 0..n {+ if j != i {+ den = den.mul(r[i].sub(r[j]));+ }+ }+ let step = eval(r[i]).div(den);+ r[i] = r[i].sub(step);+ delta = delta.max(step.abs());+ }+ if delta < 1e-14 {+ break;+ }+ }+ out.n = 0;+ for &ri in r.iter().take(n) {+ out.push(ri);+ }+}++fn bessel(n: usize) -> Zpk {+ // Reverse Bessel polynomial: a_k = (2n − k)! / (2^(n−k) k! (n − k)!), monic (a_n = 1).+ let mut c = [0.0f64; MAX_ORDER + 1];+ let fact = |m: usize| -> f64 { (1..=m).fold(1.0, |a, v| a * v as f64) };+ for (k, ck) in c.iter_mut().enumerate().take(n + 1) {+ *ck = fact(2 * n - k) / (2f64.powi((n - k) as i32) * fact(k) * fact(n - k));+ }+ let mut p = Roots::new();+ poly_roots(&c[..=n], &mut p);+ // H(s) = a0 / θ(s); find Ω where |H(jΩ)| = 1/√2 and normalise it to 1.+ let a0 = c[0];+ let mag = |w: f64| -> f64 {+ let s = C::new(0.0, w);+ p.as_slice().iter().fold(C::real(1.0), |acc, &r| acc.mul(s.sub(r))).abs().recip() * a0+ };+ let (mut lo, mut hi) = (1e-3f64, 100.0f64);+ for _ in 0..200 {+ let mid = (lo * hi).sqrt();+ if mag(mid) > std::f64::consts::FRAC_1_SQRT_2 { lo = mid } else { hi = mid }+ }+ let w3 = (lo * hi).sqrt();+ for r in &mut p.v[..p.n] {+ *r = r.scale(1.0 / w3);+ }+ let k = p.prod_neg().re;+ Zpk { z: Roots::new(), p, k }+}++// ---- Jacobi elliptic functions via Landen transformations (normalised argument u·K).++const LANDEN_STEPS: usize = 10;++/// Descending Landen sequence of moduli.+fn landen(k: f64) -> ([f64; LANDEN_STEPS], usize) {+ let mut v = [0.0; LANDEN_STEPS];+ let mut n = 0;+ let mut k = k;+ while n < LANDEN_STEPS && k > 1e-16 {+ k = (k / (1.0 + (1.0 - k * k).max(0.0).sqrt())).powi(2);+ v[n] = k;+ n += 1;+ }+ (v, n)+}++/// Complete elliptic integral K(k).+#[cfg(test)]+fn ellip_k(k: f64) -> f64 {+ if k >= 1.0 {+ return f64::INFINITY;+ }+ let (v, n) = landen(k);+ v[..n].iter().fold(PI / 2.0, |a, &vi| a * (1.0 + vi))+}++/// cd(u·K, k) for complex normalised u.+fn cde(u: C, k: f64) -> C {+ let (v, n) = landen(k);+ let mut w = u.scale(PI / 2.0).cos();+ for &vi in v[..n].iter().rev() {+ w = w.scale(1.0 + vi).div(C::real(1.0).add(w.mul(w).scale(vi)));+ }+ w+}++/// sn(u·K, k) for complex normalised u.+fn sne(u: C, k: f64) -> C {+ let (v, n) = landen(k);+ let mut w = u.scale(PI / 2.0).sin();+ for &vi in v[..n].iter().rev() {+ w = w.scale(1.0 + vi).div(C::real(1.0).add(w.mul(w).scale(vi)));+ }+ w+}++/// Inverse of [`cde`]: normalised u with cd(u·K, k) = w.+fn acde(w: C, k: f64) -> C {+ let (v, n) = landen(k);+ let mut w = w;+ for i in 0..n {+ let v1 = if i == 0 { k } else { v[i - 1] };+ let s = C::real(1.0).sub(w.mul(w).scale(v1 * v1)).sqrt();+ w = w.div(C::real(1.0).add(s)).scale(2.0 / (1.0 + v[i]));+ }+ w.acos().scale(2.0 / PI)+}++/// Inverse of [`sne`]: sn(uK) = cd((1 − u)K).+fn asne(w: C, k: f64) -> C {+ C::real(1.0).sub(acde(w, k))+}++fn elliptic(n: usize, rp: f64, rs: f64) -> Zpk {+ let ep = (10f64.powf(rp / 10.0) - 1.0).sqrt();+ let es = (10f64.powf(rs / 10.0) - 1.0).sqrt();+ let k1 = ep / es;+ let k1p = (1.0 - k1 * k1).sqrt();+ let l = n / 2;+ // Degree equation: k' = k1'^N · Π sn⁴(u_i K', k1').+ let mut kp = k1p.powi(n as i32);+ for i in 1..=l {+ let ui = (2 * i - 1) as f64 / n as f64;+ kp *= sne(C::real(ui), k1p).re.powi(4);+ }+ let k = (1.0 - kp * kp).max(0.0).sqrt();+ // v0 = −j·asn(j/εp, k1) / N (normalised).+ let a = asne(C::new(0.0, 1.0 / ep), k1);+ let v0 = C::new(a.im, -a.re).scale(1.0 / n as f64); // −j·a/N+ let mut z = Roots::new();+ let mut p = Roots::new();+ for i in 1..=l {+ let ui = (2 * i - 1) as f64 / n as f64;+ let zeta = cde(C::real(ui), k);+ let zi = C::new(0.0, 1.0).div(zeta.scale(k));+ z.push(zi);+ z.push(zi.conj());+ // p_i = j·cd((u_i − j v0)K, k)+ let arg = C::real(ui).sub(C::new(0.0, 1.0).mul(v0));+ let c = cde(arg, k);+ let pi = C::new(-c.im, c.re);+ p.push(pi);+ p.push(pi.conj());+ }+ if n % 2 == 1 {+ // p0 = j·sn(j v0 K, k)+ let s = sne(C::new(0.0, 1.0).mul(v0), k);+ p.push(C::new(-s.im, s.re));+ // the result is real (negative); drop the numerical imaginary residue+ let last = p.n - 1;+ p.v[last].im = 0.0;+ p.v[last].re = -p.v[last].re.abs();+ }+ // Make sure all poles are in the left half plane.+ for r in &mut p.v[..p.n] {+ if r.re > 0.0 {+ r.re = -r.re;+ }+ }+ // Gain: H(0) = 1 (odd N) or 1/√(1+εp²) (even N).+ let h0 = if n % 2 == 1 { 1.0 } else { 1.0 / (1.0 + ep * ep).sqrt() };+ let num = z.prod_neg();+ let den = p.prod_neg();+ let k = h0 * den.div(num).re;+ Zpk { z, p, k }+}++// ---------------------------------------------------------------------------- transforms++fn lp_to_lp(f: &mut Zpk, wc: f64) {+ for r in &mut f.z.v[..f.z.n] {+ *r = r.scale(wc);+ }+ for r in &mut f.p.v[..f.p.n] {+ *r = r.scale(wc);+ }+ f.k *= wc.powi((f.p.n - f.z.n) as i32);+}++fn lp_to_hp(f: &mut Zpk, wc: f64) {+ let ratio = f.z.prod_neg().div(f.p.prod_neg()).re;+ let degree = f.p.n - f.z.n;+ for r in &mut f.z.v[..f.z.n] {+ *r = C::real(wc).div(*r);+ }+ for r in &mut f.p.v[..f.p.n] {+ *r = C::real(wc).div(*r);+ }+ for _ in 0..degree {+ f.z.push(C::real(0.0));+ }+ f.k *= ratio;+}++fn lp_to_bp(f: &mut Zpk, w0: f64, bw: f64) {+ let degree = f.p.n - f.z.n;+ let map = |src: &Roots| -> Roots {+ let mut out = Roots::new();+ for &r in src.as_slice() {+ let a = r.scale(bw / 2.0);+ let d = a.mul(a).sub(C::real(w0 * w0)).sqrt();+ out.push(a.add(d));+ out.push(a.sub(d));+ }+ out+ };+ f.z = map(&f.z);+ f.p = map(&f.p);+ for _ in 0..degree {+ f.z.push(C::real(0.0));+ }+ f.k *= bw.powi(degree as i32);+}++fn lp_to_bs(f: &mut Zpk, w0: f64, bw: f64) {+ let degree = f.p.n - f.z.n;+ let ratio = f.z.prod_neg().div(f.p.prod_neg()).re;+ let map = |src: &Roots| -> Roots {+ let mut out = Roots::new();+ for &r in src.as_slice() {+ let a = C::real(bw / 2.0).div(r);+ let d = a.mul(a).sub(C::real(w0 * w0)).sqrt();+ out.push(a.add(d));+ out.push(a.sub(d));+ }+ out+ };+ f.z = map(&f.z);+ f.p = map(&f.p);+ for _ in 0..degree {+ f.z.push(C::new(0.0, w0));+ f.z.push(C::new(0.0, -w0));+ }+ f.k *= ratio;+}++fn bilinear(f: &mut Zpk, fs: f64) {+ let fs2 = 2.0 * fs;+ let degree = f.p.n - f.z.n;+ let num = f.z.as_slice().iter().fold(C::real(1.0), |a, &r| a.mul(C::real(fs2).sub(r)));+ let den = f.p.as_slice().iter().fold(C::real(1.0), |a, &r| a.mul(C::real(fs2).sub(r)));+ for r in &mut f.z.v[..f.z.n] {+ *r = C::real(fs2).add(*r).div(C::real(fs2).sub(*r));+ }+ for r in &mut f.p.v[..f.p.n] {+ *r = C::real(fs2).add(*r).div(C::real(fs2).sub(*r));+ }+ for _ in 0..degree {+ f.z.push(C::real(-1.0));+ }+ f.k *= num.div(den).re;+}++// ------------------------------------------------------------------------ factorisation++const REAL_EPS: f64 = 1e-7;++/// Split roots into conjugate pairs (upper half plane members) and real roots.+fn split(r: &Roots) -> (Roots, Roots) {+ let mut pairs = Roots::new();+ let mut reals = Roots::new();+ for &x in r.as_slice() {+ if x.im.abs() <= REAL_EPS * (1.0 + x.abs()) {+ reals.push(C::real(x.re));+ } else if x.im > 0.0 {+ pairs.push(x);+ }+ }+ (pairs, reals)+}++fn take(r: &mut Roots, i: usize) -> C {+ let v = r.v[i];+ r.v[i] = r.v[r.n - 1];+ r.n -= 1;+ v+}++fn closest(r: &Roots, to: C) -> Option<usize> {+ (0..r.n).min_by(|&a, &b| r.v[a].sub(to).abs().total_cmp(&r.v[b].sub(to).abs()))+}++fn take_closest(r: &mut Roots, to: C) -> C {+ let i = closest(r, to).unwrap_or(0);+ take(r, i)+}++fn into_sections(f: &Zpk) -> Sections {+ let (mut pp, mut pr) = split(&f.p);+ let (mut zp, mut zr) = split(&f.z);+ let mut out = Sections { c: [Coeffs::IDENTITY; MAX_SECTIONS], n: 0 };+ let mut push = |b: [f64; 3], a: [f64; 2]| {+ if out.n < MAX_SECTIONS {+ out.c[out.n] = Coeffs { b0: b[0], b1: b[1], b2: b[2], a1: a[0], a2: a[1] };+ out.n += 1;+ }+ };+ // An odd real pole first (it needs a single real zero).+ if pr.n % 2 == 1 {+ let i = (0..pr.n).max_by(|&a, &b| pr.v[a].re.abs().total_cmp(&pr.v[b].re.abs())).unwrap_or(0);+ let p = take(&mut pr, i);+ let b = match closest(&zr, p) {+ Some(j) => {+ let z = take(&mut zr, j);+ [1.0, -z.re, 0.0]+ }+ None => [1.0, 0.0, 0.0],+ };+ push(b, [-p.re, 0.0]);+ }+ // Second-order sections, highest-Q (closest to the unit circle) first.+ loop {+ let pole_pair = if pp.n > 0 {+ let i = (0..pp.n).max_by(|&a, &b| pp.v[a].abs().total_cmp(&pp.v[b].abs())).unwrap_or(0);+ let p = take(&mut pp, i);+ Some([-2.0 * p.re, p.re * p.re + p.im * p.im, p.re, p.im])+ } else if pr.n >= 2 {+ let p1 = take(&mut pr, 0);+ let p2 = take(&mut pr, 0);+ Some([-(p1.re + p2.re), p1.re * p2.re, (p1.re + p2.re) / 2.0, 0.0])+ } else {+ None+ };+ let Some([a1, a2, cre, cim]) = pole_pair else { break };+ let centre = C::new(cre, cim);+ // Zeros: best complex pair, else two reals, else none.+ let b = if let Some(j) = closest(&zp, centre) {+ let use_pair = zr.n < 2 || zp.v[j].sub(centre).abs() <= closest(&zr, centre).map_or(f64::INFINITY, |k| zr.v[k].sub(centre).abs());+ if use_pair {+ let z = take(&mut zp, j);+ [1.0, -2.0 * z.re, z.re * z.re + z.im * z.im]+ } else {+ let z1 = take_closest(&mut zr, centre);+ let z2 = take_closest(&mut zr, centre);+ [1.0, -(z1.re + z2.re), z1.re * z2.re]+ }+ } else if zr.n >= 2 {+ let z1 = take_closest(&mut zr, centre);+ let z2 = take_closest(&mut zr, centre);+ [1.0, -(z1.re + z2.re), z1.re * z2.re]+ } else if zr.n == 1 {+ let z1 = take(&mut zr, 0);+ [1.0, -z1.re, 0.0]+ } else {+ [1.0, 0.0, 0.0]+ };+ push(b, [a1, a2]);+ }+ // Overall gain on the first section.+ if out.n > 0 {+ out.c[0].b0 *= f.k;+ out.c[0].b1 *= f.k;+ out.c[0].b2 *= f.k;+ }+ out+}++/// Design parameters.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Spec {+ pub family: Family,+ pub band: Band,+ /// Prototype order (1..=[`MAX_ORDER`]).+ pub order: usize,+ /// Low-pass / high-pass edge, or the lower edge for band-pass / band-stop (Hz).+ pub f1: f64,+ /// Upper edge for band-pass / band-stop (Hz).+ pub f2: f64,+ /// Pass-band ripple (dB, Chebyshev / elliptic).+ pub ripple_db: f64,+ /// Stop-band attenuation (dB, elliptic).+ pub stop_db: f64,+}++/// A normalised analog low-pass prototype (cache it: Bessel needs a root search).+#[derive(Clone, Copy, Debug)]+pub struct Prototype(Zpk);++/// The analog prototype for a family, order, pass-band ripple and stop-band attenuation.+pub fn prototype(family: Family, order: usize, ripple_db: f64, stop_db: f64) -> Prototype {+ let n = order.clamp(1, MAX_ORDER);+ let rp = ripple_db.clamp(0.01, 10.0);+ let rs = stop_db.clamp(rp + 1.0, 150.0);+ Prototype(match family {+ Family::Butterworth => butterworth(n),+ Family::Bessel => bessel(n),+ Family::Chebyshev => chebyshev1(n, rp),+ Family::Elliptic => elliptic(n, rp, rs),+ })+}++/// Transform a prototype to `band` at `f1` (and `f2` for band-pass/stop) and digitise it.+pub fn realize(proto: &Prototype, band: Band, f1: f64, f2: f64, sample_rate: f64) -> Sections {+ let mut f = proto.0;+ let nyq = sample_rate * 0.5;+ let warp = |hz: f64| 2.0 * sample_rate * (PI * hz.clamp(1.0, nyq * 0.98) / sample_rate).tan();+ match band {+ Band::LowPass => lp_to_lp(&mut f, warp(f1)),+ Band::HighPass => lp_to_hp(&mut f, warp(f1)),+ Band::BandPass | Band::BandStop => {+ let (lo, hi) = if f1 <= f2 { (f1, f2) } else { (f2, f1) };+ let hi = hi.max(lo * 1.001);+ let (w1, w2) = (warp(lo), warp(hi));+ let (w0, bw) = ((w1 * w2).sqrt(), (w2 - w1).max(1e-6));+ if band == Band::BandPass { lp_to_bp(&mut f, w0, bw) } else { lp_to_bs(&mut f, w0, bw) }+ }+ }+ bilinear(&mut f, sample_rate);+ into_sections(&f)+}++/// Design a digital filter at `sample_rate`.+pub fn design(spec: &Spec, sample_rate: f64) -> Sections {+ realize(&prototype(spec.family, spec.order, spec.ripple_db, spec.stop_db), spec.band, spec.f1, spec.f2, sample_rate)+}++#[cfg(test)]+mod tests {+ use super::*;++ const SR: f64 = 48000.0;++ fn spec(family: Family, band: Band, order: usize, f1: f64, f2: f64) -> Spec {+ Spec { family, band, order, f1, f2, ripple_db: 1.0, stop_db: 60.0 }+ }++ #[test]+ fn butterworth_matches_closed_form() {+ // |H| = 1/√(1 + (Ωa/Ωc)^(2N)) with pre-warped analog frequencies.+ for n in 1..=8 {+ let s = design(&spec(Family::Butterworth, Band::LowPass, n, 1000.0, 0.0), SR);+ let wa = |f: f64| (PI * f / SR).tan();+ for f in [100.0, 500.0, 1000.0, 2000.0, 8000.0] {+ let want = -10.0 * (1.0 + (wa(f) / wa(1000.0)).powi(2 * n as i32)).log10();+ let got = s.magnitude_db(f, SR);+ assert!((got - want).abs() < 1e-6, "n={n} f={f}: {got} vs {want}");+ }+ }+ }++ #[test]+ fn bessel_is_minus_3db_at_cutoff_and_monotonic() {+ for n in 1..=10 {+ let s = design(&spec(Family::Bessel, Band::LowPass, n, 2000.0, 0.0), SR);+ assert!((s.magnitude_db(2000.0, SR) + 3.0103).abs() < 0.02, "n={n}: {}", s.magnitude_db(2000.0, SR));+ assert!(s.magnitude_db(1.0, SR).abs() < 1e-5, "n={n}: {}", s.magnitude_db(1.0, SR));+ let mut last = 1.0;+ for i in 1..200 {+ let m = s.magnitude_db(i as f64 * 100.0, SR);+ assert!(m <= last + 1e-9, "Bessel must be monotonic");+ last = m;+ }+ }+ }++ #[test]+ fn chebyshev_ripple_bounds() {+ for n in 2..=8 {+ let s = design(&Spec { ripple_db: 0.5, ..spec(Family::Chebyshev, Band::LowPass, n, 1000.0, 0.0) }, SR);+ let mut min = f64::INFINITY;+ let mut max = f64::NEG_INFINITY;+ for i in 1..100 {+ let m = s.magnitude_db(i as f64 * 10.0, SR);+ min = min.min(m);+ max = max.max(m);+ }+ assert!(max < 1e-6 && min > -0.5 - 1e-6, "n={n} {min}..{max}");+ assert!(min < -0.45, "ripple reaches the bound (n={n}: {min})");+ assert!((s.magnitude_db(1000.0, SR) + 0.5).abs() < 1e-3);+ }+ }++ #[test]+ fn elliptic_meets_ripple_and_stopband() {+ for n in 2..=8 {+ for (rp, rs) in [(1.0, 60.0), (0.1, 40.0), (0.5, 80.0)] {+ let s = design(&Spec { ripple_db: rp, stop_db: rs, ..spec(Family::Elliptic, Band::LowPass, n, 1000.0, 0.0) }, SR);+ let mut max = f64::NEG_INFINITY;+ let mut min = f64::INFINITY;+ for i in 1..=100 {+ let m = s.magnitude_db(i as f64 * 10.0, SR);+ min = min.min(m);+ max = max.max(m);+ }+ assert!(max < 1e-6 && min > -rp - 1e-3, "n={n} rp={rp}: {min}..{max}");+ // Once the response first drops below −As it never rises above it again.+ let mut below = false;+ for i in 1..2390 {+ let f = i as f64 * 10.0;+ let m = s.magnitude_db(f, SR);+ if m < -rs {+ below = true;+ }+ if below {+ assert!(m < -rs + 0.05, "n={n} rs={rs} f={f}: {m}");+ }+ }+ assert!(below, "n={n} rs={rs}: stop band reached");+ }+ }+ // Sharper than Butterworth of the same order.+ let e = design(&spec(Family::Elliptic, Band::LowPass, 4, 1000.0, 0.0), SR);+ let b = design(&spec(Family::Butterworth, Band::LowPass, 4, 1000.0, 0.0), SR);+ assert!(e.magnitude_db(1500.0, SR) < b.magnitude_db(1500.0, SR) - 10.0);+ }++ #[test]+ fn highpass_bandpass_bandstop_shapes() {+ for fam in [Family::Butterworth, Family::Chebyshev, Family::Elliptic, Family::Bessel] {+ let hp = design(&spec(fam, Band::HighPass, 4, 1000.0, 0.0), SR);+ assert!(hp.magnitude_db(10000.0, SR) > -1.1, "{fam:?} hp pass");+ assert!(hp.magnitude_db(100.0, SR) < -40.0, "{fam:?} hp stop");+ let bp = design(&spec(fam, Band::BandPass, 3, 500.0, 2000.0), SR);+ assert!(bp.magnitude_db(1000.0, SR) > -3.5, "{fam:?} bp centre {}", bp.magnitude_db(1000.0, SR));+ assert!(bp.magnitude_db(50.0, SR) < -30.0 && bp.magnitude_db(15000.0, SR) < -25.0, "{fam:?} bp stop");+ let bs = design(&spec(fam, Band::BandStop, 3, 500.0, 2000.0), SR);+ assert!(bs.magnitude_db(1000.0, SR) < -20.0, "{fam:?} bs centre {}", bs.magnitude_db(1000.0, SR));+ assert!(bs.magnitude_db(30.0, SR) > -1.1 && bs.magnitude_db(18000.0, SR) > -1.1, "{fam:?} bs pass");+ }+ }++ #[test]+ fn complex_helpers() {+ let w = C::new(0.3, -0.7);+ let back = w.acos().cos();+ assert!(back.sub(w).abs() < 1e-12);+ assert!((C::new(-4.0, 0.0).sqrt().im - 2.0).abs() < 1e-12);+ assert!((ellip_k(0.0) - PI / 2.0).abs() < 1e-12);+ // sn(K, k) = 1; cd(0, k) = 1+ assert!((sne(C::real(1.0), 0.7).re - 1.0).abs() < 1e-9);+ assert!((cde(C::real(0.0), 0.7).re - 1.0).abs() < 1e-9);+ let u = asne(C::real(0.5), 0.7);+ assert!((sne(u, 0.7).re - 0.5).abs() < 1e-9);+ }+}diff --git a/crates/audio-dsp/src/effects/declick.rs b/crates/audio-dsp/src/effects/declick.rsnew file mode 100644index 000000000..ccdce3681--- /dev/null+++ b/crates/audio-dsp/src/effects/declick.rs@@ -0,0 +1,235 @@+//! Automatic Click Remover: clicks are found as outliers of the linear-prediction residual and+//! replaced by autoregressive interpolation.+//!+//! Textbook method (Vaseghi & Rayner style): per 512-sample block an order-`p` LPC model is fitted+//! (autocorrelation + Levinson–Durbin over a Hann-windowed 1152-sample analysis span); samples+//! whose prediction error exceeds `k·σ` (σ from the median absolute residual) mark a click,+//! nearby marks are merged, and each region is re-synthesised by forward prediction from the+//! clean past and backward prediction from the future, cross-faded. Regions longer than the+//! maximum click length are left alone (they are transients, not clicks). Latency is one block+//! plus the look-ahead.++use crate::{AudioEffect, ParamSpec, ParamValues, Unit, block_len, param_plumbing};++const BLOCK: usize = 512;+const CONTEXT: usize = 512;+const LOOKAHEAD: usize = 128;+const SPAN: usize = CONTEXT + BLOCK + LOOKAHEAD;+const MAX_ORDER: usize = 32;++#[derive(Clone, Debug)]+struct Chan {+ buf: Vec<f32>,+ out: Vec<f32>,+ pos: usize,+}++impl Chan {+ fn new() -> Chan {+ Chan { buf: vec![0.0; SPAN], out: vec![0.0; BLOCK], pos: 0 }+ }+ fn reset(&mut self) {+ self.buf.iter_mut().for_each(|v| *v = 0.0);+ self.out.iter_mut().for_each(|v| *v = 0.0);+ self.pos = 0;+ }+}++/// Shared analysis scratch.+#[derive(Clone, Debug)]+struct Scratch {+ win: Vec<f32>,+ xw: Vec<f64>,+ resid: Vec<f32>,+ sorted: Vec<f32>,+ marks: Vec<bool>,+}++/// LPC coefficients `a[1..=p]` (prediction x̂[n] = Σ a_k x[n−k]) by Levinson–Durbin.+/// Returns `false` for silent / degenerate input.+fn lpc(x: &[f64], p: usize, a: &mut [f64; MAX_ORDER + 1]) -> bool {+ let mut r = [0.0f64; MAX_ORDER + 1];+ for (k, rk) in r.iter_mut().enumerate().take(p + 1) {+ *rk = x[k..].iter().zip(x).map(|(u, v)| u * v).sum();+ }+ if r[0] <= 1e-12 {+ return false;+ }+ r[0] *= 1.0 + 1e-6; // white-noise correction+ let mut e = r[0];+ let mut tmp = [0.0f64; MAX_ORDER + 1];+ *a = [0.0; MAX_ORDER + 1];+ for i in 1..=p {+ let mut acc = r[i];+ for j in 1..i {+ acc -= a[j] * r[i - j];+ }+ let k = acc / e;+ tmp[..i].copy_from_slice(&a[..i]);+ a[i] = k;+ for j in 1..i {+ a[j] = tmp[j] - k * tmp[i - j];+ }+ e *= 1.0 - k * k;+ if e <= 1e-15 {+ return false;+ }+ }+ true+}++/// Automatic click remover.+pub struct ClickRemover {+ pv: ParamValues,+ ch: Vec<Chan>,+ s: Scratch,+ /// Number of clicks repaired so far (for metering / tests).+ pub repaired: usize,+}++impl ClickRemover {+ pub const PARAMS: &'static [ParamSpec] =+ &[ParamSpec::new("threshold", "Threshold", 1.0, 100.0, 30.0, Unit::None), ParamSpec::new("complexity", "Complexity", 1.0, 100.0, 16.0, Unit::None)];++ pub fn new(_sample_rate: f32, channels: usize) -> Self {+ let win = (0..SPAN).map(|i| (0.5 - 0.5 * (2.0 * std::f64::consts::PI * (i as f64 + 0.5) / SPAN as f64).cos()) as f32).collect();+ ClickRemover {+ pv: ParamValues::new(Self::PARAMS),+ ch: vec![Chan::new(); channels.max(1)],+ s: Scratch { win, xw: vec![0.0; SPAN], resid: vec![0.0; SPAN], sorted: vec![0.0; SPAN], marks: vec![false; SPAN] },+ repaired: 0,+ }+ }+ fn apply_params(&mut self, _snap: bool) {}++ /// Detection factor k (residual outliers above k·σ are clicks).+ fn k(&self) -> f32 {+ 4.0 + 0.2 * self.pv.v("threshold")+ }+ fn order(&self) -> usize {+ (8.0 + 24.0 * (self.pv.v("complexity") - 1.0) / 99.0).round() as usize+ }+ fn max_len(&self) -> usize {+ (16.0 + 48.0 * (self.pv.v("complexity") - 1.0) / 99.0).round() as usize+ }++ fn analyse(c: &mut Chan, s: &mut Scratch, p: usize, k: f32, max_len: usize) -> usize {+ let buf = &mut c.buf;+ for i in 0..SPAN {+ s.xw[i] = (buf[i] * s.win[i]) as f64;+ }+ let mut a = [0.0f64; MAX_ORDER + 1];+ if !lpc(&s.xw, p, &mut a) {+ return 0;+ }+ // Prediction residual over the span.+ for n in 0..SPAN {+ s.resid[n] = if n < p {+ 0.0+ } else {+ let mut pred = 0.0f64;+ for j in 1..=p {+ pred += a[j] * buf[n - j] as f64;+ }+ (buf[n] as f64 - pred) as f32+ };+ }+ for n in 0..SPAN {+ s.sorted[n] = s.resid[n].abs();+ }+ let valid = &mut s.sorted[p..];+ let mid = valid.len() / 2;+ valid.select_nth_unstable_by(mid, |x, y| x.total_cmp(y));+ let sigma = valid[mid] / 0.6745;+ if sigma <= 1e-9 {+ return 0;+ }+ let thr = k * sigma;+ s.marks.iter_mut().for_each(|m| *m = false);+ let mut n = CONTEXT;+ let mut repaired = 0;+ while n < CONTEXT + BLOCK {+ if s.resid[n].abs() <= thr {+ n += 1;+ continue;+ }+ // Group outliers separated by ≤ 4 samples.+ let first = n;+ let mut last = n;+ let mut m = n + 1;+ while m < SPAN - p && m <= last + 4 {+ if s.resid[m].abs() > thr {+ last = m;+ }+ m += 1;+ }+ let start = first.saturating_sub(2).max(p);+ let end = (last + 3).min(SPAN - p - 1);+ n = last + 1;+ if end <= start || end - start > max_len {+ continue;+ }+ // Forward prediction from the (clean) past.+ let len = end - start;+ let mut fwd = [0.0f32; 80];+ let mut bwd = [0.0f32; 80];+ for t in 0..len {+ let i = start + t;+ let mut pred = 0.0f64;+ for j in 1..=p {+ let v = if i - j >= start { fwd[i - j - start] } else { buf[i - j] };+ pred += a[j] * v as f64;+ }+ fwd[t] = pred as f32;+ }+ // Backward prediction from the future (stationary AR: same coefficients reversed).+ for t in (0..len).rev() {+ let i = start + t;+ let mut pred = 0.0f64;+ for j in 1..=p {+ let v = if i + j < end { bwd[i + j - start] } else { buf[i + j] };+ pred += a[j] * v as f64;+ }+ bwd[t] = pred as f32;+ }+ for t in 0..len {+ let w = (t + 1) as f32 / (len + 1) as f32;+ buf[start + t] = (1.0 - w) * fwd[t] + w * bwd[t];+ }+ repaired += 1;+ }+ repaired+ }+}++impl AudioEffect for ClickRemover {+ param_plumbing!("click_remover");+ fn latency(&self) -> usize {+ BLOCK + LOOKAHEAD+ }+ fn reset(&mut self) {+ self.ch.iter_mut().for_each(Chan::reset);+ self.repaired = 0;+ }+ fn process(&mut self, channels: &mut [&mut [f32]]) {+ let n = block_len(channels);+ let nch = channels.len().min(self.ch.len());+ let (p, k, max_len) = (self.order(), self.k(), self.max_len().min(80));+ for (ci, chan) in channels.iter_mut().enumerate().take(nch) {+ let c = &mut self.ch[ci];+ for v in chan[..n].iter_mut() {+ let x = *v;+ *v = c.out[c.pos];+ c.buf[SPAN - BLOCK + c.pos] = x;+ c.pos += 1;+ if c.pos == BLOCK {+ c.pos = 0;+ self.repaired += Self::analyse(c, &mut self.s, p, k, max_len);+ // Emit the finished block, then slide the span.+ c.out.copy_from_slice(&c.buf[CONTEXT..CONTEXT + BLOCK]);+ c.buf.copy_within(BLOCK.., 0);+ }+ }+ }+ }+}diff --git a/crates/audio-dsp/src/effects/dynamics.rs b/crates/audio-dsp/src/effects/dynamics.rsindex 14f89fffb..5807d1ba8 100644--- a/crates/audio-dsp/src/effects/dynamics.rs+++ b/crates/audio-dsp/src/effects/dynamics.rs@@ -62,7 +62,7 @@ impl Compressor {ParamSpec::new("knee", "Knee", 0.0, 24.0, 6.0, Unit::Decibels),ParamSpec::log("attack", "Attack", 0.01, 300.0, 10.0, Unit::Milliseconds),ParamSpec::log("release", "Release", 1.0, 3000.0, 100.0, Unit::Milliseconds),- ParamSpec::new("makeup", "Make-up Gain", 0.0, 40.0, 0.0, Unit::Decibels),+ ParamSpec::new("makeup", "Make-up Gain", -40.0, 40.0, 0.0, Unit::Decibels),ParamSpec::choice("detector", "Detector", &["Peak", "RMS"], 0),];@@ -112,6 +112,9 @@ impl Compressor {impl AudioEffect for Compressor {param_plumbing!("compressor");+ fn transfer_db(&self, band: usize, input_db: f32) -> Option<f32> {+ (band == 0).then(|| self.curve(input_db) + self.pv.v("makeup"))+ }fn reset(&mut self) {self.makeup.snap();self.ms = 0.0;@@ -211,6 +214,9 @@ impl Gate {impl AudioEffect for Gate {param_plumbing!("gate");+ fn transfer_db(&self, band: usize, input_db: f32) -> Option<f32> {+ (band == 0).then(|| self.curve(input_db))+ }fn reset(&mut self) {self.env = 0.0;self.hold_left = 0;diff --git a/crates/audio-dsp/src/effects/eq.rs b/crates/audio-dsp/src/effects/eq.rsindex 0fef89b7b..47a91f906 100644--- a/crates/audio-dsp/src/effects/eq.rs+++ b/crates/audio-dsp/src/effects/eq.rs@@ -9,6 +9,8 @@ pub const FILTER_TYPE_NAMES: &[&str] = &["Peaking", "Low Shelf", "High Shelf", "/// Coefficients are recomputed at most every this many samples while parameters glide.const COEFF_INTERVAL: u32 = 16;const SMOOTH_MS: f32 = 30.0;+/// Most bands a [`BandBank`] can hold.+pub(crate) const MAX_BANDS: usize = 40;#[derive(Clone, Debug)]struct Band {@@ -35,6 +37,7 @@ pub(crate) struct BandBank {impl BandBank {pub(crate) fn new(sample_rate: f32, channels: usize, nbands: usize) -> Self {+ assert!(nbands <= MAX_BANDS);let band = Band {kind: FilterType::Peaking,freq: Smoothed::with_ms(1000f32.log2(), sample_rate, SMOOTH_MS),@@ -66,7 +69,7 @@ impl BandBank {b.dirty = true;}- fn update_coeffs(&mut self, force: bool) {+ pub(crate) fn update_coeffs(&mut self, force: bool) {let sr = self.sample_rate;for b in &mut self.bands {if b.dirty || force {@@ -122,7 +125,7 @@ impl BandBank {}let g = out_gain.tick();// Tick the band mixes once per sample (shared by all channels).- let mut mixes = [0.0f32; 16];+ let mut mixes = [0.0f32; MAX_BANDS];for (m, b) in mixes.iter_mut().zip(self.bands.iter_mut()) {*m = b.mix.tick();}@@ -228,6 +231,9 @@ impl ParametricEq {impl AudioEffect for ParametricEq {param_plumbing!("parametric_eq");+ fn response_db(&self, freq: f64) -> Option<f64> {+ Some(ParametricEq::response_db(self, freq))+ }fn reset(&mut self) {self.out.snap();self.bank.reset();@@ -284,6 +290,9 @@ impl SimpleEq {impl AudioEffect for SimpleEq {param_plumbing!("simple_eq");+ fn response_db(&self, freq: f64) -> Option<f64> {+ Some(SimpleEq::response_db(self, freq))+ }fn reset(&mut self) {self.out.snap();self.bank.reset();diff --git a/crates/audio-dsp/src/effects/filters.rs b/crates/audio-dsp/src/effects/filters.rsnew file mode 100644index 000000000..b4ff576e0--- /dev/null+++ b/crates/audio-dsp/src/effects/filters.rs@@ -0,0 +1,702 @@+//! Filter and EQ effects: graphic equalisers (10/20/30 bands), the full parametric equaliser+//! (pass filters, shelves, five peaking bands), the six-notch filter, the Scientific Filter+//! (Bessel / Butterworth / Chebyshev / elliptic designs) and the FFT Filter (frequency-sampled+//! gain curve applied by STFT overlap-add).++use super::eq::{BandBank, MAX_BANDS};+use super::stft::{Spectral, StftChannel, fft_size};+use crate::biquad::{Biquad, FilterType};+use crate::design::{self, Band, Family, MAX_SECTIONS, Prototype, Sections};+use crate::{AudioEffect, ParamSpec, ParamValues, Smoothed, Unit, block_len, db_to_gain, param_plumbing};++const SMOOTH_MS: f32 = 30.0;++/// Q of a peaking band `octaves` wide (between the −3 dB points of the analog prototype).+pub fn q_for_octaves(octaves: f64) -> f64 {+ let p = 2f64.powf(octaves);+ p.sqrt() / (p - 1.0)+}++/// Copy `N` parameter-spec arrays into one flat array (const-evaluable).+const fn flatten<const K: usize, const N: usize, const M: usize>(groups: [[ParamSpec; K]; N]) -> [ParamSpec; M] {+ let mut out = [ParamSpec::new("", "", 0.0, 0.0, 0.0, Unit::None); M];+ let mut g = 0;+ while g < N {+ let mut k = 0;+ while k < K {+ out[g * K + k] = groups[g][k];+ k += 1;+ }+ g += 1;+ }+ out+}++/// `a` followed by `b` (const-evaluable).+const fn join<const A: usize, const B: usize, const M: usize>(a: [ParamSpec; A], b: [ParamSpec; B]) -> [ParamSpec; M] {+ let mut out = [ParamSpec::new("", "", 0.0, 0.0, 0.0, Unit::None); M];+ let mut i = 0;+ while i < A {+ out[i] = a[i];+ i += 1;+ }+ let mut j = 0;+ while j < B {+ out[A + j] = b[j];+ j += 1;+ }+ out+}++// ------------------------------------------------------------------------------ graphic EQ++/// Centre frequencies of the 10-band graphic equaliser.+pub const GEQ10_FREQS: [f32; 10] = [31.5, 63.0, 125.0, 250.0, 500.0, 1000.0, 2000.0, 4000.0, 8000.0, 16000.0];+const GEQ10_PARAMS: &[ParamSpec] = &[+ ParamSpec::new("b1", "31.5 Hz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b2", "63 Hz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b3", "125 Hz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b4", "250 Hz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b5", "500 Hz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b6", "1 kHz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b7", "2 kHz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b8", "4 kHz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b9", "8 kHz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b10", "16 kHz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("gain", "Master Gain", -24.0, 24.0, 0.0, Unit::Decibels),+];+/// Centre frequencies of the 20-band graphic equaliser.+pub const GEQ20_FREQS: [f32; 20] =+ [31.5, 44.0, 63.0, 88.0, 125.0, 177.0, 250.0, 355.0, 500.0, 710.0, 1000.0, 1400.0, 2000.0, 2800.0, 4000.0, 5600.0, 8000.0, 11200.0, 16000.0, 22400.0];+const GEQ20_PARAMS: &[ParamSpec] = &[+ ParamSpec::new("b1", "31.5 Hz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b2", "44 Hz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b3", "63 Hz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b4", "88 Hz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b5", "125 Hz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b6", "177 Hz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b7", "250 Hz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b8", "355 Hz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b9", "500 Hz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b10", "710 Hz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b11", "1 kHz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b12", "1.4 kHz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b13", "2 kHz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b14", "2.8 kHz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b15", "4 kHz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b16", "5.6 kHz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b17", "8 kHz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b18", "11.2 kHz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b19", "16 kHz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b20", "22.4 kHz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("gain", "Master Gain", -24.0, 24.0, 0.0, Unit::Decibels),+];+/// Centre frequencies of the 30-band graphic equaliser.+pub const GEQ30_FREQS: [f32; 30] = [+ 25.0, 31.5, 40.0, 50.0, 63.0, 80.0, 100.0, 125.0, 160.0, 200.0, 250.0, 315.0, 400.0, 500.0, 630.0, 800.0, 1000.0, 1250.0, 1600.0, 2000.0, 2500.0, 3150.0,+ 4000.0, 5000.0, 6300.0, 8000.0, 10000.0, 12500.0, 16000.0, 20000.0,+];+const GEQ30_PARAMS: &[ParamSpec] = &[+ ParamSpec::new("b1", "25 Hz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b2", "31.5 Hz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b3", "40 Hz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b4", "50 Hz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b5", "63 Hz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b6", "80 Hz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b7", "100 Hz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b8", "125 Hz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b9", "160 Hz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b10", "200 Hz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b11", "250 Hz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b12", "315 Hz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b13", "400 Hz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b14", "500 Hz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b15", "630 Hz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b16", "800 Hz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b17", "1 kHz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b18", "1.25 kHz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b19", "1.6 kHz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b20", "2 kHz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b21", "2.5 kHz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b22", "3.15 kHz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b23", "4 kHz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b24", "5 kHz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b25", "6.3 kHz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b26", "8 kHz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b27", "10 kHz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b28", "12.5 kHz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b29", "16 kHz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("b30", "20 kHz", -24.0, 24.0, 0.0, Unit::Decibels),+ ParamSpec::new("gain", "Master Gain", -24.0, 24.0, 0.0, Unit::Decibels),+];++/// Constant-Q graphic equaliser with 10 (octave), 20 (half-octave) or 30 (third-octave) bands.+pub struct GraphicEq<const N: usize> {+ pv: ParamValues,+ bank: BandBank,+ out: Smoothed,+}++impl<const N: usize> GraphicEq<N> {+ pub const PARAMS: &'static [ParamSpec] = match N {+ 10 => GEQ10_PARAMS,+ 20 => GEQ20_PARAMS,+ _ => GEQ30_PARAMS,+ };+ const ID: &'static str = match N {+ 10 => "graphic_eq_10",+ 20 => "graphic_eq_20",+ _ => "graphic_eq_30",+ };++ /// Band centre frequencies.+ pub fn freqs() -> &'static [f32] {+ match N {+ 10 => &GEQ10_FREQS,+ 20 => &GEQ20_FREQS,+ _ => &GEQ30_FREQS,+ }+ }++ /// Band Q (octave, half-octave or third-octave bandwidth).+ pub fn q() -> f32 {+ q_for_octaves(match N {+ 10 => 1.0,+ 20 => 0.5,+ _ => 1.0 / 3.0,+ }) as f32+ }++ pub fn new(sample_rate: f32, channels: usize) -> Self {+ assert!(N <= MAX_BANDS);+ let mut s = GraphicEq {+ pv: ParamValues::new(Self::PARAMS),+ bank: BandBank::new(sample_rate, channels, N),+ out: Smoothed::with_ms(1.0, sample_rate, SMOOTH_MS),+ };+ s.apply_params(true);+ s+ }++ fn apply_params(&mut self, snap: bool) {+ let q = Self::q();+ for (i, &f) in Self::freqs().iter().enumerate() {+ let g = self.pv.v(Self::PARAMS[i].id);+ self.bank.set_band(i, true, FilterType::Peaking, f, g, q, snap);+ }+ self.out.set(db_to_gain(self.pv.v("gain")));+ if snap {+ self.out.snap();+ self.bank.update_coeffs(true);+ }+ }+}++impl<const N: usize> AudioEffect for GraphicEq<N> {+ param_plumbing!(Self::ID);+ fn response_db(&self, freq: f64) -> Option<f64> {+ Some(self.bank.response_db(freq) + self.pv.v("gain") as f64)+ }+ fn reset(&mut self) {+ self.out.snap();+ self.bank.reset();+ }+ fn process(&mut self, channels: &mut [&mut [f32]]) {+ self.bank.process(channels, &mut self.out);+ }+}++// ----------------------------------------------------------------------- parametric EQ++/// Pass-filter slopes.+pub const SLOPES: &[&str] = &["12 dB/oct", "24 dB/oct", "36 dB/oct", "48 dB/oct"];++macro_rules! peq_band {+ ($p:literal, $name:literal, $f:expr, $q:expr) => {+ [+ ParamSpec::toggle(concat!($p, "_on"), concat!($name, " On"), true),+ ParamSpec::log(concat!($p, "_freq"), concat!($name, " Frequency"), 20.0, 20000.0, $f, Unit::Hertz),+ ParamSpec::new(concat!($p, "_gain"), concat!($name, " Gain"), -30.0, 30.0, 0.0, Unit::Decibels),+ ParamSpec::log(concat!($p, "_q"), concat!($name, " Q"), 0.1, 30.0, $q, Unit::Q),+ ]+ };+}++/// The bands of the full parametric equaliser between its pass filters, in signal order:+/// (parameter prefix, filter type).+pub const PEQ_BANDS: [(&str, FilterType); 7] = [+ ("low", FilterType::LowShelf),+ ("b1", FilterType::Peaking),+ ("b2", FilterType::Peaking),+ ("mid", FilterType::Peaking),+ ("b4", FilterType::Peaking),+ ("b5", FilterType::Peaking),+ ("high", FilterType::HighShelf),+];++const PEQ_BAND_IDS: [[&str; 4]; 7] = [+ ["low_on", "low_freq", "low_gain", "low_q"],+ ["b1_on", "b1_freq", "b1_gain", "b1_q"],+ ["b2_on", "b2_freq", "b2_gain", "b2_q"],+ ["mid_on", "mid_freq", "mid_gain", "mid_q"],+ ["b4_on", "b4_freq", "b4_gain", "b4_q"],+ ["b5_on", "b5_freq", "b5_gain", "b5_q"],+ ["high_on", "high_freq", "high_gain", "high_q"],+];++const PEQ_HEAD: [ParamSpec; 4] = [+ ParamSpec::new("master_gain", "Master Gain", -30.0, 30.0, 0.0, Unit::Decibels),+ ParamSpec::toggle("hp_on", "High Pass On", false),+ ParamSpec::log("hp_freq", "High Pass Frequency", 10.0, 20000.0, 30.0, Unit::Hertz),+ ParamSpec::choice("hp_slope", "High Pass Slope", SLOPES, 0),+];+const PEQ_TAIL: [ParamSpec; 3] = [+ ParamSpec::toggle("lp_on", "Low Pass On", false),+ ParamSpec::log("lp_freq", "Low Pass Frequency", 20.0, 22000.0, 18000.0, Unit::Hertz),+ ParamSpec::choice("lp_slope", "Low Pass Slope", SLOPES, 0),+];+const PEQ_MID: [ParamSpec; 28] = flatten([+ peq_band!("low", "Low Shelf", 100.0, 0.707),+ peq_band!("b1", "Band 1", 200.0, 1.0),+ peq_band!("b2", "Band 2", 500.0, 1.0),+ peq_band!("mid", "Band 3", 1000.0, 1.0),+ peq_band!("b4", "Band 4", 2000.0, 1.0),+ peq_band!("b5", "Band 5", 5000.0, 1.0),+ peq_band!("high", "High Shelf", 8000.0, 0.707),+]);+const PEQ_HEAD_MID: [ParamSpec; 32] = join(PEQ_HEAD, PEQ_MID);+const PEQ_PARAMS: [ParamSpec; 35] = join(PEQ_HEAD_MID, PEQ_TAIL);++/// Butterworth Q of section `k` (0-based) of an order-`2m` cascade.+pub fn butterworth_q(m: usize, k: usize) -> f32 {+ let n = 2 * m;+ (1.0 / (2.0 * (std::f64::consts::PI * (2 * k + 1) as f64 / (2 * n) as f64).cos())) as f32+}++/// Premiere-style parametric equaliser: master gain, high-pass (12–48 dB/oct), low shelf,+/// five peaking bands, high shelf and low-pass (12–48 dB/oct), all RBJ biquads.+pub struct FullParametricEq {+ pv: ParamValues,+ bank: BandBank,+ out: Smoothed,+}++impl FullParametricEq {+ pub const PARAMS: &'static [ParamSpec] = &PEQ_PARAMS;+ /// Bank layout: 4 high-pass slots, 7 bands, 4 low-pass slots.+ const SLOTS: usize = 4 + 7 + 4;++ pub fn new(sample_rate: f32, channels: usize) -> Self {+ let mut s = FullParametricEq {+ pv: ParamValues::new(Self::PARAMS),+ bank: BandBank::new(sample_rate, channels, Self::SLOTS),+ out: Smoothed::with_ms(1.0, sample_rate, SMOOTH_MS),+ };+ s.apply_params(true);+ s+ }++ fn apply_params(&mut self, snap: bool) {+ let p = &self.pv;+ let pass = |on: bool, slope: usize, slot: usize| -> (bool, f32) {+ let m = slope + 1;+ if on && slot < m { (true, butterworth_q(m, slot)) } else { (false, std::f32::consts::FRAC_1_SQRT_2) }+ };+ let (hp_on, hp_f, hp_s) = (p.on("hp_on"), p.v("hp_freq"), p.idx("hp_slope"));+ let (lp_on, lp_f, lp_s) = (p.on("lp_on"), p.v("lp_freq"), p.idx("lp_slope"));+ let mut bands = [(false, FilterType::Peaking, 1000.0, 0.0, 1.0); 7];+ for (i, ids) in PEQ_BAND_IDS.iter().enumerate() {+ bands[i] = (p.on(ids[0]), PEQ_BANDS[i].1, p.v(ids[1]), p.v(ids[2]), p.v(ids[3]));+ }+ for slot in 0..4 {+ let (on, q) = pass(hp_on, hp_s, slot);+ self.bank.set_band(slot, on, FilterType::HighPass, hp_f, 0.0, q, snap);+ let (on, q) = pass(lp_on, lp_s, slot);+ self.bank.set_band(11 + slot, on, FilterType::LowPass, lp_f, 0.0, q, snap);+ }+ for (i, (on, kind, f, g, q)) in bands.into_iter().enumerate() {+ self.bank.set_band(4 + i, on, kind, f, g, q, snap);+ }+ self.out.set(db_to_gain(self.pv.v("master_gain")));+ if snap {+ self.out.snap();+ self.bank.update_coeffs(true);+ }+ }+}++impl AudioEffect for FullParametricEq {+ param_plumbing!("parametric_eq_full");+ fn response_db(&self, freq: f64) -> Option<f64> {+ Some(self.bank.response_db(freq) + self.pv.v("master_gain") as f64)+ }+ fn reset(&mut self) {+ self.out.snap();+ self.bank.reset();+ }+ fn process(&mut self, channels: &mut [&mut [f32]]) {+ self.bank.process(channels, &mut self.out);+ }+}++// ---------------------------------------------------------------------------- notch filter++/// Notch widths.+pub const NOTCH_WIDTHS: &[&str] = &["Narrow", "Very Narrow", "Super Narrow"];+const NOTCH_Q: [f32; 3] = [8.0, 20.0, 50.0];++macro_rules! notch {+ ($n:literal, $f:expr) => {+ [+ ParamSpec::toggle(concat!("n", $n, "_on"), concat!("Notch ", $n, " On"), false),+ ParamSpec::log(concat!("n", $n, "_freq"), concat!("Notch ", $n, " Frequency"), 20.0, 20000.0, $f, Unit::Hertz),+ ParamSpec::new(concat!("n", $n, "_gain"), concat!("Notch ", $n, " Gain"), -90.0, 0.0, -30.0, Unit::Decibels),+ ]+ };+}++const NOTCH_BANDS: [ParamSpec; 18] =+ flatten([notch!("1", 60.0), notch!("2", 120.0), notch!("3", 180.0), notch!("4", 240.0), notch!("5", 300.0), notch!("6", 360.0)]);+const NOTCH_PARAMS: [ParamSpec; 19] = join(NOTCH_BANDS, [ParamSpec::choice("width", "Notch Width", NOTCH_WIDTHS, 0)]);++const NOTCH_IDS: [[&str; 3]; 6] = [+ ["n1_on", "n1_freq", "n1_gain"],+ ["n2_on", "n2_freq", "n2_gain"],+ ["n3_on", "n3_freq", "n3_gain"],+ ["n4_on", "n4_freq", "n4_gain"],+ ["n5_on", "n5_freq", "n5_gain"],+ ["n6_on", "n6_freq", "n6_gain"],+];++/// Up to six narrow cuts (constant-bandwidth [`FilterType::Cut`] biquads) of selectable width.+pub struct NotchFilter {+ pv: ParamValues,+ bank: BandBank,+ out: Smoothed,+}++impl NotchFilter {+ pub const PARAMS: &'static [ParamSpec] = &NOTCH_PARAMS;++ pub fn new(sample_rate: f32, channels: usize) -> Self {+ let mut s = NotchFilter { pv: ParamValues::new(Self::PARAMS), bank: BandBank::new(sample_rate, channels, 6), out: Smoothed::new(1.0, 0) };+ s.apply_params(true);+ s+ }++ fn apply_params(&mut self, snap: bool) {+ let q = NOTCH_Q[self.pv.idx("width").min(2)];+ for (i, ids) in NOTCH_IDS.iter().enumerate() {+ self.bank.set_band(i, self.pv.on(ids[0]), FilterType::Cut, self.pv.v(ids[1]), self.pv.v(ids[2]), q, snap);+ }+ if snap {+ self.bank.update_coeffs(true);+ }+ }+}++impl AudioEffect for NotchFilter {+ param_plumbing!("notch_filter");+ fn response_db(&self, freq: f64) -> Option<f64> {+ Some(self.bank.response_db(freq))+ }+ fn reset(&mut self) {+ self.bank.reset();+ }+ fn process(&mut self, channels: &mut [&mut [f32]]) {+ self.bank.process(channels, &mut self.out);+ }+}++// ----------------------------------------------------------------------- scientific filter++pub const SCI_TYPES: &[&str] = &["Bessel", "Butterworth", "Chebyshev", "Elliptical"];+pub const SCI_MODES: &[&str] = &["Low Pass", "High Pass", "Band Pass", "Band Stop"];++/// Classical IIR designs (see [`crate::design`]) as a cascade of biquads. Cutoff changes glide+/// (redesigned every 32 samples while moving); type/order/ripple changes switch immediately.+pub struct ScientificFilter {+ pv: ParamValues,+ sr: f32,+ proto_key: (usize, usize, f32, f32),+ proto: Prototype,+ band: Band,+ /// log2 cutoffs (smoothed so automation glides).+ f1: Smoothed,+ f2: Smoothed,+ sections: Sections,+ state: Vec<[Biquad; MAX_SECTIONS]>,+ gain: Smoothed,+ counter: u32,+ dirty: bool,+}++impl ScientificFilter {+ pub const PARAMS: &'static [ParamSpec] = &[+ ParamSpec::choice("type", "Type", SCI_TYPES, 1),+ ParamSpec::choice("mode", "Mode", SCI_MODES, 0),+ ParamSpec::new("order", "Order", 1.0, design::MAX_ORDER as f32, 6.0, Unit::None),+ ParamSpec::log("cutoff", "Cutoff", 20.0, 20000.0, 1000.0, Unit::Hertz),+ ParamSpec::log("high_cutoff", "High Cutoff", 20.0, 20000.0, 4000.0, Unit::Hertz),+ ParamSpec::new("ripple", "Passband Ripple", 0.01, 6.0, 1.0, Unit::Decibels),+ ParamSpec::new("stop_atten", "Stopband Attenuation", 20.0, 120.0, 60.0, Unit::Decibels),+ ParamSpec::new("gain", "Master Gain", -30.0, 30.0, 0.0, Unit::Decibels),+ ];++ pub fn new(sample_rate: f32, channels: usize) -> Self {+ let proto = design::prototype(Family::Butterworth, 1, 1.0, 60.0);+ let mut s = ScientificFilter {+ pv: ParamValues::new(Self::PARAMS),+ sr: sample_rate,+ proto_key: (usize::MAX, 0, 0.0, 0.0),+ proto,+ band: Band::LowPass,+ f1: Smoothed::with_ms(10.0, sample_rate, SMOOTH_MS),+ f2: Smoothed::with_ms(12.0, sample_rate, SMOOTH_MS),+ sections: design::realize(&proto, Band::LowPass, 1000.0, 2000.0, sample_rate as f64),+ state: vec![[Biquad::new(); MAX_SECTIONS]; channels.max(1)],+ gain: Smoothed::with_ms(1.0, sample_rate, SMOOTH_MS),+ counter: 0,+ dirty: true,+ };+ s.apply_params(true);+ s+ }++ fn family(&self) -> Family {+ [Family::Bessel, Family::Butterworth, Family::Chebyshev, Family::Elliptic][self.pv.idx("type").min(3)]+ }++ fn apply_params(&mut self, snap: bool) {+ let key = (self.pv.idx("type"), self.pv.v("order").round() as usize, self.pv.v("ripple"), self.pv.v("stop_atten"));+ if key != self.proto_key {+ self.proto_key = key;+ self.proto = design::prototype(self.family(), key.1, key.2 as f64, key.3 as f64);+ }+ self.band = [Band::LowPass, Band::HighPass, Band::BandPass, Band::BandStop][self.pv.idx("mode").min(3)];+ self.f1.set(self.pv.v("cutoff").log2());+ self.f2.set(self.pv.v("high_cutoff").log2());+ self.gain.set(db_to_gain(self.pv.v("gain")));+ self.dirty = true;+ if snap {+ self.f1.snap();+ self.f2.snap();+ self.gain.snap();+ self.redesign();+ }+ }++ fn redesign(&mut self) {+ let (f1, f2) = (2f64.powf(self.f1.value() as f64), 2f64.powf(self.f2.value() as f64));+ self.sections = design::realize(&self.proto, self.band, f1, f2, self.sr as f64);+ self.dirty = self.f1.is_smoothing() || self.f2.is_smoothing();+ }++ /// The designed cascade at the target settings.+ pub fn target_sections(&self) -> Sections {+ design::realize(&self.proto, self.band, self.pv.v("cutoff") as f64, self.pv.v("high_cutoff") as f64, self.sr as f64)+ }+}++impl AudioEffect for ScientificFilter {+ param_plumbing!("scientific_filter");+ fn response_db(&self, freq: f64) -> Option<f64> {+ Some(self.target_sections().magnitude_db(freq, self.sr as f64) + self.pv.v("gain") as f64)+ }+ fn reset(&mut self) {+ self.f1.snap();+ self.f2.snap();+ self.gain.snap();+ self.state.iter_mut().for_each(|s| s.iter_mut().for_each(Biquad::reset));+ self.counter = 0;+ self.redesign();+ }+ fn process(&mut self, channels: &mut [&mut [f32]]) {+ let n = block_len(channels);+ let nch = channels.len().min(self.state.len());+ for i in 0..n {+ if self.counter == 0 && self.dirty {+ self.redesign();+ }+ self.counter = (self.counter + 1) % 32;+ self.f1.tick();+ self.f2.tick();+ if self.f1.is_smoothing() || self.f2.is_smoothing() {+ self.dirty = true;+ }+ let g = self.gain.tick() as f64;+ let secs = self.sections.as_slice();+ for ch in 0..nch {+ let mut x = channels[ch][i] as f64;+ for (c, st) in secs.iter().zip(self.state[ch].iter_mut()) {+ x = st.tick(c, x);+ }+ channels[ch][i] = (x * g) as f32;+ }+ }+ }+}++// ------------------------------------------------------------------------------ FFT filter++/// Number of FFT Filter curve points.+pub const FFT_POINTS: usize = 8;+const FFT_POINT_IDS: [[&str; 2]; FFT_POINTS] = [+ ["p1_freq", "p1_gain"],+ ["p2_freq", "p2_gain"],+ ["p3_freq", "p3_gain"],+ ["p4_freq", "p4_gain"],+ ["p5_freq", "p5_gain"],+ ["p6_freq", "p6_gain"],+ ["p7_freq", "p7_gain"],+ ["p8_freq", "p8_gain"],+];++macro_rules! fft_point {+ ($n:literal, $f:expr) => {+ [+ ParamSpec::log(concat!("p", $n, "_freq"), concat!("Point ", $n, " Frequency"), 20.0, 20000.0, $f, Unit::Hertz),+ ParamSpec::new(concat!("p", $n, "_gain"), concat!("Point ", $n, " Gain"), -60.0, 20.0, 0.0, Unit::Decibels),+ ]+ };+}++const FFT_POINT_PARAMS: [ParamSpec; 16] = flatten([+ fft_point!("1", 40.0),+ fft_point!("2", 100.0),+ fft_point!("3", 250.0),+ fft_point!("4", 600.0),+ fft_point!("5", 1500.0),+ fft_point!("6", 4000.0),+ fft_point!("7", 9000.0),+ fft_point!("8", 16000.0),+]);+const FFT_PARAMS: [ParamSpec; 17] = join(FFT_POINT_PARAMS, [ParamSpec::choice("interp", "Interpolation", &["Linear", "Smooth"], 1)]);++/// Gain (dB) of the FFT Filter curve at `freq` for points `(freq, gain_db)` (any order):+/// constant beyond the end points, interpolated in log-frequency between them (linearly or with+/// a smoothstep).+pub fn fft_curve_db(points: &[(f32, f32)], freq: f32, smooth: bool) -> f32 {+ let mut pts = [(0.0f32, 0.0f32); FFT_POINTS];+ let n = points.len().min(FFT_POINTS);+ pts[..n].copy_from_slice(&points[..n]);+ pts[..n].sort_by(|a, b| a.0.total_cmp(&b.0));+ let pts = &pts[..n];+ if pts.is_empty() {+ return 0.0;+ }+ if freq <= pts[0].0 {+ return pts[0].1;+ }+ for w in pts.windows(2) {+ if freq <= w[1].0 {+ let span = (w[1].0 / w[0].0).log2();+ let mut t = if span > 0.0 { (freq / w[0].0).log2() / span } else { 1.0 };+ if smooth {+ t = t * t * (3.0 - 2.0 * t);+ }+ return w[0].1 + (w[1].1 - w[0].1) * t;+ }+ }+ pts[n - 1].1+}++/// Zero-phase frequency-domain gain curve (8 points), applied with a √Hann STFT at 75 %+/// overlap (latency = FFT size). Curve changes glide over a few frames.+pub struct FftFilter {+ pv: ParamValues,+ sr: f32,+ n: usize,+ hop: usize,+ spec: Spectral,+ stft: Vec<StftChannel>,+ /// Target and current per-bin linear gains.+ target: Vec<f32>,+ gains: Vec<f32>,+}++impl FftFilter {+ pub const PARAMS: &'static [ParamSpec] = &FFT_PARAMS;++ pub fn new(sample_rate: f32, channels: usize) -> Self {+ let n = fft_size(sample_rate);+ let bins = n / 2 + 1;+ let mut s = FftFilter {+ pv: ParamValues::new(Self::PARAMS),+ sr: sample_rate,+ n,+ hop: n / 4,+ spec: Spectral::new(n, true),+ stft: vec![StftChannel::new(n); channels.max(1)],+ target: vec![1.0; bins],+ gains: vec![1.0; bins],+ };+ s.apply_params(true);+ s+ }++ fn points(&self) -> [(f32, f32); FFT_POINTS] {+ let mut p = [(0.0, 0.0); FFT_POINTS];+ for (i, ids) in FFT_POINT_IDS.iter().enumerate() {+ p[i] = (self.pv.v(ids[0]), self.pv.v(ids[1]));+ }+ p+ }++ fn apply_params(&mut self, snap: bool) {+ let pts = self.points();+ let smooth = self.pv.idx("interp") == 1;+ let bins = self.n / 2 + 1;+ for k in 0..bins {+ let f = (k as f32 * self.sr / self.n as f32).max(1.0);+ self.target[k] = db_to_gain(fft_curve_db(&pts, f, smooth));+ }+ if snap {+ self.gains.copy_from_slice(&self.target);+ }+ }+}++impl AudioEffect for FftFilter {+ param_plumbing!("fft_filter");+ fn latency(&self) -> usize {+ self.n+ }+ fn response_db(&self, freq: f64) -> Option<f64> {+ Some(fft_curve_db(&self.points(), freq as f32, self.pv.idx("interp") == 1) as f64)+ }+ fn reset(&mut self) {+ self.stft.iter_mut().for_each(StftChannel::reset);+ self.gains.copy_from_slice(&self.target);+ }+ fn process(&mut self, channels: &mut [&mut [f32]]) {+ let len = block_len(channels);+ let nch = channels.len().min(self.stft.len());+ let (n, hop) = (self.n, self.hop);+ let scale = 1.0 / (n as f32 * 2.0);+ let bins = n / 2 + 1;+ for i in 0..len {+ for ch in 0..nch {+ let spec = &mut self.spec;+ let gains = &mut self.gains;+ let target = &self.target;+ // Every channel frames at the same samples; the gains glide once per frame.+ let first = ch == 0;+ let mut frame = |input: &[f32], out: &mut [f32]| {+ if first {+ for k in 0..bins {+ gains[k] += (target[k] - gains[k]) * 0.5;+ }+ }+ spec.analyse(input);+ for k in 0..bins {+ spec.re[k] *= gains[k];+ spec.im[k] *= gains[k];+ }+ spec.synthesise_add(out, scale);+ };+ channels[ch][i] = self.stft[ch].tick(channels[ch][i], hop, &mut frame);+ }+ }+ }+}diff --git a/crates/audio-dsp/src/effects/mod.rs b/crates/audio-dsp/src/effects/mod.rsindex fd11ffc99..1a6f02a33 100644--- a/crates/audio-dsp/src/effects/mod.rs+++ b/crates/audio-dsp/src/effects/mod.rs@@ -1,20 +1,33 @@//! Audio effects and their registry.pub mod channel;+pub mod declick;pub mod dynamics;pub mod eq;pub mod essential;+pub mod filters;+pub mod modulation;+pub mod multiband;pub mod pitch;pub mod restoration;+pub mod reverbs;+pub mod special;mod stft;pub mod time;+pub(crate) mod util;pub use channel::{Amplify, Balance, ChannelVolume, Invert, Route, Routing};+pub use declick::ClickRemover;pub use dynamics::{Compressor, Gate, Limiter};pub use eq::{ParametricEq, SimpleEq};pub use essential::{DeEsser, DeReverb, SpeechEnhance, StereoWidth};+pub use filters::{FftFilter, FullParametricEq, GraphicEq, NotchFilter, ScientificFilter};+pub use modulation::{AnalogDelay, ChorusFlanger, Flanger, MultitapDelay, Phaser};+pub use multiband::{DynamicsRack, MultibandCompressor, TubeCompressor};pub use pitch::PitchShifter;pub use restoration::{DeHum, DeNoise};+pub use reverbs::{ConvolutionReverb, SurroundReverb};+pub use special::{AmbisonicsPanner, Binauralizer, ChannelMixer, Distortion, GuitarSuite, LoudnessMeterFx, Mastering, Mute, StereoExpander, VocalEnhancer};pub use time::{Delay, Reverb};use crate::{AudioEffect, ParamSpec};@@ -28,6 +41,9 @@ pub enum Category {Channel,Restoration,Pitch,+ Modulation,+ Reverb,+ Special,}/// Registry entry describing one effect type.@@ -98,6 +114,35 @@ static REGISTRY: &[EffectInfo] = &[entry!("dereverb", "DeReverb", Restoration, DeReverb),entry!("speech_enhance", "Enhance Speech", Filter, SpeechEnhance),entry!("stereo_width", "Stereo Width", Channel, StereoWidth),+ // Premiere audio-effect set (M7.7)+ entry!("graphic_eq_10", "Graphic Equalizer (10 Bands)", Filter, GraphicEq<10>),+ entry!("graphic_eq_20", "Graphic Equalizer (20 Bands)", Filter, GraphicEq<20>),+ entry!("graphic_eq_30", "Graphic Equalizer (30 Bands)", Filter, GraphicEq<30>),+ entry!("parametric_eq_full", "Parametric Equalizer (full)", Filter, FullParametricEq),+ entry!("notch_filter", "Notch Filter", Filter, NotchFilter),+ entry!("scientific_filter", "Scientific Filter", Filter, ScientificFilter),+ entry!("fft_filter", "FFT Filter", Filter, FftFilter),+ entry!("dynamics_rack", "Dynamics", Dynamics, DynamicsRack),+ entry!("multiband_compressor", "Multiband Compressor", Dynamics, MultibandCompressor),+ entry!("tube_compressor", "Tube-modeled Compressor", Dynamics, TubeCompressor),+ entry!("chorus_flanger", "Chorus/Flanger", Modulation, ChorusFlanger),+ entry!("flanger", "Flanger", Modulation, Flanger),+ entry!("phaser", "Phaser", Modulation, Phaser),+ entry!("analog_delay", "Analog Delay", Time, AnalogDelay),+ entry!("multitap_delay", "Multitap Delay", Time, MultitapDelay),+ entry!("convolution_reverb", "Convolution Reverb", Reverb, ConvolutionReverb),+ entry!("surround_reverb", "Surround Reverb", Reverb, SurroundReverb),+ entry!("click_remover", "Automatic Click Remover", Restoration, ClickRemover),+ entry!("channel_mixer", "Channel Mixer", Channel, ChannelMixer),+ entry!("distortion", "Distortion", Special, Distortion),+ entry!("guitar_suite", "GuitarSuite", Special, GuitarSuite),+ entry!("mastering", "Mastering", Special, Mastering),+ entry!("vocal_enhancer", "Vocal Enhancer", Special, VocalEnhancer),+ entry!("stereo_expander", "Stereo Expander", Channel, StereoExpander),+ entry!("binauralizer", "Binauralizer - Ambisonics", Special, Binauralizer),+ entry!("ambisonics_panner", "Panner - Ambisonics", Special, AmbisonicsPanner),+ entry!("loudness_meter", "Loudness Meter", Special, LoudnessMeterFx),+ entry!("mute", "Mute", Channel, Mute),];/// All registered effects.@@ -271,3 +316,6 @@ mod tests {}}}++#[cfg(test)]+mod premiere_tests;diff --git a/crates/audio-dsp/src/effects/modulation.rs b/crates/audio-dsp/src/effects/modulation.rsnew file mode 100644index 000000000..1851c79d8--- /dev/null+++ b/crates/audio-dsp/src/effects/modulation.rs@@ -0,0 +1,554 @@+//! Modulation and echo effects: Chorus/Flanger, Flanger, Phaser, Analog Delay and Multitap+//! Delay. All modulated delays read with linear interpolation; feedback loops are bounded+//! (|g| < 1, or saturating for the Analog Delay).++use super::util::{AllPass1, DelayLine, Envelope, Lfo, OnePole, coef, uni_sine, uni_tri};+use crate::{AudioEffect, ParamSpec, ParamValues, Smoothed, Unit, block_len, db_to_gain, param_plumbing};++const SM: f32 = 20.0;++// ---------------------------------------------------------------------------- chorus / flanger++/// Chorus (three modulated voices, 15–35 ms) or flanger (one voice, 0.3–5 ms, feedback).+pub struct ChorusFlanger {+ pv: ParamValues,+ sr: f32,+ lines: Vec<DelayLine>,+ lfo: Lfo,+ fb: Vec<f32>,+ fast: Vec<Envelope>,+ slow: Vec<Envelope>,+ mix: Smoothed,+ width: Smoothed,+ intensity: Smoothed,+ speed: f32,+}++impl ChorusFlanger {+ pub const PARAMS: &'static [ParamSpec] = &[+ ParamSpec::choice("mode", "Mode", &["Chorus", "Flanger"], 0),+ ParamSpec::log("speed", "Speed", 0.05, 10.0, 0.8, Unit::Hertz),+ ParamSpec::new("width", "Width", 0.0, 100.0, 50.0, Unit::Percent),+ ParamSpec::new("intensity", "Intensity", 0.0, 100.0, 30.0, Unit::Percent),+ ParamSpec::new("transience", "Transience", 0.0, 100.0, 0.0, Unit::Percent),+ ParamSpec::new("mix", "Mix", 0.0, 100.0, 50.0, Unit::Percent),+ ];++ pub fn new(sample_rate: f32, channels: usize) -> Self {+ let ch = channels.max(1);+ let max = (0.05 * sample_rate) as usize;+ let mut s = ChorusFlanger {+ pv: ParamValues::new(Self::PARAMS),+ sr: sample_rate,+ lines: vec![DelayLine::new(max); ch],+ lfo: Lfo::default(),+ fb: vec![0.0; ch],+ fast: vec![Envelope::default(); ch],+ slow: vec![Envelope::default(); ch],+ mix: Smoothed::with_ms(0.0, sample_rate, SM),+ width: Smoothed::with_ms(0.0, sample_rate, SM),+ intensity: Smoothed::with_ms(0.0, sample_rate, SM),+ speed: 1.0,+ };+ s.apply_params(true);+ s+ }++ fn apply_params(&mut self, snap: bool) {+ self.mix.set(self.pv.v("mix") / 100.0);+ self.width.set(self.pv.v("width") / 100.0);+ self.intensity.set(self.pv.v("intensity") / 100.0);+ self.speed = self.pv.v("speed");+ if snap {+ self.mix.snap();+ self.width.snap();+ self.intensity.snap();+ }+ }+}++impl AudioEffect for ChorusFlanger {+ param_plumbing!("chorus_flanger");+ fn reset(&mut self) {+ self.lines.iter_mut().for_each(DelayLine::reset);+ self.lfo.reset();+ self.fb.iter_mut().for_each(|v| *v = 0.0);+ self.fast.iter_mut().for_each(|e| e.env = 0.0);+ self.slow.iter_mut().for_each(|e| e.env = 0.0);+ self.mix.snap();+ self.width.snap();+ self.intensity.snap();+ }+ fn process(&mut self, channels: &mut [&mut [f32]]) {+ let n = block_len(channels);+ let nch = channels.len().min(self.lines.len());+ let flanger = self.pv.idx("mode") == 1;+ let trans = self.pv.v("transience") / 100.0;+ let ms = self.sr * 0.001;+ let (fa, fr, sa, sr_) = (coef(0.5, self.sr), coef(20.0, self.sr), coef(30.0, self.sr), coef(200.0, self.sr));+ for i in 0..n {+ let mix = self.mix.tick();+ let width = self.width.tick();+ let inten = self.intensity.tick();+ for ch in 0..nch {+ let x = channels[ch][i];+ let off = ch as f64 * 0.25;+ let line = &mut self.lines[ch];+ let wet = if flanger {+ let d = (0.3 + 4.7 * width * uni_tri(self.lfo.phase(off))) * ms;+ let y = line.read(d);+ self.fb[ch] = y;+ y+ } else {+ let mut acc = 0.0;+ for v in 0..3 {+ let d = (15.0 + 20.0 * width * uni_sine(self.lfo.phase(off + v as f64 / 3.0))) * ms;+ acc += line.read(d);+ }+ let y = acc / 3.0;+ self.fb[ch] = y;+ y+ };+ let g = if flanger { 0.95 * inten } else { 0.6 * inten };+ line.push(x + g * self.fb[ch]);+ let mut w = wet;+ if trans > 0.0 {+ let a = x.abs();+ let f = self.fast[ch].tick(fa, fr, a);+ let s = self.slow[ch].tick(sa, sr_, a);+ let boost = if s > 1e-9 { ((f - s) / s).clamp(0.0, 2.0) } else { 0.0 };+ w *= 1.0 + trans * boost;+ }+ channels[ch][i] = x + mix * (w - x);+ }+ self.lfo.advance(self.speed, self.sr);+ }+ }+}++// ------------------------------------------------------------------------------------ flanger++/// Classic flanger: the delay sweeps between the initial and final delay; stereo phasing+/// offsets the right channel's LFO; feedback, inverted and "special effects" (normal minus+/// inverted sweep) modes.+pub struct Flanger {+ pv: ParamValues,+ sr: f32,+ lines: Vec<DelayLine>,+ lfo: Lfo,+ d0: Smoothed,+ d1: Smoothed,+ fb: Smoothed,+ mix: Smoothed,+}++impl Flanger {+ pub const PARAMS: &'static [ParamSpec] = &[+ ParamSpec::log("initial_delay", "Initial Delay", 0.1, 20.0, 1.0, Unit::Milliseconds),+ ParamSpec::log("final_delay", "Final Delay", 0.1, 20.0, 5.0, Unit::Milliseconds),+ ParamSpec::new("stereo_phasing", "Stereo Phasing", 0.0, 180.0, 90.0, Unit::None),+ ParamSpec::new("feedback", "Feedback", -100.0, 100.0, 50.0, Unit::Percent),+ ParamSpec::log("rate", "Modulation Rate", 0.01, 10.0, 0.5, Unit::Hertz),+ ParamSpec::toggle("inverted", "Inverted", false),+ ParamSpec::toggle("special", "Special Effects", false),+ ParamSpec::toggle("sinusoidal", "Sinusoidal", true),+ ParamSpec::new("mix", "Mix", 0.0, 100.0, 50.0, Unit::Percent),+ ];++ pub fn new(sample_rate: f32, channels: usize) -> Self {+ let ch = channels.max(1);+ let sm = |v| Smoothed::with_ms(v, sample_rate, SM);+ let mut s = Flanger {+ pv: ParamValues::new(Self::PARAMS),+ sr: sample_rate,+ lines: vec![DelayLine::new((0.025 * sample_rate) as usize); ch],+ lfo: Lfo::default(),+ d0: sm(0.0),+ d1: sm(0.0),+ fb: sm(0.0),+ mix: sm(0.0),+ };+ s.apply_params(true);+ s+ }++ fn apply_params(&mut self, snap: bool) {+ let ms = self.sr * 0.001;+ self.d0.set(self.pv.v("initial_delay") * ms);+ self.d1.set(self.pv.v("final_delay") * ms);+ self.fb.set(0.95 * self.pv.v("feedback") / 100.0);+ self.mix.set(self.pv.v("mix") / 100.0);+ if snap {+ for s in [&mut self.d0, &mut self.d1, &mut self.fb, &mut self.mix] {+ s.snap();+ }+ }+ }+}++impl AudioEffect for Flanger {+ param_plumbing!("flanger");+ fn reset(&mut self) {+ self.lines.iter_mut().for_each(DelayLine::reset);+ self.lfo.reset();+ for s in [&mut self.d0, &mut self.d1, &mut self.fb, &mut self.mix] {+ s.snap();+ }+ }+ fn process(&mut self, channels: &mut [&mut [f32]]) {+ let n = block_len(channels);+ let nch = channels.len().min(self.lines.len());+ let sine = self.pv.on("sinusoidal");+ let inv = if self.pv.on("inverted") { -1.0 } else { 1.0 };+ let special = self.pv.on("special");+ let phasing = self.pv.v("stereo_phasing") as f64 / 360.0;+ let rate = self.pv.v("rate");+ let shape = |p: f64| if sine { uni_sine(p) } else { uni_tri(p) };+ for i in 0..n {+ let (d0, d1, fb, mix) = (self.d0.tick(), self.d1.tick(), self.fb.tick(), self.mix.tick());+ for ch in 0..nch {+ let x = channels[ch][i];+ let p = self.lfo.phase(if ch == 1 { phasing } else { 0.0 });+ let line = &mut self.lines[ch];+ let y = line.read(d0 + (d1 - d0) * shape(p));+ let wet = if special {+ let y2 = line.read(d0 + (d1 - d0) * shape((p + 0.5).rem_euclid(1.0)));+ 0.5 * (y - y2) + 0.5 * y+ } else {+ y+ };+ line.push(x + fb * y);+ channels[ch][i] = x + mix * (inv * wet - x);+ }+ self.lfo.advance(rate, self.sr);+ }+ }+}++// -------------------------------------------------------------------------------------- phaser++const MAX_STAGES: usize = 12;++/// Swept cascade of first-order all-pass stages with feedback.+pub struct Phaser {+ pv: ParamValues,+ sr: f32,+ ap: Vec<[AllPass1; MAX_STAGES]>,+ coefs: Vec<f64>,+ fbs: Vec<f64>,+ lfo: Lfo,+ counter: u32,+ intensity: Smoothed,+ mix: Smoothed,+ fb: Smoothed,+ out: Smoothed,+}++impl Phaser {+ pub const PARAMS: &'static [ParamSpec] = &[+ ParamSpec::new("stages", "Stages", 2.0, MAX_STAGES as f32, 4.0, Unit::None),+ ParamSpec::new("intensity", "Intensity", 0.0, 100.0, 100.0, Unit::Percent),+ ParamSpec::new("depth", "Depth", 0.0, 100.0, 70.0, Unit::Percent),+ ParamSpec::log("rate", "Modulation Rate", 0.01, 10.0, 0.5, Unit::Hertz),+ ParamSpec::new("phase_diff", "Phase Difference", 0.0, 180.0, 90.0, Unit::None),+ ParamSpec::log("upper_freq", "Upper Frequency", 100.0, 20000.0, 2500.0, Unit::Hertz),+ ParamSpec::new("feedback", "Feedback", -100.0, 100.0, 0.0, Unit::Percent),+ ParamSpec::new("mix", "Mix", 0.0, 100.0, 50.0, Unit::Percent),+ ParamSpec::new("output", "Output Gain", -24.0, 24.0, 0.0, Unit::Decibels),+ ];++ pub fn new(sample_rate: f32, channels: usize) -> Self {+ let ch = channels.max(1);+ let sm = |v| Smoothed::with_ms(v, sample_rate, SM);+ let mut s = Phaser {+ pv: ParamValues::new(Self::PARAMS),+ sr: sample_rate,+ ap: vec![[AllPass1::default(); MAX_STAGES]; ch],+ coefs: vec![0.0; ch],+ fbs: vec![0.0; ch],+ lfo: Lfo::default(),+ counter: 0,+ intensity: sm(0.0),+ mix: sm(0.0),+ fb: sm(0.0),+ out: sm(1.0),+ };+ s.apply_params(true);+ s+ }++ fn apply_params(&mut self, snap: bool) {+ self.intensity.set(self.pv.v("intensity") / 100.0);+ self.mix.set(self.pv.v("mix") / 100.0);+ self.fb.set(0.9 * self.pv.v("feedback") / 100.0);+ self.out.set(db_to_gain(self.pv.v("output")));+ if snap {+ for s in [&mut self.intensity, &mut self.mix, &mut self.fb, &mut self.out] {+ s.snap();+ }+ }+ }+}++impl AudioEffect for Phaser {+ param_plumbing!("phaser");+ fn reset(&mut self) {+ self.ap.iter_mut().for_each(|a| a.iter_mut().for_each(AllPass1::reset));+ self.fbs.iter_mut().for_each(|v| *v = 0.0);+ self.lfo.reset();+ self.counter = 0;+ for s in [&mut self.intensity, &mut self.mix, &mut self.fb, &mut self.out] {+ s.snap();+ }+ }+ fn process(&mut self, channels: &mut [&mut [f32]]) {+ let n = block_len(channels);+ let nch = channels.len().min(self.ap.len());+ let stages = ((self.pv.v("stages").round() as usize / 2) * 2).clamp(2, MAX_STAGES);+ let depth = self.pv.v("depth") / 100.0;+ let upper = self.pv.v("upper_freq");+ let diff = self.pv.v("phase_diff") as f64 / 360.0;+ let rate = self.pv.v("rate");+ for i in 0..n {+ if self.counter == 0 {+ for ch in 0..nch {+ let p = self.lfo.phase(if ch == 1 { diff } else { 0.0 });+ // Sweep down from the upper frequency by up to 6 octaves.+ let f = upper * 2f32.powf(-6.0 * depth * uni_sine(p));+ self.coefs[ch] = AllPass1::coef(f, self.sr);+ }+ }+ self.counter = (self.counter + 1) % 8;+ let (inten, mix, fb, out) = (self.intensity.tick(), self.mix.tick(), self.fb.tick() as f64, self.out.tick());+ for ch in 0..nch {+ let x = channels[ch][i];+ let a = self.coefs[ch];+ let mut y = x as f64 + fb * self.fbs[ch];+ for st in self.ap[ch].iter_mut().take(stages) {+ y = st.tick(a, y);+ }+ self.fbs[ch] = y;+ let wet = x + inten * (y as f32 - x);+ channels[ch][i] = (x + mix * (wet - x)) * out;+ }+ self.lfo.advance(rate, self.sr);+ }+ }+}++// -------------------------------------------------------------------------------- analog delay++pub const ANALOG_MODES: &[&str] = &["Tape", "Tape/Tube", "Analog"];++/// Delay with a coloured, saturating feedback path (tape / tape+tube / bucket-brigade style+/// low-pass and soft clipping) and stereo spread.+pub struct AnalogDelay {+ pv: ParamValues,+ sr: f32,+ lines: Vec<DelayLine>,+ lp: Vec<OnePole>,+ time: Smoothed,+ dry: Smoothed,+ wet: Smoothed,+ fb: Smoothed,+ drive: Smoothed,+ spread: Smoothed,+}++impl AnalogDelay {+ pub const MAX_MS: f32 = 8000.0;+ pub const PARAMS: &'static [ParamSpec] = &[+ ParamSpec::choice("mode", "Mode", ANALOG_MODES, 0),+ ParamSpec::new("dry", "Dry Out", 0.0, 100.0, 100.0, Unit::Percent),+ ParamSpec::new("wet", "Wet Out", 0.0, 100.0, 40.0, Unit::Percent),+ ParamSpec::log("delay", "Delay", 5.0, 8000.0, 250.0, Unit::Milliseconds),+ ParamSpec::new("feedback", "Feedback", 0.0, 200.0, 40.0, Unit::Percent),+ ParamSpec::new("trash", "Trash", 0.0, 200.0, 0.0, Unit::Percent),+ ParamSpec::new("spread", "Spread", 0.0, 200.0, 0.0, Unit::Percent),+ ];++ pub fn new(sample_rate: f32, channels: usize) -> Self {+ let ch = channels.max(1);+ let max = (Self::MAX_MS * 1.5 * 0.001 * sample_rate) as usize + 4;+ let sm = |v| Smoothed::with_ms(v, sample_rate, SM);+ let mut s = AnalogDelay {+ pv: ParamValues::new(Self::PARAMS),+ sr: sample_rate,+ lines: vec![DelayLine::new(max); ch],+ lp: vec![OnePole::default(); ch],+ time: Smoothed::with_ms(1.0, sample_rate, 100.0),+ dry: sm(1.0),+ wet: sm(0.0),+ fb: sm(0.0),+ drive: sm(1.0),+ spread: sm(0.0),+ };+ s.apply_params(true);+ s+ }++ fn apply_params(&mut self, snap: bool) {+ self.time.set(self.pv.v("delay") * 0.001 * self.sr);+ self.dry.set(self.pv.v("dry") / 100.0);+ self.wet.set(self.pv.v("wet") / 100.0);+ self.fb.set(self.pv.v("feedback") / 100.0);+ self.drive.set(1.0 + 4.0 * self.pv.v("trash") / 100.0);+ self.spread.set(self.pv.v("spread") / 100.0);+ if snap {+ for s in [&mut self.time, &mut self.dry, &mut self.wet, &mut self.fb, &mut self.drive, &mut self.spread] {+ s.snap();+ }+ }+ }+}++impl AudioEffect for AnalogDelay {+ param_plumbing!("analog_delay");+ fn reset(&mut self) {+ self.lines.iter_mut().for_each(DelayLine::reset);+ self.lp.iter_mut().for_each(OnePole::reset);+ for s in [&mut self.time, &mut self.dry, &mut self.wet, &mut self.fb, &mut self.drive, &mut self.spread] {+ s.snap();+ }+ }+ fn process(&mut self, channels: &mut [&mut [f32]]) {+ let n = block_len(channels);+ let nch = channels.len().min(self.lines.len());+ let mode = self.pv.idx("mode");+ let cutoff = [6500.0, 5000.0, 3200.0][mode.min(2)];+ let a = OnePole::alpha(cutoff, self.sr);+ for i in 0..n {+ let (t, dry, wet, fb, drive, spread) = (self.time.tick(), self.dry.tick(), self.wet.tick(), self.fb.tick(), self.drive.tick(), self.spread.tick());+ for ch in 0..nch {+ let x = channels[ch][i];+ let side = match (nch, ch) {+ (1, _) => 0.0,+ (_, 0) => -0.25,+ _ => 0.25,+ };+ let d = t * (1.0 + side * spread);+ let line = &mut self.lines[ch];+ let y = line.read(d - 1.0);+ let c = self.lp[ch].lp(a, y) * drive;+ let sat = match mode {+ 0 => c.tanh(),+ 1 => (c + 0.2).tanh() - 0.2f32.tanh(),+ _ => c / (1.0 + c.abs()),+ } / drive;+ line.push(x + fb * sat);+ channels[ch][i] = dry * x + wet * y;+ }+ }+ }+}++// ------------------------------------------------------------------------------- multitap delay++const TAPS: usize = 4;+const TAP_IDS: [[&str; 3]; TAPS] =+ [["delay1", "feedback1", "level1"], ["delay2", "feedback2", "level2"], ["delay3", "feedback3", "level3"], ["delay4", "feedback4", "level4"]];++/// Four independent feedback delay taps mixed into one wet signal.+pub struct MultitapDelay {+ pv: ParamValues,+ sr: f32,+ /// `[channel * TAPS + tap]`.+ lines: Vec<DelayLine>,+ time: [Smoothed; TAPS],+ fb: [Smoothed; TAPS],+ level: [Smoothed; TAPS],+ mix: Smoothed,+}++impl MultitapDelay {+ pub const MAX_MS: f32 = 4000.0;+ pub const PARAMS: &'static [ParamSpec] = &[+ ParamSpec::log("delay1", "Delay 1", 1.0, 4000.0, 250.0, Unit::Milliseconds),+ ParamSpec::new("feedback1", "Feedback 1", 0.0, 95.0, 0.0, Unit::Percent),+ ParamSpec::new("level1", "Level 1", -96.0, 0.0, -6.0, Unit::Decibels),+ ParamSpec::log("delay2", "Delay 2", 1.0, 4000.0, 500.0, Unit::Milliseconds),+ ParamSpec::new("feedback2", "Feedback 2", 0.0, 95.0, 0.0, Unit::Percent),+ ParamSpec::new("level2", "Level 2", -96.0, 0.0, -9.0, Unit::Decibels),+ ParamSpec::log("delay3", "Delay 3", 1.0, 4000.0, 750.0, Unit::Milliseconds),+ ParamSpec::new("feedback3", "Feedback 3", 0.0, 95.0, 0.0, Unit::Percent),+ ParamSpec::new("level3", "Level 3", -96.0, 0.0, -12.0, Unit::Decibels),+ ParamSpec::log("delay4", "Delay 4", 1.0, 4000.0, 1000.0, Unit::Milliseconds),+ ParamSpec::new("feedback4", "Feedback 4", 0.0, 95.0, 0.0, Unit::Percent),+ ParamSpec::new("level4", "Level 4", -96.0, 0.0, -15.0, Unit::Decibels),+ ParamSpec::new("mix", "Mix", 0.0, 100.0, 50.0, Unit::Percent),+ ];++ pub fn new(sample_rate: f32, channels: usize) -> Self {+ let ch = channels.max(1);+ let max = (Self::MAX_MS * 0.001 * sample_rate) as usize + 4;+ let sm = |v| Smoothed::with_ms(v, sample_rate, SM);+ let tm = || Smoothed::with_ms(1.0, sample_rate, 100.0);+ let mut s = MultitapDelay {+ pv: ParamValues::new(Self::PARAMS),+ sr: sample_rate,+ lines: vec![DelayLine::new(max); ch * TAPS],+ time: [tm(), tm(), tm(), tm()],+ fb: [sm(0.0), sm(0.0), sm(0.0), sm(0.0)],+ level: [sm(0.0), sm(0.0), sm(0.0), sm(0.0)],+ mix: sm(0.0),+ };+ s.apply_params(true);+ s+ }++ fn apply_params(&mut self, snap: bool) {+ for (k, ids) in TAP_IDS.iter().enumerate() {+ self.time[k].set(self.pv.v(ids[0]) * 0.001 * self.sr);+ self.fb[k].set(self.pv.v(ids[1]) / 100.0);+ let l = self.pv.v(ids[2]);+ self.level[k].set(if l <= -96.0 { 0.0 } else { db_to_gain(l) });+ }+ self.mix.set(self.pv.v("mix") / 100.0);+ if snap {+ self.snap();+ }+ }++ fn snap(&mut self) {+ for k in 0..TAPS {+ self.time[k].snap();+ self.fb[k].snap();+ self.level[k].snap();+ }+ self.mix.snap();+ }+}++impl AudioEffect for MultitapDelay {+ param_plumbing!("multitap_delay");+ fn reset(&mut self) {+ self.lines.iter_mut().for_each(DelayLine::reset);+ self.snap();+ }+ fn process(&mut self, channels: &mut [&mut [f32]]) {+ let n = block_len(channels);+ let nch = channels.len().min(self.lines.len() / TAPS);+ for i in 0..n {+ let mut t = [0.0f32; TAPS];+ let mut fb = [0.0f32; TAPS];+ let mut lv = [0.0f32; TAPS];+ for k in 0..TAPS {+ t[k] = self.time[k].tick();+ fb[k] = self.fb[k].tick();+ lv[k] = self.level[k].tick();+ }+ let mix = self.mix.tick();+ for ch in 0..nch {+ let x = channels[ch][i];+ let mut wet = 0.0;+ for k in 0..TAPS {+ let line = &mut self.lines[ch * TAPS + k];+ let y = line.read(t[k] - 1.0);+ line.push(x + fb[k] * y);+ wet += lv[k] * y;+ }+ channels[ch][i] = x + mix * (wet - x);+ }+ }+ }+}diff --git a/crates/audio-dsp/src/effects/multiband.rs b/crates/audio-dsp/src/effects/multiband.rsnew file mode 100644index 000000000..16b2472ea--- /dev/null+++ b/crates/audio-dsp/src/effects/multiband.rs@@ -0,0 +1,621 @@+//! Dynamics rack ("Dynamics": auto gate → expander → compressor → limiter), the four-band+//! Multiband Compressor (Linkwitz–Riley crossovers with all-pass phase compensation, so the+//! bands sum to an all-pass) and the Tube-modeled Compressor.++use super::dynamics::{compressor_curve, expander_curve};+use super::util::{coef, lin_db};+use crate::biquad::{Biquad, Coeffs, FilterType};+use crate::{AudioEffect, ParamSpec, ParamValues, Smoothed, Unit, block_len, db_to_gain, param_plumbing};++/// Attenuation of a closed gate (dB).+const GATE_RANGE: f32 = 80.0;+/// Most expander attenuation (dB).+const EXP_RANGE: f32 = 60.0;++#[inline]+fn smooth(env: &mut f32, target: f32, att: f32, rel: f32) {+ // Gains in dB (≤ 0): falling = attack, rising = release.+ let c = if target < *env { att } else { rel };+ *env = c * *env + (1.0 - c) * target;+ if env.abs() < 1e-7 {+ *env = 0.0;+ }+}++/// Cubic soft clipper with ceiling `t` (linear): identity below t/2, smooth to exactly ±t.+#[inline]+pub fn soft_clip(x: f32, t: f32) -> f32 {+ let k = 0.5 * t;+ let a = x.abs();+ if a <= k {+ x+ } else {+ // Quadratic blend from slope 1 at k to slope 0 at 2t − k… normalised to reach t.+ let u = ((a - k) / (2.0 * (t - k))).min(1.0);+ let y = k + (t - k) * (2.0 * u - u * u);+ y.copysign(x)+ }+}++// --------------------------------------------------------------------------------- dynamics++/// Premiere-style Dynamics: Auto Gate, Compressor, Expander and Limiter sections in series+/// (stereo-linked peak detection), plus output gain.+pub struct DynamicsRack {+ pv: ParamValues,+ sr: f32,+ gate_env: f32,+ gate_hold: u32,+ exp_env: f32,+ comp_env: f32,+ lim_env: f32,+ out: Smoothed,+ /// Cached coefficients.+ c: [f32; 8],+ hold: u32,+}++impl DynamicsRack {+ pub const PARAMS: &'static [ParamSpec] = &[+ ParamSpec::toggle("gate_on", "Auto Gate", false),+ ParamSpec::new("gate_threshold", "Gate Threshold", -80.0, 0.0, -50.0, Unit::Decibels),+ ParamSpec::log("gate_attack", "Gate Attack", 0.1, 100.0, 2.0, Unit::Milliseconds),+ ParamSpec::log("gate_release", "Gate Release", 1.0, 3000.0, 100.0, Unit::Milliseconds),+ ParamSpec::new("gate_hold", "Gate Hold", 0.0, 1000.0, 50.0, Unit::Milliseconds),+ ParamSpec::toggle("comp_on", "Compressor", true),+ ParamSpec::new("comp_threshold", "Compressor Threshold", -60.0, 0.0, -20.0, Unit::Decibels),+ ParamSpec::new("comp_ratio", "Compressor Ratio", 1.0, 30.0, 2.0, Unit::Ratio),+ ParamSpec::log("comp_attack", "Compressor Attack", 0.1, 300.0, 10.0, Unit::Milliseconds),+ ParamSpec::log("comp_release", "Compressor Release", 1.0, 3000.0, 100.0, Unit::Milliseconds),+ ParamSpec::toggle("comp_auto", "Auto Makeup", false),+ ParamSpec::new("comp_makeup", "Compressor Makeup", 0.0, 30.0, 0.0, Unit::Decibels),+ ParamSpec::toggle("exp_on", "Expander", false),+ ParamSpec::new("exp_threshold", "Expander Threshold", -80.0, 0.0, -60.0, Unit::Decibels),+ ParamSpec::new("exp_ratio", "Expander Ratio", 1.0, 30.0, 2.0, Unit::Ratio),+ ParamSpec::toggle("lim_on", "Limiter", false),+ ParamSpec::new("lim_threshold", "Limiter Threshold", -30.0, 0.0, -1.0, Unit::Decibels),+ ParamSpec::log("lim_release", "Limiter Release", 1.0, 1000.0, 50.0, Unit::Milliseconds),+ ParamSpec::toggle("soft_clip", "Soft Clip", false),+ ParamSpec::new("output", "Output Gain", -30.0, 30.0, 0.0, Unit::Decibels),+ ];++ pub fn new(sample_rate: f32, _channels: usize) -> Self {+ let mut s = DynamicsRack {+ pv: ParamValues::new(Self::PARAMS),+ sr: sample_rate,+ gate_env: 0.0,+ gate_hold: 0,+ exp_env: 0.0,+ comp_env: 0.0,+ lim_env: 0.0,+ out: Smoothed::with_ms(1.0, sample_rate, 20.0),+ c: [0.0; 8],+ hold: 0,+ };+ s.apply_params(true);+ s+ }++ fn apply_params(&mut self, snap: bool) {+ let p = &self.pv;+ let sr = self.sr;+ self.c = [+ coef(p.v("gate_attack"), sr),+ coef(p.v("gate_release"), sr),+ coef(1.0, sr),+ coef(80.0, sr),+ coef(p.v("comp_attack"), sr),+ coef(p.v("comp_release"), sr),+ 0.0,+ coef(p.v("lim_release"), sr),+ ];+ self.hold = (p.v("gate_hold") * 0.001 * sr) as u32;+ self.out.set(db_to_gain(p.v("output") + self.makeup_db()));+ if snap {+ self.out.snap();+ }+ }++ fn makeup_db(&self) -> f32 {+ let p = &self.pv;+ if !p.on("comp_on") {+ return 0.0;+ }+ let auto = if p.on("comp_auto") {+ let (t, r) = (p.v("comp_threshold"), p.v("comp_ratio"));+ -0.5 * t * (1.0 - 1.0 / r)+ } else {+ 0.0+ };+ p.v("comp_makeup") + auto+ }++ /// Static gain (dB) of the enabled sections for a detector level, before make-up/output.+ fn static_gain(&self, level: f32) -> f32 {+ let p = &self.pv;+ let mut l = level;+ if p.on("gate_on") && l < p.v("gate_threshold") {+ l -= GATE_RANGE;+ }+ if p.on("exp_on") {+ l = expander_curve(l, p.v("exp_threshold"), p.v("exp_ratio"), EXP_RANGE);+ }+ if p.on("comp_on") {+ l = compressor_curve(l, p.v("comp_threshold"), p.v("comp_ratio"), 0.0);+ }+ if p.on("lim_on") {+ l = l.min(p.v("lim_threshold"));+ }+ l - level+ }+}++impl AudioEffect for DynamicsRack {+ param_plumbing!("dynamics_rack");+ fn transfer_db(&self, band: usize, input_db: f32) -> Option<f32> {+ (band == 0).then(|| input_db + self.static_gain(input_db) + self.pv.v("output") + self.makeup_db())+ }+ fn reset(&mut self) {+ self.gate_env = 0.0;+ self.gate_hold = 0;+ self.exp_env = 0.0;+ self.comp_env = 0.0;+ self.lim_env = 0.0;+ self.out.snap();+ }+ fn process(&mut self, channels: &mut [&mut [f32]]) {+ let n = block_len(channels);+ let p = &self.pv;+ let (gate_on, gt) = (p.on("gate_on"), p.v("gate_threshold"));+ let (exp_on, et, er) = (p.on("exp_on"), p.v("exp_threshold"), p.v("exp_ratio"));+ let (comp_on, ct, cr) = (p.on("comp_on"), p.v("comp_threshold"), p.v("comp_ratio"));+ let (lim_on, lt) = (p.on("lim_on"), p.v("lim_threshold"));+ let clip = p.on("soft_clip");+ let ceiling = db_to_gain(lt);+ let c = self.c;+ for i in 0..n {+ let peak = channels.iter().fold(0.0f32, |a, ch| a.max(ch[i].abs()));+ let mut l = lin_db(peak);+ let mut g = 0.0f32;+ if gate_on {+ let target = if l < gt { -GATE_RANGE } else { 0.0 };+ if target >= 0.0 {+ self.gate_hold = self.hold;+ smooth(&mut self.gate_env, 0.0, c[1], c[0]);+ } else if self.gate_hold > 0 {+ self.gate_hold -= 1;+ } else {+ smooth(&mut self.gate_env, target, c[1], c[1]);+ }+ g += self.gate_env;+ l += self.gate_env;+ }+ if exp_on {+ let target = expander_curve(l, et, er, EXP_RANGE) - l;+ smooth(&mut self.exp_env, target, c[2], c[3]);+ g += self.exp_env;+ l += self.exp_env;+ }+ if comp_on {+ let target = compressor_curve(l, ct, cr, 0.0) - l;+ smooth(&mut self.comp_env, target, c[4], c[5]);+ g += self.comp_env;+ l += self.comp_env;+ }+ if lim_on {+ let target = (lt - l).min(0.0);+ if target < self.lim_env {+ self.lim_env = target;+ } else {+ smooth(&mut self.lim_env, target, 0.0, c[7]);+ }+ g += self.lim_env;+ }+ let gain = db_to_gain(g);+ let o = self.out.tick();+ for ch in channels.iter_mut() {+ let mut y = ch[i] * gain;+ if lim_on {+ y = if clip { soft_clip(y, ceiling) } else { y.clamp(-ceiling, ceiling) };+ }+ ch[i] = y * o;+ }+ }+ }+}++// ----------------------------------------------------------------------- multiband compressor++/// Number of bands.+pub const MB_BANDS: usize = 4;++macro_rules! mb_band {+ ($n:literal) => {+ [+ ParamSpec::new(concat!("b", $n, "_threshold"), concat!("Band ", $n, " Threshold"), -60.0, 0.0, -18.0, Unit::Decibels),+ ParamSpec::new(concat!("b", $n, "_ratio"), concat!("Band ", $n, " Ratio"), 1.0, 30.0, 3.0, Unit::Ratio),+ ParamSpec::log(concat!("b", $n, "_attack"), concat!("Band ", $n, " Attack"), 0.1, 500.0, 10.0, Unit::Milliseconds),+ ParamSpec::log(concat!("b", $n, "_release"), concat!("Band ", $n, " Release"), 1.0, 5000.0, 100.0, Unit::Milliseconds),+ ParamSpec::new(concat!("b", $n, "_gain"), concat!("Band ", $n, " Gain"), -18.0, 18.0, 0.0, Unit::Decibels),+ ParamSpec::toggle(concat!("b", $n, "_solo"), concat!("Band ", $n, " Solo"), false),+ ParamSpec::toggle(concat!("b", $n, "_bypass"), concat!("Band ", $n, " Bypass"), false),+ ]+ };+}++const fn mb_params() -> [ParamSpec; 3 + 4 * 7 + 5] {+ let head = [+ ParamSpec::log("xo1", "Low Crossover", 20.0, 1000.0, 120.0, Unit::Hertz),+ ParamSpec::log("xo2", "Mid Crossover", 100.0, 8000.0, 2000.0, Unit::Hertz),+ ParamSpec::log("xo3", "High Crossover", 1000.0, 20000.0, 10000.0, Unit::Hertz),+ ];+ let bands = [mb_band!("1"), mb_band!("2"), mb_band!("3"), mb_band!("4")];+ let tail = [+ ParamSpec::new("output", "Output Gain", -18.0, 18.0, 0.0, Unit::Decibels),+ ParamSpec::toggle("lim_on", "Limiter", false),+ ParamSpec::new("lim_threshold", "Limiter Threshold", -30.0, 0.0, -0.1, Unit::Decibels),+ ParamSpec::log("lim_release", "Limiter Release", 1.0, 1000.0, 50.0, Unit::Milliseconds),+ ParamSpec::toggle("link", "Link Channels", true),+ ];+ let mut out = [ParamSpec::new("", "", 0.0, 0.0, 0.0, Unit::None); 3 + 4 * 7 + 5];+ let mut i = 0;+ while i < 3 {+ out[i] = head[i];+ i += 1;+ }+ let mut b = 0;+ while b < 4 {+ let mut k = 0;+ while k < 7 {+ out[3 + b * 7 + k] = bands[b][k];+ k += 1;+ }+ b += 1;+ }+ let mut t = 0;+ while t < 5 {+ out[31 + t] = tail[t];+ t += 1;+ }+ out+}++const MB_PARAMS: [ParamSpec; 36] = mb_params();++/// Parameter ids of band `b` (0-based): threshold, ratio, attack, release, gain, solo, bypass.+pub const MB_IDS: [[&str; 7]; MB_BANDS] = [+ ["b1_threshold", "b1_ratio", "b1_attack", "b1_release", "b1_gain", "b1_solo", "b1_bypass"],+ ["b2_threshold", "b2_ratio", "b2_attack", "b2_release", "b2_gain", "b2_solo", "b2_bypass"],+ ["b3_threshold", "b3_ratio", "b3_attack", "b3_release", "b3_gain", "b3_solo", "b3_bypass"],+ ["b4_threshold", "b4_ratio", "b4_attack", "b4_release", "b4_gain", "b4_solo", "b4_bypass"],+];++/// Per-channel crossover filter state.+#[derive(Clone, Copy, Debug, Default)]+struct XoState {+ lp1: [Biquad; 2],+ hp1: [Biquad; 2],+ lp2: [Biquad; 2],+ hp2: [Biquad; 2],+ lp3: [Biquad; 2],+ hp3: [Biquad; 2],+ /// Phase compensation: band 1 through AP(f2), AP(f3); band 2 through AP(f3).+ ap1_2: Biquad,+ ap1_3: Biquad,+ ap2_3: Biquad,+}++#[derive(Clone, Copy, Debug)]+struct XoCoeffs {+ lp: [Coeffs; 3],+ hp: [Coeffs; 3],+ ap: [Coeffs; 3],+}++/// Four-band compressor with LR4 crossovers.+pub struct MultibandCompressor {+ pv: ParamValues,+ sr: f32,+ xo: [Smoothed; 3],+ xc: XoCoeffs,+ state: Vec<XoState>,+ /// Gain-reduction envelopes (dB), `[channel][band]` (channel 0 is used when linked).+ env: Vec<[f32; MB_BANDS]>,+ lim_env: f32,+ band_gain: [Smoothed; MB_BANDS],+ out: Smoothed,+ att: [f32; MB_BANDS],+ rel: [f32; MB_BANDS],+ lim_rel: f32,+ counter: u32,+}++const Q_BW: f64 = std::f64::consts::FRAC_1_SQRT_2;++impl MultibandCompressor {+ pub const PARAMS: &'static [ParamSpec] = &MB_PARAMS;++ pub fn new(sample_rate: f32, channels: usize) -> Self {+ let sm = |v: f32| Smoothed::with_ms(v, sample_rate, 30.0);+ let mut s = MultibandCompressor {+ pv: ParamValues::new(Self::PARAMS),+ sr: sample_rate,+ xo: [sm(1.0), sm(1.0), sm(1.0)],+ xc: XoCoeffs { lp: [Coeffs::IDENTITY; 3], hp: [Coeffs::IDENTITY; 3], ap: [Coeffs::IDENTITY; 3] },+ state: vec![XoState::default(); channels.max(1)],+ env: vec![[0.0; MB_BANDS]; channels.max(1)],+ lim_env: 0.0,+ band_gain: [sm(1.0), sm(1.0), sm(1.0), sm(1.0)],+ out: sm(1.0),+ att: [0.0; MB_BANDS],+ rel: [0.0; MB_BANDS],+ lim_rel: 0.0,+ counter: 0,+ };+ s.apply_params(true);+ s+ }++ /// Crossover frequencies (Hz) at the current settings, kept strictly increasing.+ pub fn crossovers(&self) -> [f32; 3] {+ let a = self.pv.v("xo1");+ let b = self.pv.v("xo2").max(a * 1.25);+ let c = self.pv.v("xo3").max(b * 1.25).min(self.sr * 0.45);+ [a, b.min(c / 1.25), c]+ }++ fn update_xo(&mut self) {+ let sr = self.sr as f64;+ for k in 0..3 {+ let f = 2f64.powf(self.xo[k].value() as f64);+ self.xc.lp[k] = Coeffs::design(FilterType::LowPass, sr, f, Q_BW, 0.0);+ self.xc.hp[k] = Coeffs::design(FilterType::HighPass, sr, f, Q_BW, 0.0);+ self.xc.ap[k] = Coeffs::design(FilterType::AllPass, sr, f, Q_BW, 0.0);+ }+ }++ fn apply_params(&mut self, snap: bool) {+ let xo = self.crossovers();+ for k in 0..3 {+ self.xo[k].set(xo[k].log2());+ }+ for b in 0..MB_BANDS {+ let ids = MB_IDS[b];+ self.att[b] = coef(self.pv.v(ids[2]), self.sr);+ self.rel[b] = coef(self.pv.v(ids[3]), self.sr);+ self.band_gain[b].set(self.band_level(b));+ }+ self.lim_rel = coef(self.pv.v("lim_release"), self.sr);+ self.out.set(db_to_gain(self.pv.v("output")));+ if snap {+ self.xo.iter_mut().for_each(Smoothed::snap);+ self.band_gain.iter_mut().for_each(Smoothed::snap);+ self.out.snap();+ self.update_xo();+ }+ }++ /// Linear output level of band `b` from its gain, solo and bypass switches.+ fn band_level(&self, b: usize) -> f32 {+ let any_solo = MB_IDS.iter().any(|ids| self.pv.on(ids[5]));+ let ids = MB_IDS[b];+ if any_solo && !self.pv.on(ids[5]) {+ return 0.0;+ }+ if self.pv.on(ids[6]) { 1.0 } else { db_to_gain(self.pv.v(ids[4])) }+ }++ #[inline]+ fn split(st: &mut XoState, c: &XoCoeffs, x: f64) -> [f64; MB_BANDS] {+ let lr = |f: &mut [Biquad; 2], co: &Coeffs, v: f64| {+ let u = f[0].tick(co, v);+ f[1].tick(co, u)+ };+ let b1 = lr(&mut st.lp1, &c.lp[0], x);+ let r1 = lr(&mut st.hp1, &c.hp[0], x);+ let b1 = st.ap1_3.tick(&c.ap[2], st.ap1_2.tick(&c.ap[1], b1));+ let b2 = lr(&mut st.lp2, &c.lp[1], r1);+ let r2 = lr(&mut st.hp2, &c.hp[1], r1);+ let b2 = st.ap2_3.tick(&c.ap[2], b2);+ let b3 = lr(&mut st.lp3, &c.lp[2], r2);+ let b4 = lr(&mut st.hp3, &c.hp[2], r2);+ [b1, b2, b3, b4]+ }+}++impl AudioEffect for MultibandCompressor {+ param_plumbing!("multiband_compressor");+ fn transfer_db(&self, band: usize, input_db: f32) -> Option<f32> {+ let ids = MB_IDS.get(band)?;+ if self.pv.on(ids[6]) {+ return Some(input_db);+ }+ Some(compressor_curve(input_db, self.pv.v(ids[0]), self.pv.v(ids[1]), 0.0) + self.pv.v(ids[4]))+ }+ fn reset(&mut self) {+ self.xo.iter_mut().for_each(Smoothed::snap);+ self.band_gain.iter_mut().for_each(Smoothed::snap);+ self.out.snap();+ self.update_xo();+ self.state.iter_mut().for_each(|s| *s = XoState::default());+ self.env.iter_mut().for_each(|e| *e = [0.0; MB_BANDS]);+ self.lim_env = 0.0;+ self.counter = 0;+ }+ fn process(&mut self, channels: &mut [&mut [f32]]) {+ let n = block_len(channels);+ let nch = channels.len().min(self.state.len());+ let link = self.pv.on("link");+ let lim_on = self.pv.on("lim_on");+ let lt = self.pv.v("lim_threshold");+ let ceiling = db_to_gain(lt);+ let mut thr = [0.0f32; MB_BANDS];+ let mut ratio = [1.0f32; MB_BANDS];+ let mut byp = [false; MB_BANDS];+ for b in 0..MB_BANDS {+ thr[b] = self.pv.v(MB_IDS[b][0]);+ ratio[b] = self.pv.v(MB_IDS[b][1]);+ byp[b] = self.pv.on(MB_IDS[b][6]);+ }+ let mut bands = [[0.0f64; MB_BANDS]; 8];+ for i in 0..n {+ if self.counter == 0 && self.xo.iter().any(Smoothed::is_smoothing) {+ self.update_xo();+ }+ self.counter = (self.counter + 1) % 16;+ for x in &mut self.xo {+ x.tick();+ }+ let mut bg = [0.0f32; MB_BANDS];+ for b in 0..MB_BANDS {+ bg[b] = self.band_gain[b].tick();+ }+ let o = self.out.tick();+ for ch in 0..nch.min(8) {+ bands[ch] = Self::split(&mut self.state[ch], &self.xc, channels[ch][i] as f64);+ }+ // Detection (per band; linked = loudest channel drives all).+ let mut gains = [[1.0f32; MB_BANDS]; 8];+ for b in 0..MB_BANDS {+ if byp[b] {+ continue;+ }+ if link {+ let peak = (0..nch.min(8)).fold(0.0f32, |a, ch| a.max(bands[ch][b].abs() as f32));+ let l = lin_db(peak);+ let target = compressor_curve(l, thr[b], ratio[b], 0.0) - l;+ smooth(&mut self.env[0][b], target, self.att[b], self.rel[b]);+ let g = db_to_gain(self.env[0][b]);+ for gc in gains.iter_mut().take(nch.min(8)) {+ gc[b] = g;+ }+ } else {+ for ch in 0..nch.min(8) {+ let l = lin_db(bands[ch][b].abs() as f32);+ let target = compressor_curve(l, thr[b], ratio[b], 0.0) - l;+ smooth(&mut self.env[ch][b], target, self.att[b], self.rel[b]);+ gains[ch][b] = db_to_gain(self.env[ch][b]);+ }+ }+ }+ let mut ys = [0.0f32; 8];+ for ch in 0..nch.min(8) {+ let mut y = 0.0f64;+ for b in 0..MB_BANDS {+ y += bands[ch][b] * (gains[ch][b] * bg[b]) as f64;+ }+ ys[ch] = y as f32 * o;+ }+ if lim_on {+ let peak = ys[..nch.min(8)].iter().fold(0.0f32, |a, v| a.max(v.abs()));+ let target = (lt - lin_db(peak)).min(0.0);+ if target < self.lim_env {+ self.lim_env = target;+ } else {+ smooth(&mut self.lim_env, target, 0.0, self.lim_rel);+ }+ let g = db_to_gain(self.lim_env);+ for y in ys.iter_mut().take(nch.min(8)) {+ *y = (*y * g).clamp(-ceiling, ceiling);+ }+ }+ for ch in 0..nch.min(8) {+ channels[ch][i] = ys[ch];+ }+ }+ }+}++// --------------------------------------------------------------------- tube-modeled compressor++/// Compressor with an RMS detector, wide soft knee, program-dependent release and a gentle+/// symmetric tube-style saturation stage (`tanh(kx)/k`, k = ½: −0.2 dB at −6 dBFS).+pub struct TubeCompressor {+ pv: ParamValues,+ sr: f32,+ ms: f32,+ env: f32,+ slow: f32,+ att: f32,+ rel: f32,+ rms_c: f32,+ out: Smoothed,+}++const TUBE_K: f32 = 0.5;+const TUBE_KNEE: f32 = 10.0;++impl TubeCompressor {+ pub const PARAMS: &'static [ParamSpec] = &[+ ParamSpec::new("threshold", "Threshold", -60.0, 0.0, -20.0, Unit::Decibels),+ ParamSpec::new("ratio", "Ratio", 1.0, 30.0, 4.0, Unit::Ratio),+ ParamSpec::log("attack", "Attack", 0.1, 500.0, 10.0, Unit::Milliseconds),+ ParamSpec::log("release", "Release", 1.0, 5000.0, 100.0, Unit::Milliseconds),+ ParamSpec::new("output", "Output Gain", -30.0, 30.0, 0.0, Unit::Decibels),+ ];++ pub fn new(sample_rate: f32, _channels: usize) -> Self {+ let mut s = TubeCompressor {+ pv: ParamValues::new(Self::PARAMS),+ sr: sample_rate,+ ms: 0.0,+ env: 0.0,+ slow: 0.0,+ att: 0.0,+ rel: 0.0,+ rms_c: coef(5.0, sample_rate),+ out: Smoothed::with_ms(1.0, sample_rate, 20.0),+ };+ s.apply_params(true);+ s+ }++ fn apply_params(&mut self, snap: bool) {+ self.att = coef(self.pv.v("attack"), self.sr);+ self.rel = coef(self.pv.v("release"), self.sr);+ self.out.set(db_to_gain(self.pv.v("output")));+ if snap {+ self.out.snap();+ }+ }+}++impl AudioEffect for TubeCompressor {+ param_plumbing!("tube_compressor");+ fn transfer_db(&self, band: usize, input_db: f32) -> Option<f32> {+ (band == 0).then(|| compressor_curve(input_db, self.pv.v("threshold"), self.pv.v("ratio"), TUBE_KNEE) + self.pv.v("output"))+ }+ fn reset(&mut self) {+ self.ms = 0.0;+ self.env = 0.0;+ self.slow = 0.0;+ self.out.snap();+ }+ fn process(&mut self, channels: &mut [&mut [f32]]) {+ let n = block_len(channels);+ let (t, r) = (self.pv.v("threshold"), self.pv.v("ratio"));+ let slow_c = coef(1500.0, self.sr);+ for i in 0..n {+ let sq = channels.iter().fold(0.0f32, |a, ch| a.max(ch[i] * ch[i]));+ self.ms = self.rms_c * self.ms + (1.0 - self.rms_c) * sq;+ if self.ms < 1e-30 {+ self.ms = 0.0;+ }+ let l = 10.0 * self.ms.max(1e-20).log10();+ let target = compressor_curve(l, t, r, TUBE_KNEE) - l;+ // Program-dependent release: long, sustained reduction releases more slowly.+ self.slow = slow_c * self.slow + (1.0 - slow_c) * self.env;+ if self.slow.abs() < 1e-7 {+ self.slow = 0.0;+ }+ let rel = self.rel + (self.slow / -20.0).clamp(0.0, 1.0) * (1.0 - self.rel) * 0.5;+ smooth(&mut self.env, target, self.att, rel.min(0.999_999));+ let g = db_to_gain(self.env);+ let o = self.out.tick();+ for buf in channels.iter_mut() {+ let y = buf[i] * g;+ buf[i] = (TUBE_K * y).tanh() / TUBE_K * o;+ }+ }+ }+}diff --git a/crates/audio-dsp/src/effects/premiere_tests.rs b/crates/audio-dsp/src/effects/premiere_tests.rsnew file mode 100644index 000000000..65fef0677--- /dev/null+++ b/crates/audio-dsp/src/effects/premiere_tests.rs@@ -0,0 +1,553 @@+//! Behavioural tests of the Premiere audio-effect set: neutral settings are (delayed)+//! identity, output is deterministic, latency is constant and correct, and each effect does+//! what it says on generated signals (tones, noise, impulses), plus a realtime-factor check.++use super::*;+use crate::AudioEffect;+use crate::testutil::*;++const SR: f32 = 48000.0;++fn noise(seed: u64, n: usize, amp: f32) -> Vec<f32> {+ let mut r = Rng::new(seed);+ (0..n).map(|_| r.uniform() * amp).collect()+}++fn fx(id: &str, params: &[(&str, f32)]) -> Box<dyn AudioEffect> {+ let mut e = create_effect(id, SR, 2).unwrap_or_else(|| panic!("no effect {id}"));+ for (p, v) in params {+ assert!(e.set_param(p, *v), "{id}.{p}");+ }+ e.reset();+ e+}++fn run(e: &mut dyn AudioEffect, l: &[f32], r: &[f32]) -> (Vec<f32>, Vec<f32>) {+ let (mut a, mut b) = (l.to_vec(), r.to_vec());+ e.process(&mut [&mut a, &mut b]);+ (a, b)+}++/// Steady-state amplitude (relative, dB) of a tone through the effect (second half measured,+/// latency ignored because the tone is stationary).+fn tone_db(e: &mut dyn AudioEffect, freq: f64, amp: f32) -> f64 {+ e.reset();+ let n = SR as usize;+ let x = sine(freq, amp as f64, SR as f64, n, 0.0);+ let (y, _) = run(e, &x, &x);+ db(tone_amplitude(&y[n / 2..], freq, SR as f64) / amp as f64)+}++/// Settings under which each effect must pass audio through unchanged (apart from latency).+fn neutral(id: &str) -> Option<Vec<(&'static str, f32)>> {+ Some(match id {+ "graphic_eq_10" | "graphic_eq_20" | "graphic_eq_30" | "notch_filter" | "channel_mixer" | "stereo_expander" | "ambisonics_panner" | "loudness_meter"+ | "mute" | "mastering" | "fft_filter" => vec![],+ "parametric_eq_full" => vec![],+ "dynamics_rack" => vec![("comp_on", 0.0)],+ "multiband_compressor" => return None, // all-pass, not identity: see its own test+ "tube_compressor" => return None, // saturation stage: near-identity at low level, tested separately+ "chorus_flanger" | "flanger" | "phaser" | "multitap_delay" | "distortion" | "guitar_suite" | "binauralizer" | "convolution_reverb" => {+ vec![("mix", 0.0)]+ }+ "analog_delay" => vec![("wet", 0.0), ("dry", 100.0)],+ "surround_reverb" => vec![("wet", 0.0), ("dry", 100.0)],+ "click_remover" => vec![("threshold", 100.0)],+ "scientific_filter" => return None,+ "vocal_enhancer" => return None,+ _ => return None,+ })+}++const NEW_IDS: &[&str] = &[+ "graphic_eq_10",+ "graphic_eq_20",+ "graphic_eq_30",+ "parametric_eq_full",+ "notch_filter",+ "scientific_filter",+ "fft_filter",+ "dynamics_rack",+ "multiband_compressor",+ "tube_compressor",+ "chorus_flanger",+ "flanger",+ "phaser",+ "analog_delay",+ "multitap_delay",+ "convolution_reverb",+ "surround_reverb",+ "click_remover",+ "channel_mixer",+ "distortion",+ "guitar_suite",+ "mastering",+ "vocal_enhancer",+ "stereo_expander",+ "binauralizer",+ "ambisonics_panner",+ "loudness_meter",+ "mute",+];++#[test]+fn neutral_settings_are_delayed_identity() {+ let n = 24000;+ let l = noise(1, n, 0.25);+ let r = noise(2, n, 0.25);+ let mut checked = 0;+ for id in NEW_IDS {+ let Some(p) = neutral(id) else { continue };+ let mut e = fx(id, &p);+ let lat = e.latency();+ let (a, b) = run(e.as_mut(), &l, &r);+ let mut worst = 0.0f32;+ for i in lat..n {+ worst = worst.max((a[i] - l[i - lat]).abs()).max((b[i] - r[i - lat]).abs());+ }+ assert!(worst < 2e-4, "{id}: neutral output differs by {worst}");+ checked += 1;+ }+ assert!(checked >= 20);+}++#[test]+fn every_effect_is_deterministic_and_latency_is_constant() {+ let n = 12000;+ let l = noise(3, n, 0.5);+ let r = noise(4, n, 0.5);+ for e in effects() {+ let mk = || {+ let mut f = (e.create)(SR, 2);+ for p in e.params {+ let v = match p.unit {+ crate::Unit::Toggle => 1.0 - p.default,+ crate::Unit::Choice => p.max,+ _ => p.min + (p.max - p.min) * 0.61,+ };+ f.set_param(p.id, v);+ }+ f+ };+ let lat0 = (e.create)(SR, 2).latency();+ let mut a = mk();+ let mut b = mk();+ assert_eq!(a.latency(), lat0, "{}: latency depends on parameters", e.id);+ let ya = run(a.as_mut(), &l, &r);+ let yb = run(b.as_mut(), &l, &r);+ assert!(ya.0 == yb.0 && ya.1 == yb.1, "{}: not deterministic", e.id);+ }+}++#[test]+fn latency_is_where_the_impulse_lands() {+ // Effects with latency: an impulse comes out exactly `latency` samples later at neutral+ // settings (FFT filter / convolution / click remover / existing STFT effects).+ for (id, p) in [("fft_filter", vec![]), ("convolution_reverb", vec![("mix", 0.0)]), ("click_remover", vec![("threshold", 100.0)])] {+ let mut e = fx(id, &p);+ let lat = e.latency();+ assert!(lat > 0, "{id}");+ let n = lat + 4000;+ let mut l = vec![0.0f32; n];+ l[100] = 0.5;+ let (a, _) = run(e.as_mut(), &l, &l);+ let peak = a.iter().enumerate().max_by(|x, y| x.1.abs().total_cmp(&y.1.abs())).unwrap().0;+ assert_eq!(peak, 100 + lat, "{id}");+ assert!((a[peak] - 0.5).abs() < 1e-3, "{id}: {}", a[peak]);+ }+}++#[test]+fn graphic_eq_bands_hit_their_gain() {+ for (id, band, freq) in [("graphic_eq_10", "b6", 1000.0), ("graphic_eq_20", "b11", 1000.0), ("graphic_eq_30", "b17", 1000.0)] {+ let mut e = fx(id, &[(band, 12.0)]);+ let want = e.response_db(freq).unwrap();+ assert!((want - 12.0).abs() < 1.0, "{id}: analytic {want}");+ let got = tone_db(e.as_mut(), freq, 0.1);+ assert!((got - want).abs() < 0.1, "{id}: measured {got} vs {want}");+ // An octave+ away the boost has mostly gone.+ assert!(e.response_db(freq * 4.0).unwrap() < 1.0, "{id}");+ let mut flat = fx(id, &[("gain", -6.0)]);+ assert!((tone_db(flat.as_mut(), 300.0, 0.1) + 6.0).abs() < 0.05, "{id}: master gain");+ }+}++#[test]+fn parametric_eq_full_sections() {+ // 24 dB/oct Butterworth high-pass: −3 dB at the corner, ≈ −48 dB two octaves down.+ let hp = fx("parametric_eq_full", &[("hp_on", 1.0), ("hp_freq", 200.0), ("hp_slope", 1.0)]);+ assert!((hp.response_db(200.0).unwrap() + 3.01).abs() < 0.05, "corner {}", hp.response_db(200.0).unwrap());+ assert!(hp.response_db(50.0).unwrap() < -45.0);+ let mut e = fx("parametric_eq_full", &[("hp_on", 1.0), ("hp_freq", 200.0), ("hp_slope", 1.0), ("mid_gain", 9.0), ("master_gain", -3.0)]);+ assert!((e.response_db(1000.0).unwrap() - 6.0).abs() < 0.05);+ for f in [50.0, 200.0, 1000.0, 5000.0] {+ let want = e.response_db(f).unwrap();+ let got = tone_db(e.as_mut(), f, 0.1);+ assert!((got - want).abs() < 0.15, "{f} Hz: {got} vs {want}");+ }+}++#[test]+fn notch_filter_removes_tones() {+ let mut e = fx("notch_filter", &[("n1_on", 1.0), ("n1_freq", 1000.0), ("n1_gain", -60.0), ("width", 2.0)]);+ assert!(tone_db(e.as_mut(), 1000.0, 0.3) < -50.0);+ assert!(tone_db(e.as_mut(), 1200.0, 0.3).abs() < 0.5);+}++#[test]+fn scientific_filter_matches_its_design() {+ for (ty, mode) in [(3.0, 0.0), (1.0, 1.0), (2.0, 2.0), (0.0, 3.0)] {+ let mut e = fx("scientific_filter", &[("type", ty), ("mode", mode), ("order", 4.0), ("cutoff", 800.0), ("high_cutoff", 3000.0)]);+ for f in [200.0, 1000.0, 1500.0, 6000.0] {+ let want = e.response_db(f).unwrap();+ let got = tone_db(e.as_mut(), f, 0.1);+ if want > -60.0 {+ assert!((got - want).abs() < 0.2, "type {ty} mode {mode} {f} Hz: {got} vs {want}");+ } else {+ assert!(got < -55.0, "type {ty} mode {mode} {f} Hz: {got}");+ }+ }+ }+}++#[test]+fn fft_filter_applies_its_curve() {+ let mut e = fx("fft_filter", &[("p5_gain", -30.0), ("interp", 0.0)]);+ assert!((e.response_db(1500.0).unwrap() + 30.0).abs() < 1e-3);+ let got = tone_db(e.as_mut(), 1500.0, 0.3);+ assert!((got + 30.0).abs() < 1.5, "{got}");+ assert!(tone_db(e.as_mut(), 100.0, 0.3).abs() < 0.3);+}++#[test]+fn dynamics_rack_sections() {+ // Compressor: −6 dBFS sine (peak), −20 dB threshold, 4:1 → ≈ −16.5 dB peak.+ let mut e = fx("dynamics_rack", &[("comp_threshold", -20.0), ("comp_ratio", 4.0), ("comp_attack", 0.1), ("comp_release", 3000.0)]);+ let want = e.transfer_db(0, -6.0).unwrap();+ assert!((want + 16.5).abs() < 1e-4);+ let n = SR as usize;+ let x = sine(1000.0, 0.5, SR as f64, n, 0.0);+ let (y, _) = run(e.as_mut(), &x, &x);+ let peak = y[n / 2..].iter().fold(0.0f32, |a, v| a.max(v.abs()));+ assert!((gain_db(peak) - want).abs() < 0.3, "compressed peak {}", gain_db(peak));+ // Gate: a quiet tone under the gate threshold is closed by ≥ 60 dB.+ let mut g = fx("dynamics_rack", &[("comp_on", 0.0), ("gate_on", 1.0), ("gate_threshold", -30.0)]);+ let q = sine(1000.0, 0.01, SR as f64, n, 0.0);+ let (yq, _) = run(g.as_mut(), &q, &q);+ assert!(db(rms(&yq[n / 2..]) / rms(&q[n / 2..])) < -60.0);+ // Limiter: hard ceiling.+ let mut lim = fx("dynamics_rack", &[("comp_on", 0.0), ("lim_on", 1.0), ("lim_threshold", -6.0)]);+ let loud = noise(5, n, 1.0);+ let (yl, _) = run(lim.as_mut(), &loud, &loud);+ assert!(yl.iter().all(|v| v.abs() <= db_to_gain(-6.0) + 1e-6));+ let mut sc = fx("dynamics_rack", &[("comp_on", 0.0), ("lim_on", 1.0), ("lim_threshold", -6.0), ("soft_clip", 1.0)]);+ let (ys, _) = run(sc.as_mut(), &loud, &loud);+ assert!(ys.iter().all(|v| v.abs() <= db_to_gain(-6.0) + 1e-6));+}++#[test]+fn multiband_crossovers_sum_flat_and_bands_compress_independently() {+ let mut e = fx("multiband_compressor", &[("b1_ratio", 1.0), ("b2_ratio", 1.0), ("b3_ratio", 1.0), ("b4_ratio", 1.0)]);+ for f in [40.0, 120.0, 700.0, 2000.0, 6000.0, 10000.0, 15000.0] {+ let g = tone_db(e.as_mut(), f, 0.25);+ assert!(g.abs() < 0.02, "crossover sum not flat at {f}: {g}");+ }+ // Band 1 compresses a loud bass tone; a treble tone in band 3 is untouched.+ let mut c = fx("multiband_compressor", &[("b1_threshold", -30.0), ("b1_ratio", 4.0), ("b3_threshold", 0.0), ("b2_threshold", 0.0), ("b4_threshold", 0.0)]);+ assert!(tone_db(c.as_mut(), 60.0, 0.5) < -10.0);+ assert!(tone_db(c.as_mut(), 5000.0, 0.5).abs() < 0.1);+ assert!((c.transfer_db(0, -6.0).unwrap() + 24.0).abs() < 1e-4);+ // Solo band 4: low tones vanish.+ let mut s = fx("multiband_compressor", &[("b4_solo", 1.0), ("b4_ratio", 1.0)]);+ assert!(tone_db(s.as_mut(), 200.0, 0.25) < -40.0);+ assert!(tone_db(s.as_mut(), 16000.0, 0.25).abs() < 0.5);+}++#[test]+fn tube_compressor_levels() {+ let mut e = fx("tube_compressor", &[("threshold", -30.0), ("ratio", 4.0)]);+ // Low level: below the knee and practically linear.+ assert!(tone_db(e.as_mut(), 1000.0, 0.005).abs() < 0.05);+ // Above threshold: reduced roughly as the static curve says (RMS detector: sine RMS = peak − 3 dB).+ let level_rms = -6.0 - 3.01;+ let want = e.transfer_db(0, level_rms).unwrap() - level_rms;+ let got = tone_db(e.as_mut(), 1000.0, 0.5);+ assert!((got - want as f64).abs() < 1.5, "tube gain {got} vs static {want}");+}++#[test]+fn flanger_static_comb_notch() {+ // initial = final: a fixed delay of d + 1 samples, mixed 50/50 → notch at fs / (2(d+1)).+ let mut e = fx("flanger", &[("initial_delay", 1.0), ("final_delay", 1.0), ("feedback", 0.0), ("mix", 50.0)]);+ let d = 48.0 + 1.0;+ let notch = SR as f64 / (2.0 * d);+ assert!(tone_db(e.as_mut(), notch, 0.3) < -30.0);+ assert!(tone_db(e.as_mut(), 2.0 * notch, 0.3).abs() < 0.2);+}++#[test]+fn chorus_flanger_and_phaser_modulate() {+ for id in ["chorus_flanger", "phaser"] {+ let mut e = fx(id, &[]);+ let x = noise(7, SR as usize, 0.3);+ let (y, _) = run(e.as_mut(), &x, &x);+ let ratio = db(rms(&y) / rms(&x));+ assert!(ratio.abs() < 6.0, "{id}: level {ratio}");+ let diff: f64 = y.iter().zip(&x).map(|(a, b)| ((a - b) as f64).powi(2)).sum();+ assert!(diff > 1.0, "{id}: no effect");+ }+ let mut cf = fx("chorus_flanger", &[("mode", 1.0)]);+ let x = noise(8, 4800, 0.3);+ let (y, _) = run(cf.as_mut(), &x, &x);+ assert!(y.iter().all(|v| v.is_finite()));+ // Static phaser (depth 0): 4 all-pass stages at 1 kHz, mixed 50/50 → a notch where the+ // chain's phase is −180°, i.e. each stage −45°.+ let mut ph = fx("phaser", &[("depth", 0.0), ("upper_freq", 1000.0), ("stages", 4.0), ("mix", 50.0)]);+ let a = util::AllPass1::coef(1000.0, SR);+ let phase = |f: f64| {+ let w = 2.0 * std::f64::consts::PI * f / SR as f64;+ // (a + e^{-jw}) / (1 + a e^{-jw})+ let (nr, ni) = (a + w.cos(), -w.sin());+ let (dr, di) = (1.0 + a * w.cos(), -a * w.sin());+ ni.atan2(nr) - di.atan2(dr)+ };+ let (mut lo, mut hi) = (10.0, 1000.0);+ for _ in 0..60 {+ let mid = 0.5 * (lo + hi);+ if 4.0 * phase(mid) > -std::f64::consts::PI { lo = mid } else { hi = mid }+ }+ assert!(tone_db(ph.as_mut(), lo, 0.3) < -25.0, "phaser notch at {lo}");+}++#[test]+fn delays_put_echoes_where_asked() {+ let n = SR as usize;+ let mut imp = vec![0.0f32; n];+ imp[0] = 1.0;+ let mut e = fx("analog_delay", &[("delay", 100.0), ("feedback", 0.0), ("dry", 0.0), ("wet", 100.0), ("mode", 2.0)]);+ let (y, _) = run(e.as_mut(), &imp, &imp);+ let peak = y.iter().enumerate().max_by(|a, b| a.1.abs().total_cmp(&b.1.abs())).unwrap().0;+ assert!((peak as i64 - 4800).abs() <= 3, "analog echo at {peak}");+ let mut m =+ fx("multitap_delay", &[("delay1", 50.0), ("delay2", 120.0), ("level1", 0.0), ("level2", -6.0), ("level3", -96.0), ("level4", -96.0), ("mix", 100.0)]);+ let (y, _) = run(m.as_mut(), &imp, &imp);+ assert!((y[2400] - 1.0).abs() < 1e-4, "tap 1 {}", y[2400]);+ assert!((y[5760] - db_to_gain(-6.0)).abs() < 1e-4, "tap 2 {}", y[5760]);+ let elsewhere = y.iter().enumerate().filter(|(i, _)| *i != 2400 && *i != 5760).fold(0.0f32, |a, (_, v)| a.max(v.abs()));+ assert!(elsewhere < 1e-6);+ // Feedback repeats.+ let mut f = fx(+ "multitap_delay",+ &[("delay1", 50.0), ("feedback1", 50.0), ("level1", 0.0), ("level2", -96.0), ("level3", -96.0), ("level4", -96.0), ("mix", 100.0)],+ );+ let (y, _) = run(f.as_mut(), &imp, &imp);+ assert!((y[4800] - 0.5).abs() < 1e-4 && (y[7200] - 0.25).abs() < 1e-4);+}++/// RT60 by Schroeder backward integration (−5 … −25 dB fit, extrapolated).+fn rt60(ir: &[f32]) -> f64 {+ let mut e: Vec<f64> = ir.iter().map(|&v| (v as f64) * (v as f64)).collect();+ for i in (0..e.len() - 1).rev() {+ e[i] += e[i + 1];+ }+ let total = e[0];+ let t = |level: f64| e.iter().position(|&v| 10.0 * (v / total).log10() < level).unwrap_or(e.len()) as f64 / SR as f64;+ (t(-25.0) - t(-5.0)) * 3.0+}++#[test]+fn convolution_reverb_impulses() {+ for (k, want_rt) in [(0usize, 0.45), (2, 1.9), (4, 1.6)] {+ let mut e = fx("convolution_reverb", &[("impulse", k as f32), ("mix", 100.0), ("width", 100.0)]);+ let lat = e.latency();+ let n = (SR * 4.0) as usize;+ let mut imp = vec![0.0f32; n];+ imp[0] = 1.0;+ let (l, r) = run(e.as_mut(), &imp, &imp);+ let (l, r) = (&l[lat..], &r[lat..]);+ let el: f64 = l.iter().map(|&v| (v as f64).powi(2)).sum();+ assert!((el - 1.0).abs() < 0.02, "impulse {k}: energy {el}");+ let rt = rt60(l);+ assert!((rt - want_rt).abs() < want_rt * 0.25, "impulse {k}: RT60 {rt} vs {want_rt}");+ // Decorrelated stereo.+ let c: f64 = l.iter().zip(r).map(|(a, b)| (*a as f64) * (*b as f64)).sum();+ assert!(c.abs() < 0.3, "impulse {k}: L/R correlation {c}");+ }+ // Room size shortens the tail.+ let mut a = fx("convolution_reverb", &[("impulse", 2.0), ("mix", 100.0), ("room_size", 40.0)]);+ let n = (SR * 3.0) as usize;+ let mut imp = vec![0.0f32; n];+ imp[0] = 1.0;+ let (l, _) = run(a.as_mut(), &imp, &imp);+ let rt = rt60(&l[a.latency()..]);+ assert!((rt - 0.76).abs() < 0.25, "scaled RT60 {rt}");+}++#[test]+fn surround_reverb_tail_decays() {+ let mut e = fx("surround_reverb", &[("decay", 1.0), ("dry", 0.0), ("wet", 100.0)]);+ let n = (SR * 3.0) as usize;+ let mut imp = vec![0.0f32; n];+ imp[0] = 1.0;+ let (l, r) = run(e.as_mut(), &imp, &imp);+ let seg = |s: f32, e: f32| rms(&l[(s * SR) as usize..(e * SR) as usize]);+ assert!(seg(0.05, 0.3) > 1e-4);+ let drop = db(seg(1.6, 1.9) / seg(0.1, 0.4));+ assert!(drop < -45.0 && drop > -120.0, "RT60≈1 s: 1.5 s later {drop} dB");+ assert!(r.iter().all(|v| v.is_finite()));+}++#[test]+fn click_remover_repairs_clicks() {+ let n = SR as usize * 2;+ let clean: Vec<f32> = sine(440.0, 0.3, SR as f64, n, 0.0).iter().zip(noise(9, n, 0.01)).map(|(a, b)| a + b).collect();+ let mut dirty = clean.clone();+ for k in 0..30 {+ let at = 3000 + k * 3001;+ dirty[at] += 0.6;+ dirty[at + 1] -= 0.4;+ }+ let mut e = fx("click_remover", &[]);+ let lat = e.latency();+ let (y, _) = run(e.as_mut(), &dirty, &dirty);+ let err = |s: &[f32], off: usize| -> f64 { (lat + 2000..n).map(|i| ((s[i] - clean[i - off]) as f64).powi(2)).sum::<f64>().sqrt() };+ let before = err(&dirty[..], 0);+ let after = err(&y, lat);+ assert!(db(after / before) < -20.0, "error {before} → {after}");+}++#[test]+fn channel_and_stereo_tools() {+ let n = 4800;+ let l = noise(10, n, 0.3);+ let r = noise(11, n, 0.3);+ let mut sw = fx("channel_mixer", &[("l_from_l", 0.0), ("l_from_r", 100.0), ("r_from_l", 100.0), ("r_from_r", 0.0), ("invert_r", 1.0)]);+ let (a, b) = run(sw.as_mut(), &l, &r);+ assert!(a.iter().zip(&r).all(|(x, y)| (x - y).abs() < 1e-6));+ assert!(b.iter().zip(&l).all(|(x, y)| (x + y).abs() < 1e-6));+ let mut mono = fx("stereo_expander", &[("expand", 0.0)]);+ let (a, b) = run(mono.as_mut(), &l, &r);+ assert!(a.iter().zip(&b).all(|(x, y)| (x - y).abs() < 1e-6));+ let mut wide = fx("stereo_expander", &[("expand", 200.0), ("center_pan", 100.0)]);+ let (a, b) = run(wide.as_mut(), &l, &l);+ // centre fully right: identical L/R input → nothing left+ assert!(a.iter().all(|v| v.abs() < 1e-6) && b.iter().zip(&l).all(|(x, y)| (x - y).abs() < 1e-6));+ // Mute ramps to silence.+ let mut m = fx("mute", &[("mute", 1.0)]);+ let (a, _) = run(m.as_mut(), &l, &r);+ assert!(a.iter().all(|v| *v == 0.0));+}++#[test]+fn distortion_harmonics() {+ let n = SR as usize;+ let x = sine(500.0, 0.5, SR as f64, n, 0.0);+ let mut sym = fx("distortion", &[("drive", 24.0), ("curve", 1.0)]);+ let (y, _) = run(sym.as_mut(), &x, &x);+ let h = |s: &[f32], k: f64| tone_amplitude(&s[n / 2..], 500.0 * k, SR as f64);+ assert!(h(&y, 3.0) > 0.1 * h(&y, 1.0), "hard clip makes odd harmonics");+ assert!(h(&y, 2.0) < 1e-3 * h(&y, 1.0), "symmetric: no even harmonics");+ let mut asym = fx("distortion", &[("drive", 24.0), ("symmetry", 60.0)]);+ let (y, _) = run(asym.as_mut(), &x, &x);+ assert!(h(&y, 2.0) > 0.02 * h(&y, 1.0), "asymmetric: even harmonics");+ // GuitarSuite with everything off is near-transparent at low level.+ let mut gs = fx("guitar_suite", &[("compressor", 0.0), ("distortion", 0.0), ("amp", 0.0), ("filter", 0.0)]);+ assert!(tone_db(gs.as_mut(), 1000.0, 0.01).abs() < 0.05);+ let mut gs2 = fx("guitar_suite", &[]);+ let (y, _) = run(gs2.as_mut(), &x, &x);+ assert!(y.iter().all(|v| v.is_finite()) && rms(&y) > 0.01);+}++#[test]+fn mastering_and_vocal_enhancer() {+ let mut e = fx("mastering", &[("eq_low", 6.0)]);+ assert!((e.response_db(20.0).unwrap() - 6.0).abs() < 0.3);+ assert!((tone_db(e.as_mut(), 30.0, 0.1) - e.response_db(30.0).unwrap()).abs() < 0.1);+ let n = SR as usize;+ let x = noise(12, n, 0.3);+ let mut loud = fx("mastering", &[("loudness", 100.0)]);+ let (y, _) = run(loud.as_mut(), &x, &x);+ assert!(y.iter().all(|v| v.abs() <= db_to_gain(-0.3) + 1e-6));+ assert!(rms(&y) > 1.5 * rms(&x));+ let mut v = fx("vocal_enhancer", &[("mode", 0.0)]);+ assert!(v.response_db(40.0).unwrap() < -6.0);+ assert!(v.response_db(3000.0).unwrap() > 2.0);+ // Below the compressor threshold the measured response is the EQ.+ assert!((tone_db(v.as_mut(), 3000.0, 0.02) - v.response_db(3000.0).unwrap()).abs() < 0.1);+ let mut music = fx("vocal_enhancer", &[("mode", 2.0)]);+ assert!(music.response_db(1500.0).unwrap() < -3.0);+ assert!((tone_db(music.as_mut(), 1500.0, 0.3) - music.response_db(1500.0).unwrap()).abs() < 0.1);+}++#[test]+fn binaural_and_ambisonic_rendering() {+ let n = SR as usize;+ // A correlated low tone stays at unity.+ let mut b = fx("binauralizer", &[]);+ assert!(tone_db(b.as_mut(), 100.0, 0.3).abs() < 0.5);+ // Left-only input reaches the right ear later (interaural time difference).+ let mut imp = vec![0.0f32; 2000];+ imp[100] = 1.0;+ let zero = vec![0.0f32; 2000];+ let (l, r) = run(b.as_mut(), &imp, &zero);+ let pk = |s: &[f32]| s.iter().enumerate().max_by(|a, b| a.1.abs().total_cmp(&b.1.abs())).unwrap().0;+ let itd = pk(&r) as f64 - pk(&l) as f64;+ let a = 0.0875f64;+ let th = 30f64.to_radians();+ let want = a / 343.0 * (th + th.sin()) * SR as f64;+ assert!((itd - want).abs() <= 1.5, "ITD {itd} samples vs {want}");+ assert!(l[pk(&l)].abs() > r[pk(&r)].abs(), "head shadow: far ear quieter");+ // Ambisonic pan 180°: the left source ends up on the right.+ let mut p = fx("ambisonics_panner", &[("pan", 180.0)]);+ let x = noise(13, n, 0.3);+ let (l, r) = run(p.as_mut(), &x, &zero[..0].iter().copied().chain(std::iter::repeat_n(0.0, n)).collect::<Vec<_>>());+ assert!(rms(&r) > 3.0 * rms(&l), "rotated: L {} R {}", rms(&l), rms(&r));+ let (g, _) = special::AmbisonicsPanner::source_gains(30.0, 0.0, 0.0, 0.0);+ assert!((g - 1.0).abs() < 1e-6);+}++#[test]+fn loudness_meter_passes_through_and_measures() {+ let n = SR as usize * 3;+ let x = sine(1000.0, 0.1, SR as f64, n, 0.0);+ let mut m = special::LoudnessMeterFx::new(SR, 2);+ let (mut a, mut b) = (x.clone(), x.clone());+ m.process(&mut [&mut a, &mut b]);+ assert_eq!(a, x);+ let mut reference = crate::LoudnessMeter::new(SR as f64, 2);+ reference.process(&[&x, &x]);+ assert!((m.meter().integrated() - reference.integrated()).abs() < 1e-9);+ assert!(m.meter().integrated().is_finite());+}++#[test]+fn realtime_factor_sanity() {+ let secs = 2.0;+ let n = (SR * secs) as usize;+ let l = noise(14, n, 0.3);+ let r = noise(15, n, 0.3);+ let mut slowest = (f64::INFINITY, "");+ for e in effects() {+ let mut f = (e.create)(SR, 2);+ let (mut a, mut b) = (l.clone(), r.clone());+ let t0 = std::time::Instant::now();+ for (ca, cb) in a.chunks_mut(512).zip(b.chunks_mut(512)) {+ f.process(&mut [ca, cb]);+ }+ let dt = t0.elapsed().as_secs_f64().max(1e-9);+ let rtf = secs as f64 / dt;+ if rtf < slowest.0 {+ slowest = (rtf, e.id);+ }+ assert!(rtf > 1.0, "{}: only {rtf:.1}× realtime", e.id);+ }+ eprintln!("slowest effect: {} at {:.0}× realtime", slowest.1, slowest.0);+}++fn gain_db(x: f32) -> f32 {+ crate::gain_to_db(x)+}++fn db_to_gain(x: f32) -> f32 {+ crate::db_to_gain(x)+}diff --git a/crates/audio-dsp/src/effects/reverbs.rs b/crates/audio-dsp/src/effects/reverbs.rsnew file mode 100644index 000000000..251bc384d--- /dev/null+++ b/crates/audio-dsp/src/effects/reverbs.rs@@ -0,0 +1,474 @@+//! Convolution Reverb (uniformly partitioned overlap-save convolution with impulse responses+//! we generate ourselves) and Surround Reverb (early reflections + the FDN late field).++use super::time::Reverb;+use super::util::{DelayLine, OnePole, Prng};+use crate::fft::Fft;+use crate::{AudioEffect, ParamSpec, ParamValues, Smoothed, Unit, block_len, db_to_gain, param_plumbing};++/// Partition (block) size; the effect's latency.+const PART: usize = 256;++/// Built-in impulse responses (generated, see [`generate_ir`]).+pub const IMPULSES: &[&str] = &["Small Room", "Medium Room", "Large Hall", "Cathedral", "Plate", "Ambience", "Vocal Booth"];++/// Character of a generated impulse.+#[derive(Clone, Copy, Debug)]+struct IrSpec {+ rt60: f32,+ /// Early-reflection span (ms) and count.+ er_ms: f32,+ er_count: usize,+ /// How fast the high frequencies die relative to the low ones (1/s).+ hf_decay: f32,+ /// Late-field onset (ms).+ onset_ms: f32,+ seed: u64,+}++const IR_SPECS: [IrSpec; 7] = [+ IrSpec { rt60: 0.45, er_ms: 25.0, er_count: 10, hf_decay: 6.0, onset_ms: 8.0, seed: 11 },+ IrSpec { rt60: 0.8, er_ms: 45.0, er_count: 14, hf_decay: 4.0, onset_ms: 15.0, seed: 12 },+ IrSpec { rt60: 1.9, er_ms: 80.0, er_count: 18, hf_decay: 2.2, onset_ms: 30.0, seed: 13 },+ IrSpec { rt60: 3.2, er_ms: 120.0, er_count: 22, hf_decay: 1.4, onset_ms: 45.0, seed: 14 },+ IrSpec { rt60: 1.6, er_ms: 0.0, er_count: 0, hf_decay: 1.0, onset_ms: 1.0, seed: 15 },+ IrSpec { rt60: 0.3, er_ms: 15.0, er_count: 8, hf_decay: 8.0, onset_ms: 4.0, seed: 16 },+ IrSpec { rt60: 0.2, er_ms: 8.0, er_count: 6, hf_decay: 12.0, onset_ms: 2.0, seed: 17 },+];++fn ir_len(spec: &IrSpec, sr: f32) -> usize {+ ((spec.rt60 * 1.1 + spec.er_ms * 0.001) * sr) as usize + 1+}++/// Fill `out` (stereo, equal lengths) with a synthetic impulse response: sparse early+/// reflections plus exponentially decaying noise whose bandwidth narrows over time (high+/// frequencies decay faster), fading in over the onset, each channel normalised to unit energy.+/// Deterministic for a given index and sample rate.+fn generate_ir(index: usize, sr: f32, out: [&mut [f32]; 2]) {+ let spec = IR_SPECS[index.min(IR_SPECS.len() - 1)];+ for (c, buf) in out.into_iter().enumerate() {+ let len = buf.len();+ let mut rng = Prng::new(spec.seed * 2 + c as u64);+ let mut lp = OnePole::default();+ let onset = (spec.onset_ms * 0.001 * sr).max(1.0);+ for (i, v) in buf.iter_mut().enumerate() {+ let t = i as f32 / sr;+ let env = (-6.907_755 * t / spec.rt60).exp();+ let fade = (i as f32 / onset).min(1.0);+ let fc = (16000.0 * (-t * spec.hf_decay).exp()).max(800.0);+ let a = OnePole::alpha(fc, sr);+ *v = lp.lp(a, rng.uniform()) * env * fade;+ }+ for _ in 0..spec.er_count {+ let t = 0.002 + (rng.uniform() * 0.5 + 0.5) * spec.er_ms * 0.001;+ let i = ((t * sr) as usize).min(len - 1);+ let amp = 0.6 * (-3.0 * t / (spec.er_ms * 0.001 + 1e-3)).exp() * if rng.uniform() < 0.0 { -1.0 } else { 1.0 };+ buf[i] += amp;+ }+ let e: f64 = buf.iter().map(|&v| (v as f64) * (v as f64)).sum();+ let g = if e > 0.0 { (1.0 / e.sqrt()) as f32 } else { 0.0 };+ buf.iter_mut().for_each(|v| *v *= g);+ }+}++/// Convolution reverb with generated impulses (mono-summed input, decorrelated stereo IR).+pub struct ConvolutionReverb {+ pv: ParamValues,+ sr: f32,+ fft: Fft,+ /// Base impulse (current preset) and the processed one (size, damping) per output channel.+ base: [Vec<f32>; 2],+ base_len: usize,+ /// Partition spectra (B+1 bins, re/im interleaved per partition): `h[ch][p * 2(B+1) ..]`.+ h: [Vec<f32>; 2],+ parts: usize,+ /// Frequency-domain delay line of input spectra (same layout), ring of `max_parts`.+ fdl: Vec<f32>,+ head: usize,+ max_parts: usize,+ /// Time-domain input history (2B) and block in/out buffers.+ hist: Vec<f32>,+ inbuf: Vec<f32>,+ out: [Vec<f32>; 2],+ pos: usize,+ re: Vec<f32>,+ im: Vec<f32>,+ pre: DelayLine,+ dry_delay: Vec<DelayLine>,+ key: (usize, f32, f32, f32),+ mix: Smoothed,+ gain: Smoothed,+ width: Smoothed,+ predelay: Smoothed,+}++impl ConvolutionReverb {+ pub const PARAMS: &'static [ParamSpec] = &[+ ParamSpec::choice("impulse", "Impulse", IMPULSES, 1),+ ParamSpec::new("mix", "Mix", 0.0, 100.0, 30.0, Unit::Percent),+ ParamSpec::new("room_size", "Room Size", 10.0, 100.0, 100.0, Unit::Percent),+ ParamSpec::log("damping_lf", "Damping LF", 10.0, 1000.0, 10.0, Unit::Hertz),+ ParamSpec::log("damping_hf", "Damping HF", 1000.0, 20000.0, 20000.0, Unit::Hertz),+ ParamSpec::new("predelay", "Pre-Delay", 0.0, 500.0, 0.0, Unit::Milliseconds),+ ParamSpec::new("width", "Width", 0.0, 100.0, 100.0, Unit::Percent),+ ParamSpec::new("gain", "Gain", -24.0, 12.0, 0.0, Unit::Decibels),+ ];++ pub fn new(sample_rate: f32, channels: usize) -> Self {+ let max_len = IR_SPECS.iter().map(|s| ir_len(s, sample_rate)).max().unwrap_or(1);+ let max_parts = max_len.div_ceil(PART);+ let bins2 = 2 * (PART + 1);+ let mut s = ConvolutionReverb {+ pv: ParamValues::new(Self::PARAMS),+ sr: sample_rate,+ fft: Fft::new(2 * PART),+ base: [vec![0.0; max_len], vec![0.0; max_len]],+ base_len: 0,+ h: [vec![0.0; max_parts * bins2], vec![0.0; max_parts * bins2]],+ parts: 0,+ fdl: vec![0.0; max_parts * bins2],+ head: 0,+ max_parts,+ hist: vec![0.0; 2 * PART],+ inbuf: vec![0.0; PART],+ out: [vec![0.0; PART], vec![0.0; PART]],+ pos: 0,+ re: vec![0.0; 2 * PART],+ im: vec![0.0; 2 * PART],+ pre: DelayLine::new((0.5 * sample_rate) as usize + 2),+ dry_delay: vec![DelayLine::new(PART + 2); channels.max(1)],+ key: (usize::MAX, 0.0, 0.0, 0.0),+ mix: Smoothed::with_ms(0.0, sample_rate, 20.0),+ gain: Smoothed::with_ms(1.0, sample_rate, 20.0),+ width: Smoothed::with_ms(1.0, sample_rate, 20.0),+ predelay: Smoothed::with_ms(0.0, sample_rate, 50.0),+ };+ s.apply_params(true);+ s+ }++ /// Rebuild the partition spectra (only when the impulse, size or damping changed).+ fn rebuild(&mut self) {+ let key = (self.pv.idx("impulse"), self.pv.v("room_size"), self.pv.v("damping_lf"), self.pv.v("damping_hf"));+ if key == self.key {+ return;+ }+ if key.0 != self.key.0 {+ let len = ir_len(&IR_SPECS[key.0.min(IR_SPECS.len() - 1)], self.sr).min(self.base[0].len());+ let [a, b] = &mut self.base;+ generate_ir(key.0, self.sr, [&mut a[..len], &mut b[..len]]);+ self.base_len = len;+ }+ self.key = key;+ // Room size shortens the impulse by resampling it (linear interpolation).+ let scale = (key.1 / 100.0).clamp(0.1, 1.0);+ let len = ((self.base_len as f32 * scale) as usize).max(1);+ self.parts = len.div_ceil(PART).min(self.max_parts);+ let (alf, ahf) = (OnePole::alpha(key.2, self.sr), OnePole::alpha(key.3, self.sr));+ let bins2 = 2 * (PART + 1);+ for c in 0..2 {+ let mut hp = OnePole::default();+ let mut lp = OnePole::default();+ for p in 0..self.parts {+ for k in 0..2 * PART {+ self.re[k] = 0.0;+ self.im[k] = 0.0;+ }+ for k in 0..PART {+ let i = p * PART + k;+ if i >= len {+ break;+ }+ let src = i as f32 / scale;+ let i0 = src as usize;+ let fr = src - i0 as f32;+ let b = &self.base[c];+ let v0 = b.get(i0).copied().unwrap_or(0.0);+ let v1 = b.get(i0 + 1).copied().unwrap_or(0.0);+ let mut v = (v0 + (v1 - v0) * fr) * scale.sqrt().recip();+ if key.2 > 10.5 {+ v = hp.hp(alf, v);+ }+ if key.3 < 19999.0 {+ v = lp.lp(ahf, v);+ }+ self.re[k] = v;+ }+ self.fft.forward(&mut self.re, &mut self.im);+ let dst = &mut self.h[c][p * bins2..(p + 1) * bins2];+ for k in 0..=PART {+ dst[2 * k] = self.re[k];+ dst[2 * k + 1] = self.im[k];+ }+ }+ }+ }++ fn apply_params(&mut self, snap: bool) {+ self.rebuild();+ self.mix.set(self.pv.v("mix") / 100.0);+ self.gain.set(db_to_gain(self.pv.v("gain")));+ self.width.set(self.pv.v("width") / 100.0);+ self.predelay.set(self.pv.v("predelay") * 0.001 * self.sr);+ if snap {+ self.mix.snap();+ self.gain.snap();+ self.width.snap();+ self.predelay.snap();+ }+ }++ /// Convolve the collected block (`inbuf`) and fill `out`.+ fn block(&mut self) {+ let bins2 = 2 * (PART + 1);+ self.hist.copy_within(PART.., 0);+ self.hist[PART..].copy_from_slice(&self.inbuf);+ self.re.copy_from_slice(&self.hist);+ self.im.iter_mut().for_each(|v| *v = 0.0);+ self.fft.forward(&mut self.re, &mut self.im);+ self.head = (self.head + self.max_parts - 1) % self.max_parts;+ {+ let slot = &mut self.fdl[self.head * bins2..(self.head + 1) * bins2];+ for k in 0..=PART {+ slot[2 * k] = self.re[k];+ slot[2 * k + 1] = self.im[k];+ }+ }+ // Accumulate Y_L and Y_R (half spectra) then pack Z = Y_L + j·Y_R for one inverse FFT.+ let mut yl = [0.0f32; 2 * (PART + 1)];+ let mut yr = [0.0f32; 2 * (PART + 1)];+ for p in 0..self.parts {+ let xi = ((self.head + p) % self.max_parts) * bins2;+ let x = &self.fdl[xi..xi + bins2];+ let hl = &self.h[0][p * bins2..(p + 1) * bins2];+ let hr = &self.h[1][p * bins2..(p + 1) * bins2];+ for k in 0..=PART {+ let (xr, xim) = (x[2 * k], x[2 * k + 1]);+ yl[2 * k] += xr * hl[2 * k] - xim * hl[2 * k + 1];+ yl[2 * k + 1] += xr * hl[2 * k + 1] + xim * hl[2 * k];+ yr[2 * k] += xr * hr[2 * k] - xim * hr[2 * k + 1];+ yr[2 * k + 1] += xr * hr[2 * k + 1] + xim * hr[2 * k];+ }+ }+ let n = 2 * PART;+ for k in 0..n {+ let (lr, li, rr, ri) = if k <= PART {+ (yl[2 * k], yl[2 * k + 1], yr[2 * k], yr[2 * k + 1])+ } else {+ let m = n - k;+ (yl[2 * m], -yl[2 * m + 1], yr[2 * m], -yr[2 * m + 1])+ };+ // Z = Y_L + j·Y_R+ self.re[k] = lr - ri;+ self.im[k] = li + rr;+ }+ self.fft.inverse(&mut self.re, &mut self.im);+ let s = 1.0 / n as f32;+ for k in 0..PART {+ self.out[0][k] = self.re[PART + k] * s;+ self.out[1][k] = self.im[PART + k] * s;+ }+ }+}++impl AudioEffect for ConvolutionReverb {+ param_plumbing!("convolution_reverb");+ fn latency(&self) -> usize {+ PART+ }+ fn reset(&mut self) {+ self.fdl.iter_mut().for_each(|v| *v = 0.0);+ self.hist.iter_mut().for_each(|v| *v = 0.0);+ self.inbuf.iter_mut().for_each(|v| *v = 0.0);+ self.out.iter_mut().for_each(|o| o.iter_mut().for_each(|v| *v = 0.0));+ self.head = 0;+ self.pos = 0;+ self.pre.reset();+ self.dry_delay.iter_mut().for_each(DelayLine::reset);+ self.mix.snap();+ self.gain.snap();+ self.width.snap();+ self.predelay.snap();+ }+ fn process(&mut self, channels: &mut [&mut [f32]]) {+ let n = block_len(channels);+ let nch = channels.len().min(self.dry_delay.len());+ if nch == 0 {+ return;+ }+ for i in 0..n {+ let (mix, gain, width, pd) = (self.mix.tick(), self.gain.tick(), self.width.tick(), self.predelay.tick());+ let mono = channels[..nch].iter().map(|c| c[i]).sum::<f32>() / nch as f32;+ self.pre.push(mono);+ self.inbuf[self.pos] = self.pre.read(pd);+ let (wl, wr) = (self.out[0][self.pos], self.out[1][self.pos]);+ self.pos += 1;+ if self.pos == PART {+ self.pos = 0;+ self.block();+ }+ // Width: 0 = mono wet, 1 = full decorrelated stereo.+ let m = 0.5 * (wl + wr);+ let (wl, wr) = (m + width * (wl - m), m + width * (wr - m));+ for ch in 0..nch {+ self.dry_delay[ch].push(channels[ch][i]);+ let dry = self.dry_delay[ch].tap(PART);+ let wet = if nch == 1 {+ m+ } else if ch == 0 {+ wl+ } else {+ wr+ };+ channels[ch][i] = dry + mix * (wet * gain - dry);+ }+ }+ }+}++// ------------------------------------------------------------------------- surround reverb++const ER_TAPS: usize = 8;+const ER_MS: [f32; ER_TAPS] = [7.1, 11.3, 15.7, 19.9, 24.2, 31.7, 38.3, 47.9];+const ER_GAIN: [f32; ER_TAPS] = [0.8, -0.7, 0.62, -0.55, 0.47, -0.4, 0.33, -0.27];+const CHUNK: usize = 256;++/// Early reflections (8 taps, alternating sides) plus the 8-line FDN late field, with+/// low/high cut on the wet signal, wet width, and separate dry/wet levels. The centre input+/// level controls how much of the mid (L+R) signal feeds the reverb.+pub struct SurroundReverb {+ pv: ParamValues,+ sr: f32,+ late: Reverb,+ er: DelayLine,+ lc: [OnePole; 2],+ hc: [OnePole; 2],+ scratch: [[f32; CHUNK]; 2],+ dry: Smoothed,+ wet: Smoothed,+ early: Smoothed,+ width: Smoothed,+ centre: Smoothed,+ size: Smoothed,+}++impl SurroundReverb {+ pub const PARAMS: &'static [ParamSpec] = &[+ ParamSpec::new("center_input", "Center Input", 0.0, 100.0, 100.0, Unit::Percent),+ ParamSpec::new("room_size", "Room Size", 0.0, 100.0, 50.0, Unit::Percent),+ ParamSpec::log("decay", "Decay", 0.1, 20.0, 1.5, Unit::Seconds),+ ParamSpec::new("predelay", "Pre-Delay", 0.0, 200.0, 20.0, Unit::Milliseconds),+ ParamSpec::new("damping", "Damping", 0.0, 100.0, 40.0, Unit::Percent),+ ParamSpec::new("early", "Early Reflections", 0.0, 100.0, 40.0, Unit::Percent),+ ParamSpec::log("low_cut", "Low Frequency Cut", 20.0, 1000.0, 20.0, Unit::Hertz),+ ParamSpec::log("high_cut", "High Frequency Cut", 1000.0, 20000.0, 12000.0, Unit::Hertz),+ ParamSpec::new("width", "Width", 0.0, 100.0, 100.0, Unit::Percent),+ ParamSpec::new("dry", "Dry", 0.0, 100.0, 80.0, Unit::Percent),+ ParamSpec::new("wet", "Wet", 0.0, 100.0, 30.0, Unit::Percent),+ ];++ pub fn new(sample_rate: f32, channels: usize) -> Self {+ let mut late = Reverb::new(sample_rate, channels);+ late.set_param("mix", 100.0);+ let sm = |v| Smoothed::with_ms(v, sample_rate, 20.0);+ let mut s = SurroundReverb {+ pv: ParamValues::new(Self::PARAMS),+ sr: sample_rate,+ late,+ er: DelayLine::new((0.1 * sample_rate) as usize),+ lc: [OnePole::default(); 2],+ hc: [OnePole::default(); 2],+ scratch: [[0.0; CHUNK]; 2],+ dry: sm(1.0),+ wet: sm(0.0),+ early: sm(0.0),+ width: sm(1.0),+ centre: sm(1.0),+ size: sm(1.0),+ };+ s.apply_params(true);+ s+ }++ fn apply_params(&mut self, snap: bool) {+ self.late.set_param("size", self.pv.v("room_size"));+ self.late.set_param("decay", self.pv.v("decay"));+ self.late.set_param("predelay", self.pv.v("predelay"));+ self.late.set_param("damping", self.pv.v("damping"));+ self.dry.set(self.pv.v("dry") / 100.0);+ self.wet.set(self.pv.v("wet") / 100.0);+ self.early.set(self.pv.v("early") / 100.0);+ self.width.set(self.pv.v("width") / 100.0);+ self.centre.set(self.pv.v("center_input") / 100.0);+ self.size.set(0.5 + self.pv.v("room_size") / 100.0);+ if snap {+ self.late.reset();+ for s in [&mut self.dry, &mut self.wet, &mut self.early, &mut self.width, &mut self.centre, &mut self.size] {+ s.snap();+ }+ }+ }+}++impl AudioEffect for SurroundReverb {+ param_plumbing!("surround_reverb");+ fn reset(&mut self) {+ self.late.reset();+ self.er.reset();+ self.lc = [OnePole::default(); 2];+ self.hc = [OnePole::default(); 2];+ for s in [&mut self.dry, &mut self.wet, &mut self.early, &mut self.width, &mut self.centre, &mut self.size] {+ s.snap();+ }+ }+ fn process(&mut self, channels: &mut [&mut [f32]]) {+ let n = block_len(channels);+ let nch = channels.len().min(2);+ if nch == 0 {+ return;+ }+ let (alc, ahc) = (OnePole::alpha(self.pv.v("low_cut"), self.sr), OnePole::alpha(self.pv.v("high_cut"), self.sr));+ let ms = self.sr * 0.001;+ let mut start = 0;+ while start < n {+ let len = (n - start).min(CHUNK);+ // Reverb input: side signal plus the centre-weighted mid.+ for i in 0..len {+ let (l, r) = if nch == 2 { (channels[0][start + i], channels[1][start + i]) } else { (channels[0][start + i], channels[0][start + i]) };+ let c = self.centre.tick();+ let (mid, side) = (0.5 * (l + r), 0.5 * (l - r));+ self.scratch[0][i] = c * mid + side;+ self.scratch[1][i] = c * mid - side;+ }+ {+ let [a, b] = &mut self.scratch;+ self.late.process(&mut [&mut a[..len], &mut b[..len]]);+ }+ for i in 0..len {+ let x = if nch == 2 { 0.5 * (channels[0][start + i] + channels[1][start + i]) } else { channels[0][start + i] };+ let size = self.size.tick();+ self.er.push(x);+ let (mut el, mut er) = (0.0, 0.0);+ for k in 0..ER_TAPS {+ let v = ER_GAIN[k] * self.er.read(ER_MS[k] * size * ms);+ if k % 2 == 0 { el += v } else { er += v }+ }+ let early = self.early.tick();+ let (dry, wet, width) = (self.dry.tick(), self.wet.tick(), self.width.tick());+ let mut w = [self.scratch[0][i] + early * el, self.scratch[1][i] + early * er];+ for c in 0..2 {+ w[c] = self.hc[c].lp(ahc, self.lc[c].hp(alc, w[c]));+ }+ let m = 0.5 * (w[0] + w[1]);+ let (wl, wr) = (m + width * (w[0] - m), m + width * (w[1] - m));+ if nch == 2 {+ channels[0][start + i] = dry * channels[0][start + i] + wet * wl;+ channels[1][start + i] = dry * channels[1][start + i] + wet * wr;+ } else {+ channels[0][start + i] = dry * channels[0][start + i] + wet * m;+ }+ }+ start += len;+ }+ }+}diff --git a/crates/audio-dsp/src/effects/special.rs b/crates/audio-dsp/src/effects/special.rsnew file mode 100644index 000000000..3c5034598--- /dev/null+++ b/crates/audio-dsp/src/effects/special.rs@@ -0,0 +1,952 @@+//! Special and stereo effects: Channel Mixer, Distortion, GuitarSuite, Mastering, Vocal+//! Enhancer, Stereo Expander, Binauralizer, Ambisonics Panner, Loudness Meter and Mute.++use super::multiband::soft_clip;+use super::time::Reverb;+use super::util::{DcBlock, DelayLine, OnePole, coef, lin_db};+use crate::biquad::{Biquad, Coeffs, FilterType};+use crate::loudness::LoudnessMeter;+use crate::{AudioEffect, ParamSpec, ParamValues, Smoothed, Unit, block_len, db_to_gain, param_plumbing};+use std::f32::consts::{FRAC_PI_2, PI};++const SM: f32 = 20.0;+const CHUNK: usize = 256;++fn sm(v: f32, sr: f32) -> Smoothed {+ Smoothed::with_ms(v, sr, SM)+}++// ------------------------------------------------------------------------------ channel mixer++/// 2×2 channel matrix with per-output polarity inversion.+pub struct ChannelMixer {+ pv: ParamValues,+ g: [Smoothed; 4],+}++impl ChannelMixer {+ pub const PARAMS: &'static [ParamSpec] = &[+ ParamSpec::new("l_from_l", "Left - Left", -100.0, 100.0, 100.0, Unit::Percent),+ ParamSpec::new("l_from_r", "Left - Right", -100.0, 100.0, 0.0, Unit::Percent),+ ParamSpec::new("r_from_l", "Right - Left", -100.0, 100.0, 0.0, Unit::Percent),+ ParamSpec::new("r_from_r", "Right - Right", -100.0, 100.0, 100.0, Unit::Percent),+ ParamSpec::toggle("invert_l", "Invert Left", false),+ ParamSpec::toggle("invert_r", "Invert Right", false),+ ];++ pub fn new(sample_rate: f32, _channels: usize) -> Self {+ let mut s =+ ChannelMixer { pv: ParamValues::new(Self::PARAMS), g: [sm(1.0, sample_rate), sm(0.0, sample_rate), sm(0.0, sample_rate), sm(1.0, sample_rate)] };+ s.apply_params(true);+ s+ }++ fn apply_params(&mut self, snap: bool) {+ let il = if self.pv.on("invert_l") { -1.0 } else { 1.0 };+ let ir = if self.pv.on("invert_r") { -1.0 } else { 1.0 };+ let v =+ [il * self.pv.v("l_from_l") / 100.0, il * self.pv.v("l_from_r") / 100.0, ir * self.pv.v("r_from_l") / 100.0, ir * self.pv.v("r_from_r") / 100.0];+ for (s, v) in self.g.iter_mut().zip(v) {+ s.set(v);+ if snap {+ s.snap();+ }+ }+ }+}++impl AudioEffect for ChannelMixer {+ param_plumbing!("channel_mixer");+ fn reset(&mut self) {+ self.g.iter_mut().for_each(Smoothed::snap);+ }+ fn process(&mut self, channels: &mut [&mut [f32]]) {+ let n = block_len(channels);+ if channels.len() < 2 {+ for i in 0..n {+ let g: Vec4 = self.tick();+ channels[0][i] *= g[0] + g[1];+ }+ return;+ }+ let (a, b) = channels.split_at_mut(1);+ let (l, r) = (&mut a[0], &mut b[0]);+ for i in 0..n {+ let g = self.tick();+ let (x, y) = (l[i], r[i]);+ l[i] = g[0] * x + g[1] * y;+ r[i] = g[2] * x + g[3] * y;+ }+ }+}++type Vec4 = [f32; 4];++impl ChannelMixer {+ #[inline]+ fn tick(&mut self) -> Vec4 {+ [self.g[0].tick(), self.g[1].tick(), self.g[2].tick(), self.g[3].tick()]+ }+}++// --------------------------------------------------------------------------------- distortion++pub const DIST_CURVES: &[&str] = &["Soft Clip", "Hard Clip", "Tube", "Foldback"];++/// Memoryless transfer curves (unity small-signal slope).+#[inline]+pub fn shape(kind: usize, v: f32) -> f32 {+ match kind {+ 0 => v.tanh(),+ 1 => v.clamp(-1.0, 1.0),+ 2 => {+ if v >= 0.0 {+ v.tanh()+ } else {+ (1.6 * v).tanh() / 1.6+ }+ }+ _ => v.sin(),+ }+}++/// Waveshaping distortion: drive, curve, asymmetry (bias, DC-blocked), tone low-pass, output,+/// dry/wet mix.+pub struct Distortion {+ pv: ParamValues,+ sr: f32,+ dc: Vec<DcBlock>,+ lp: Vec<OnePole>,+ drive: Smoothed,+ bias: Smoothed,+ out: Smoothed,+ mix: Smoothed,+}++impl Distortion {+ pub const PARAMS: &'static [ParamSpec] = &[+ ParamSpec::new("drive", "Drive", 0.0, 48.0, 12.0, Unit::Decibels),+ ParamSpec::choice("curve", "Curve", DIST_CURVES, 0),+ ParamSpec::new("symmetry", "Asymmetry", -100.0, 100.0, 0.0, Unit::Percent),+ ParamSpec::log("tone", "Tone", 500.0, 20000.0, 20000.0, Unit::Hertz),+ ParamSpec::new("output", "Output Gain", -48.0, 12.0, 0.0, Unit::Decibels),+ ParamSpec::new("mix", "Mix", 0.0, 100.0, 100.0, Unit::Percent),+ ];++ pub fn new(sample_rate: f32, channels: usize) -> Self {+ let ch = channels.max(1);+ let mut s = Distortion {+ pv: ParamValues::new(Self::PARAMS),+ sr: sample_rate,+ dc: vec![DcBlock::default(); ch],+ lp: vec![OnePole::default(); ch],+ drive: sm(1.0, sample_rate),+ bias: sm(0.0, sample_rate),+ out: sm(1.0, sample_rate),+ mix: sm(1.0, sample_rate),+ };+ s.apply_params(true);+ s+ }++ fn apply_params(&mut self, snap: bool) {+ self.drive.set(db_to_gain(self.pv.v("drive")));+ self.bias.set(0.5 * self.pv.v("symmetry") / 100.0);+ self.out.set(db_to_gain(self.pv.v("output")));+ self.mix.set(self.pv.v("mix") / 100.0);+ if snap {+ for s in [&mut self.drive, &mut self.bias, &mut self.out, &mut self.mix] {+ s.snap();+ }+ }+ }+}++impl AudioEffect for Distortion {+ param_plumbing!("distortion");+ fn reset(&mut self) {+ self.dc.iter_mut().for_each(DcBlock::reset);+ self.lp.iter_mut().for_each(OnePole::reset);+ for s in [&mut self.drive, &mut self.bias, &mut self.out, &mut self.mix] {+ s.snap();+ }+ }+ fn process(&mut self, channels: &mut [&mut [f32]]) {+ let n = block_len(channels);+ let nch = channels.len().min(self.dc.len());+ let kind = self.pv.idx("curve");+ let tone = self.pv.v("tone");+ let a = OnePole::alpha(tone, self.sr);+ let r = DcBlock::r(self.sr);+ for i in 0..n {+ let (d, b, o, m) = (self.drive.tick(), self.bias.tick(), self.out.tick(), self.mix.tick());+ for ch in 0..nch {+ let x = channels[ch][i];+ let mut y = shape(kind, d * x + b) - shape(kind, b);+ y = self.dc[ch].tick(r, y);+ if tone < 19999.0 {+ y = self.lp[ch].lp(a, y);+ }+ channels[ch][i] = x + m * (y * o - x);+ }+ }+ }+}++// -------------------------------------------------------------------------------- GuitarSuite++pub const GS_AMPS: &[&str] = &["None", "Clean Combo", "British Stack", "Tweed", "Modern High Gain"];+pub const GS_FILTERS: &[&str] = &["None", "Low Pass", "High Pass", "Band Pass"];+pub const GS_DIST: &[&str] = &["Soft", "Hard", "Fuzz"];++/// Guitar chain: compressor → distortion → amplifier/cabinet voicing → filter, with mix and+/// output gain.+pub struct GuitarSuite {+ pv: ParamValues,+ sr: f32,+ env: f32,+ cab: [Coeffs; 4],+ filt: Coeffs,+ st: Vec<[Biquad; 5]>,+ dc: Vec<DcBlock>,+ mix: Smoothed,+ out: Smoothed,+ drive: Smoothed,+}++impl GuitarSuite {+ pub const PARAMS: &'static [ParamSpec] = &[+ ParamSpec::new("compressor", "Compressor", 0.0, 100.0, 30.0, Unit::Percent),+ ParamSpec::new("distortion", "Distortion", 0.0, 100.0, 40.0, Unit::Percent),+ ParamSpec::choice("dist_type", "Distortion Type", GS_DIST, 0),+ ParamSpec::choice("amp", "Amplifier", GS_AMPS, 1),+ ParamSpec::choice("filter", "Filter", GS_FILTERS, 0),+ ParamSpec::log("filter_freq", "Filter Frequency", 100.0, 10000.0, 2000.0, Unit::Hertz),+ ParamSpec::new("filter_res", "Filter Resonance", 0.0, 100.0, 20.0, Unit::Percent),+ ParamSpec::new("mix", "Mix", 0.0, 100.0, 100.0, Unit::Percent),+ ParamSpec::new("output", "Output Gain", -24.0, 12.0, 0.0, Unit::Decibels),+ ];++ pub fn new(sample_rate: f32, channels: usize) -> Self {+ let ch = channels.max(1);+ let mut s = GuitarSuite {+ pv: ParamValues::new(Self::PARAMS),+ sr: sample_rate,+ env: 0.0,+ cab: [Coeffs::IDENTITY; 4],+ filt: Coeffs::IDENTITY,+ st: vec![[Biquad::new(); 5]; ch],+ dc: vec![DcBlock::default(); ch],+ mix: sm(1.0, sample_rate),+ out: sm(1.0, sample_rate),+ drive: sm(1.0, sample_rate),+ };+ s.apply_params(true);+ s+ }++ fn apply_params(&mut self, snap: bool) {+ let sr = self.sr as f64;+ let d = |k, f, q, g| Coeffs::design(k, sr, f, q, g);+ use FilterType::*;+ self.cab = match self.pv.idx("amp") {+ 0 => [Coeffs::IDENTITY; 4],+ 1 => [d(HighPass, 70.0, 0.7, 0.0), d(Peaking, 400.0, 0.8, -2.0), d(Peaking, 2500.0, 1.0, 3.0), d(LowPass, 6000.0, 0.8, 0.0)],+ 2 => [d(HighPass, 90.0, 0.7, 0.0), d(Peaking, 800.0, 0.7, 4.0), d(Peaking, 3000.0, 1.2, 2.0), d(LowPass, 4500.0, 0.9, 0.0)],+ 3 => [d(HighPass, 60.0, 0.7, 0.0), d(LowShelf, 200.0, 0.7, 3.0), d(Peaking, 1200.0, 0.8, 2.0), d(LowPass, 4000.0, 0.7, 0.0)],+ _ => [d(HighPass, 100.0, 0.8, 0.0), d(Peaking, 500.0, 1.0, -5.0), d(Peaking, 2000.0, 0.8, 5.0), d(LowPass, 5000.0, 1.0, 0.0)],+ };+ let q = 0.5 + 7.5 * self.pv.v("filter_res") / 100.0;+ let f = self.pv.v("filter_freq") as f64;+ self.filt = match self.pv.idx("filter") {+ 1 => d(LowPass, f, q as f64, 0.0),+ 2 => d(HighPass, f, q as f64, 0.0),+ 3 => d(BandPass, f, q as f64, 0.0),+ _ => Coeffs::IDENTITY,+ };+ self.mix.set(self.pv.v("mix") / 100.0);+ self.out.set(db_to_gain(self.pv.v("output")));+ self.drive.set(db_to_gain(36.0 * self.pv.v("distortion") / 100.0));+ if snap {+ self.mix.snap();+ self.out.snap();+ self.drive.snap();+ }+ }+}++impl AudioEffect for GuitarSuite {+ param_plumbing!("guitar_suite");+ fn reset(&mut self) {+ self.env = 0.0;+ self.st.iter_mut().for_each(|s| s.iter_mut().for_each(Biquad::reset));+ self.dc.iter_mut().for_each(DcBlock::reset);+ self.mix.snap();+ self.out.snap();+ self.drive.snap();+ }+ fn process(&mut self, channels: &mut [&mut [f32]]) {+ let n = block_len(channels);+ let nch = channels.len().min(self.st.len());+ let comp = self.pv.v("compressor") / 100.0;+ let (thr, ratio) = (-6.0 - 30.0 * comp, 1.0 + 7.0 * comp);+ let (att, rel) = (coef(5.0, self.sr), coef(120.0, self.sr));+ let kind = match self.pv.idx("dist_type") {+ 0 => 0,+ 1 => 1,+ _ => 2,+ };+ let r = DcBlock::r(self.sr);+ for i in 0..n {+ let (mix, out, drive) = (self.mix.tick(), self.out.tick(), self.drive.tick());+ let peak = channels[..nch].iter().fold(0.0f32, |a, c| a.max(c[i].abs()));+ let l = lin_db(peak);+ let target = if comp > 0.0 && l > thr { (thr + (l - thr) / ratio) - l } else { 0.0 };+ let c = if target < self.env { att } else { rel };+ self.env = c * self.env + (1.0 - c) * target;+ if self.env.abs() < 1e-7 {+ self.env = 0.0;+ }+ let g = db_to_gain(self.env);+ // Distortion level compensation keeps the output near the input level.+ let comp_out = 1.0 / drive.sqrt();+ for ch in 0..nch {+ let x = channels[ch][i];+ let v = x * g * drive;+ let mut y = match kind {+ 0 => v.tanh(),+ 1 => v.clamp(-1.0, 1.0),+ _ => (v + 0.3).tanh() - 0.3f32.tanh() + 0.5 * (2.0 * v).tanh(),+ } * comp_out;+ y = self.dc[ch].tick(r, y);+ let st = &mut self.st[ch];+ let mut yd = y as f64;+ for (k, c) in self.cab.iter().enumerate() {+ yd = st[k].tick(c, yd);+ }+ yd = st[4].tick(&self.filt, yd);+ channels[ch][i] = x + mix * (yd as f32 * out - x);+ }+ }+ }+}++// --------------------------------------------------------------------------------- mastering++pub const EXCITER_MODES: &[&str] = &["Retro", "Tape", "Tube"];++/// Mastering chain: three-band EQ → reverb → exciter → widener → loudness maximiser → output.+/// At its defaults it is transparent.+pub struct Mastering {+ pv: ParamValues,+ sr: f32,+ eq: [Coeffs; 3],+ st: Vec<[Biquad; 3]>,+ rev: Reverb,+ scratch: [[f32; CHUNK]; 2],+ hp: Vec<OnePole>,+ lim_env: f32,+ rev_amt: Smoothed,+ exc: Smoothed,+ width: Smoothed,+ boost: Smoothed,+ out: Smoothed,+}++impl Mastering {+ pub const PARAMS: &'static [ParamSpec] = &[+ ParamSpec::new("eq_low", "Low Shelf Gain", -12.0, 12.0, 0.0, Unit::Decibels),+ ParamSpec::log("eq_mid_freq", "Peak Frequency", 100.0, 10000.0, 1000.0, Unit::Hertz),+ ParamSpec::new("eq_mid", "Peak Gain", -12.0, 12.0, 0.0, Unit::Decibels),+ ParamSpec::new("eq_high", "High Shelf Gain", -12.0, 12.0, 0.0, Unit::Decibels),+ ParamSpec::new("reverb", "Reverb Amount", 0.0, 100.0, 0.0, Unit::Percent),+ ParamSpec::new("exciter", "Exciter Amount", 0.0, 100.0, 0.0, Unit::Percent),+ ParamSpec::choice("exciter_mode", "Exciter Mode", EXCITER_MODES, 1),+ ParamSpec::new("widener", "Widener", 0.0, 200.0, 100.0, Unit::Percent),+ ParamSpec::new("loudness", "Loudness Maximizer", 0.0, 100.0, 0.0, Unit::Percent),+ ParamSpec::new("output", "Output Gain", -24.0, 12.0, 0.0, Unit::Decibels),+ ];++ pub fn new(sample_rate: f32, channels: usize) -> Self {+ let ch = channels.max(1);+ let mut rev = Reverb::new(sample_rate, 2);+ rev.set_param("mix", 100.0);+ rev.set_param("decay", 1.4);+ rev.set_param("size", 40.0);+ rev.reset();+ let mut s = Mastering {+ pv: ParamValues::new(Self::PARAMS),+ sr: sample_rate,+ eq: [Coeffs::IDENTITY; 3],+ st: vec![[Biquad::new(); 3]; ch],+ rev,+ scratch: [[0.0; CHUNK]; 2],+ hp: vec![OnePole::default(); ch],+ lim_env: 0.0,+ rev_amt: sm(0.0, sample_rate),+ exc: sm(0.0, sample_rate),+ width: sm(1.0, sample_rate),+ boost: sm(1.0, sample_rate),+ out: sm(1.0, sample_rate),+ };+ s.apply_params(true);+ s+ }++ fn apply_params(&mut self, snap: bool) {+ let sr = self.sr as f64;+ let q = std::f64::consts::FRAC_1_SQRT_2;+ self.eq = [+ Coeffs::design(FilterType::LowShelf, sr, 100.0, q, self.pv.v("eq_low") as f64),+ Coeffs::design(FilterType::Peaking, sr, self.pv.v("eq_mid_freq") as f64, 1.0, self.pv.v("eq_mid") as f64),+ Coeffs::design(FilterType::HighShelf, sr, 8000.0, q, self.pv.v("eq_high") as f64),+ ];+ self.rev_amt.set(0.4 * self.pv.v("reverb") / 100.0);+ self.exc.set(0.6 * self.pv.v("exciter") / 100.0);+ self.width.set(self.pv.v("widener") / 100.0);+ self.boost.set(db_to_gain(12.0 * self.pv.v("loudness") / 100.0));+ self.out.set(db_to_gain(self.pv.v("output")));+ if snap {+ for s in [&mut self.rev_amt, &mut self.exc, &mut self.width, &mut self.boost, &mut self.out] {+ s.snap();+ }+ }+ }+}++impl AudioEffect for Mastering {+ param_plumbing!("mastering");+ fn response_db(&self, freq: f64) -> Option<f64> {+ Some(self.eq.iter().map(|c| c.magnitude_db(freq, self.sr as f64)).sum::<f64>() + self.pv.v("output") as f64)+ }+ fn reset(&mut self) {+ self.st.iter_mut().for_each(|s| s.iter_mut().for_each(Biquad::reset));+ self.rev.reset();+ self.hp.iter_mut().for_each(OnePole::reset);+ self.lim_env = 0.0;+ for s in [&mut self.rev_amt, &mut self.exc, &mut self.width, &mut self.boost, &mut self.out] {+ s.snap();+ }+ }+ fn process(&mut self, channels: &mut [&mut [f32]]) {+ let n = block_len(channels);+ let nch = channels.len().min(self.st.len());+ if nch == 0 {+ return;+ }+ let loud = self.pv.v("loudness") > 0.0;+ let use_rev = self.pv.v("reverb") > 0.0;+ let mode = self.pv.idx("exciter_mode");+ let ahp = OnePole::alpha(3000.0, self.sr);+ let ceiling = db_to_gain(-0.3);+ let rel = coef(60.0, self.sr);+ let mut start = 0;+ while start < n {+ let len = (n - start).min(CHUNK);+ // EQ in place.+ for ch in 0..nch {+ for v in channels[ch][start..start + len].iter_mut() {+ let mut y = *v as f64;+ for (k, c) in self.eq.iter().enumerate() {+ y = self.st[ch][k].tick(c, y);+ }+ *v = y as f32;+ }+ }+ if use_rev {+ for i in 0..len {+ self.scratch[0][i] = channels[0][start + i];+ self.scratch[1][i] = channels[nch.min(2) - 1][start + i];+ }+ let [a, b] = &mut self.scratch;+ self.rev.process(&mut [&mut a[..len], &mut b[..len]]);+ }+ for i in 0..len {+ let (ra, ex, w, boost, out) = (self.rev_amt.tick(), self.exc.tick(), self.width.tick(), self.boost.tick(), self.out.tick());+ let mut y = [0.0f32; 2];+ for ch in 0..nch.min(2) {+ let mut v = channels[ch][start + i];+ if use_rev {+ v += ra * self.scratch[ch][i];+ }+ if ex > 0.0 {+ let h = self.hp[ch].hp(ahp, v);+ let s = match mode {+ 0 => (3.0 * h).clamp(-1.0, 1.0) / 3.0,+ 1 => (3.0 * h).tanh() / 3.0,+ _ => ((3.0 * h + 0.2).tanh() - 0.2f32.tanh()) / 3.0,+ };+ v += ex * (s - h * 0.5) * 2.0;+ }+ y[ch] = v;+ }+ if nch >= 2 {+ let (m, s) = (0.5 * (y[0] + y[1]), 0.5 * (y[0] - y[1]) * w);+ y = [m + s, m - s];+ }+ if loud {+ for v in y.iter_mut().take(nch.min(2)) {+ *v *= boost;+ }+ let peak = y[..nch.min(2)].iter().fold(0.0f32, |a, v| a.max(v.abs()));+ let target = (lin_db(ceiling) - lin_db(peak)).min(0.0);+ if target < self.lim_env {+ self.lim_env = target;+ } else {+ self.lim_env = rel * self.lim_env + (1.0 - rel) * target;+ }+ let g = db_to_gain(self.lim_env);+ for v in y.iter_mut().take(nch.min(2)) {+ *v = soft_clip(*v * g, ceiling);+ }+ }+ for ch in 0..nch.min(2) {+ channels[ch][start + i] = y[ch] * out;+ }+ }+ start += len;+ }+ }+}++// ---------------------------------------------------------------------------- vocal enhancer++pub const VOCAL_MODES: &[&str] = &["Male", "Female", "Music"];++/// Fixed voicings: Male / Female (rumble cut, de-mud, presence and air, gentle 2:1+/// compression) or Music (carves the vocal presence range so a voice sits on top).+pub struct VocalEnhancer {+ pv: ParamValues,+ sr: f32,+ eq: [Coeffs; 4],+ st: Vec<[Biquad; 4]>,+ env: f32,+}++impl VocalEnhancer {+ pub const PARAMS: &'static [ParamSpec] = &[ParamSpec::choice("mode", "Mode", VOCAL_MODES, 0)];++ pub fn new(sample_rate: f32, channels: usize) -> Self {+ let mut s = VocalEnhancer {+ pv: ParamValues::new(Self::PARAMS),+ sr: sample_rate,+ eq: [Coeffs::IDENTITY; 4],+ st: vec![[Biquad::new(); 4]; channels.max(1)],+ env: 0.0,+ };+ s.apply_params(true);+ s+ }++ fn apply_params(&mut self, _snap: bool) {+ let sr = self.sr as f64;+ let d = |k, f, q, g| Coeffs::design(k, sr, f, q, g);+ use FilterType::*;+ self.eq = match self.pv.idx("mode") {+ 0 => [d(HighPass, 80.0, 0.707, 0.0), d(Peaking, 250.0, 1.0, -3.0), d(Peaking, 3000.0, 1.0, 3.0), d(HighShelf, 10000.0, 0.707, 1.5)],+ 1 => [d(HighPass, 120.0, 0.707, 0.0), d(Peaking, 400.0, 1.0, -2.0), d(Peaking, 5000.0, 1.0, 3.0), d(HighShelf, 10000.0, 0.707, 2.0)],+ _ => [d(HighPass, 40.0, 0.707, 0.0), d(Peaking, 1500.0, 0.7, -4.0), d(Peaking, 3500.0, 1.0, -2.0), Coeffs::IDENTITY],+ };+ }+}++impl AudioEffect for VocalEnhancer {+ param_plumbing!("vocal_enhancer");+ fn response_db(&self, freq: f64) -> Option<f64> {+ Some(self.eq.iter().map(|c| c.magnitude_db(freq, self.sr as f64)).sum())+ }+ fn reset(&mut self) {+ self.st.iter_mut().for_each(|s| s.iter_mut().for_each(Biquad::reset));+ self.env = 0.0;+ }+ fn process(&mut self, channels: &mut [&mut [f32]]) {+ let n = block_len(channels);+ let nch = channels.len().min(self.st.len());+ let voice = self.pv.idx("mode") < 2;+ let (att, rel) = (coef(5.0, self.sr), coef(150.0, self.sr));+ for i in 0..n {+ for ch in 0..nch {+ let mut y = channels[ch][i] as f64;+ for (k, c) in self.eq.iter().enumerate() {+ y = self.st[ch][k].tick(c, y);+ }+ channels[ch][i] = y as f32;+ }+ if voice {+ let peak = channels[..nch].iter().fold(0.0f32, |a, c| a.max(c[i].abs()));+ let l = lin_db(peak);+ let target = if l > -18.0 { (-18.0 + (l + 18.0) / 2.0) - l } else { 0.0 };+ let c = if target < self.env { att } else { rel };+ self.env = c * self.env + (1.0 - c) * target;+ if self.env.abs() < 1e-7 {+ self.env = 0.0;+ }+ let g = db_to_gain(self.env);+ for ch in channels[..nch].iter_mut() {+ ch[i] *= g;+ }+ }+ }+ }+}++// --------------------------------------------------------------------------- stereo expander++/// Mid/side: the side signal is scaled by Stereo Expand and the centre (mid) signal is panned.+pub struct StereoExpander {+ pv: ParamValues,+ gl: Smoothed,+ gr: Smoothed,+ side: Smoothed,+}++impl StereoExpander {+ pub const PARAMS: &'static [ParamSpec] = &[+ ParamSpec::new("center_pan", "Center Channel Pan", -100.0, 100.0, 0.0, Unit::Pan),+ ParamSpec::new("expand", "Stereo Expand", 0.0, 300.0, 100.0, Unit::Percent),+ ];++ pub fn new(sample_rate: f32, _channels: usize) -> Self {+ let mut s = StereoExpander { pv: ParamValues::new(Self::PARAMS), gl: sm(1.0, sample_rate), gr: sm(1.0, sample_rate), side: sm(1.0, sample_rate) };+ s.apply_params(true);+ s+ }++ fn apply_params(&mut self, snap: bool) {+ let p = self.pv.v("center_pan") / 100.0;+ self.gl.set((1.0 - p).min(1.0));+ self.gr.set((1.0 + p).min(1.0));+ self.side.set(self.pv.v("expand") / 100.0);+ if snap {+ for s in [&mut self.gl, &mut self.gr, &mut self.side] {+ s.snap();+ }+ }+ }+}++impl AudioEffect for StereoExpander {+ param_plumbing!("stereo_expander");+ fn reset(&mut self) {+ for s in [&mut self.gl, &mut self.gr, &mut self.side] {+ s.snap();+ }+ }+ fn process(&mut self, channels: &mut [&mut [f32]]) {+ let n = block_len(channels);+ if channels.len() < 2 {+ return;+ }+ let (a, b) = channels.split_at_mut(1);+ let (l, r) = (&mut a[0], &mut b[0]);+ for i in 0..n {+ let (gl, gr, w) = (self.gl.tick(), self.gr.tick(), self.side.tick());+ let (m, s) = (0.5 * (l[i] + r[i]), 0.5 * (l[i] - r[i]) * w);+ l[i] = m * gl + s;+ r[i] = m * gr - s;+ }+ }+}++// ------------------------------------------------------------------------------ binauralizer++const SPEED_OF_SOUND: f32 = 343.0;++/// Head-shadow filter (one-pole/one-zero spherical-head model, Brown & Duda 1998):+/// H(s) = (1 + α s / 2ω₀) / (1 + s / 2ω₀), ω₀ = c / a, α from the angle of incidence.+#[derive(Clone, Copy, Debug, Default)]+struct Shadow {+ b0: f32,+ b1: f32,+ a1: f32,+ x1: f32,+ y1: f32,+}++impl Shadow {+ fn design(incidence_deg: f32, radius: f32, sr: f32) -> Shadow {+ let alpha = 1.05 + 0.95 * (incidence_deg / 150.0 * PI).cos();+ let w0 = SPEED_OF_SOUND / radius;+ let k = 2.0 * sr;+ let t = k / (2.0 * w0);+ let a0 = 1.0 + t;+ Shadow { b0: (1.0 + alpha * t) / a0, b1: (1.0 - alpha * t) / a0, a1: (1.0 - t) / a0, x1: 0.0, y1: 0.0 }+ }+ #[inline]+ fn tick(&mut self, x: f32) -> f32 {+ let y = self.b0 * x + self.b1 * self.x1 - self.a1 * self.y1;+ self.x1 = x;+ self.y1 = if y.abs() < 1e-25 { 0.0 } else { y };+ y+ }+ fn set_coeffs(&mut self, o: &Shadow) {+ self.b0 = o.b0;+ self.b1 = o.b1;+ self.a1 = o.a1;+ }+}++/// Renders the stereo input as two virtual loudspeakers at ±`angle` heard through a spherical+/// head model (Woodworth interaural time difference + head-shadow filtering), for headphones.+pub struct Binauralizer {+ pv: ParamValues,+ sr: f32,+ lines: [DelayLine; 2],+ /// near-L, far-L→R, near-R, far-R→L+ sh: [Shadow; 4],+ itd: Smoothed,+ mix: Smoothed,+}++impl Binauralizer {+ pub const PARAMS: &'static [ParamSpec] = &[+ ParamSpec::new("angle", "Speaker Angle", 0.0, 90.0, 30.0, Unit::None),+ ParamSpec::new("head_size", "Head Size", 12.0, 24.0, 17.5, Unit::None),+ ParamSpec::new("mix", "Mix", 0.0, 100.0, 100.0, Unit::Percent),+ ];++ pub fn new(sample_rate: f32, _channels: usize) -> Self {+ let max = (0.002 * sample_rate) as usize + 4;+ let mut s = Binauralizer {+ pv: ParamValues::new(Self::PARAMS),+ sr: sample_rate,+ lines: [DelayLine::new(max), DelayLine::new(max)],+ sh: [Shadow::default(); 4],+ itd: sm(0.0, sample_rate),+ mix: sm(1.0, sample_rate),+ };+ s.apply_params(true);+ s+ }++ fn apply_params(&mut self, snap: bool) {+ let theta = self.pv.v("angle");+ let a = self.pv.v("head_size") * 0.01 / 2.0;+ // Ears at ±90°: near ear sees the source at 90° − θ off its axis, the far ear 90° + θ.+ let near = Shadow::design(90.0 - theta, a, self.sr);+ let far = Shadow::design(90.0 + theta, a, self.sr);+ for (k, s) in self.sh.iter_mut().enumerate() {+ s.set_coeffs(if k % 2 == 0 { &near } else { &far });+ }+ let th = theta.to_radians();+ self.itd.set(a / SPEED_OF_SOUND * (th + th.sin()) * self.sr);+ self.mix.set(self.pv.v("mix") / 100.0);+ if snap {+ self.itd.snap();+ self.mix.snap();+ }+ }+}++impl AudioEffect for Binauralizer {+ param_plumbing!("binauralizer");+ fn reset(&mut self) {+ self.lines.iter_mut().for_each(DelayLine::reset);+ for s in &mut self.sh {+ s.x1 = 0.0;+ s.y1 = 0.0;+ }+ self.itd.snap();+ self.mix.snap();+ }+ fn process(&mut self, channels: &mut [&mut [f32]]) {+ let n = block_len(channels);+ if channels.len() < 2 {+ return;+ }+ let (a, b) = channels.split_at_mut(1);+ let (l, r) = (&mut a[0], &mut b[0]);+ for i in 0..n {+ let (itd, mix) = (self.itd.tick(), self.mix.tick());+ let (xl, xr) = (l[i], r[i]);+ self.lines[0].push(xl);+ self.lines[1].push(xr);+ let near_l = self.sh[0].tick(xl);+ let far_l = self.sh[1].tick(self.lines[0].read(itd));+ let near_r = self.sh[2].tick(xr);+ let far_r = self.sh[3].tick(self.lines[1].read(itd));+ let (bl, br) = (0.5 * (near_l + far_r), 0.5 * (near_r + far_l));+ l[i] = xl + mix * (bl - xl);+ r[i] = xr + mix * (br - xr);+ }+ }+}++// ------------------------------------------------------------------------- ambisonics panner++/// Rotates the sound field (pan / tilt / roll) of a stereo source pair placed at ±30° and+/// re-renders it to stereo with constant-power panning; sources turned behind the listener+/// are attenuated, raised/lowered sources slightly softened. Identity at 0/0/0.+pub struct AmbisonicsPanner {+ pv: ParamValues,+ /// out L ← in L, out L ← in R, out R ← in L, out R ← in R+ m: [Smoothed; 4],+}++impl AmbisonicsPanner {+ pub const PARAMS: &'static [ParamSpec] = &[+ ParamSpec::new("pan", "Pan", -180.0, 180.0, 0.0, Unit::None),+ ParamSpec::new("tilt", "Tilt", -90.0, 90.0, 0.0, Unit::None),+ ParamSpec::new("roll", "Roll", -180.0, 180.0, 0.0, Unit::None),+ ];++ pub fn new(sample_rate: f32, _channels: usize) -> Self {+ let mut s = AmbisonicsPanner {+ pv: ParamValues::new(Self::PARAMS),+ m: [sm(1.0, sample_rate), sm(0.0, sample_rate), sm(0.0, sample_rate), sm(1.0, sample_rate)],+ };+ s.apply_params(true);+ s+ }++ /// (left gain, right gain) for a source at azimuth `az` (degrees, + = left) after rotation.+ pub fn source_gains(az: f32, pan: f32, tilt: f32, roll: f32) -> (f32, f32) {+ let (az, el) = (az.to_radians(), 0.0f32);+ // x forward, y left, z up+ let mut v = [el.cos() * az.cos(), el.cos() * az.sin(), el.sin()];+ let rot = |v: [f32; 3], axis: usize, ang: f32| -> [f32; 3] {+ let (s, c) = ang.to_radians().sin_cos();+ let [x, y, z] = v;+ match axis {+ 0 => [x, c * y - s * z, s * y + c * z],+ 1 => [c * x + s * z, y, -s * x + c * z],+ _ => [c * x - s * y, s * x + c * y, z],+ }+ };+ v = rot(v, 0, roll);+ v = rot(v, 1, tilt);+ v = rot(v, 2, pan);+ let p = (v[1] / 30f32.to_radians().sin()).clamp(-1.0, 1.0);+ // constant power: p = 1 → all left, −1 → all right+ let a = (1.0 - p) * 0.5 * FRAC_PI_2;+ let (mut gl, mut gr) = (a.cos(), a.sin());+ let att = (1.0 - 0.3 * (-v[0]).max(0.0)) * (1.0 - 0.2 * v[2].abs());+ gl *= att;+ gr *= att;+ (gl, gr)+ }++ fn apply_params(&mut self, snap: bool) {+ let (pan, tilt, roll) = (self.pv.v("pan"), self.pv.v("tilt"), self.pv.v("roll"));+ let (ll, rl) = Self::source_gains(30.0, pan, tilt, roll);+ let (lr, rr) = Self::source_gains(-30.0, pan, tilt, roll);+ let clean = |v: f32| {+ if v.abs() < 1e-6 {+ 0.0+ } else if (v - 1.0).abs() < 1e-6 {+ 1.0+ } else {+ v+ }+ };+ for (s, v) in self.m.iter_mut().zip([ll, lr, rl, rr]) {+ s.set(clean(v));+ if snap {+ s.snap();+ }+ }+ }+}++impl AudioEffect for AmbisonicsPanner {+ param_plumbing!("ambisonics_panner");+ fn reset(&mut self) {+ self.m.iter_mut().for_each(Smoothed::snap);+ }+ fn process(&mut self, channels: &mut [&mut [f32]]) {+ let n = block_len(channels);+ if channels.len() < 2 {+ return;+ }+ let (a, b) = channels.split_at_mut(1);+ let (l, r) = (&mut a[0], &mut b[0]);+ for i in 0..n {+ let g = [self.m[0].tick(), self.m[1].tick(), self.m[2].tick(), self.m[3].tick()];+ let (x, y) = (l[i], r[i]);+ l[i] = g[0] * x + g[1] * y;+ r[i] = g[2] * x + g[3] * y;+ }+ }+}++// ------------------------------------------------------------------------------- loudness meter++/// Pass-through effect that measures BS.1770 loudness (momentary, short-term, integrated,+/// range, true peak) of the signal at its insert point.+pub struct LoudnessMeterFx {+ pv: ParamValues,+ meter: LoudnessMeter,+}++impl LoudnessMeterFx {+ pub const PARAMS: &'static [ParamSpec] = &[ParamSpec::new("target", "Target Loudness", -36.0, -5.0, -23.0, Unit::None)];++ pub fn new(sample_rate: f32, channels: usize) -> Self {+ LoudnessMeterFx { pv: ParamValues::new(Self::PARAMS), meter: LoudnessMeter::new(sample_rate as f64, channels.clamp(1, 2)) }+ }+ fn apply_params(&mut self, _snap: bool) {}++ /// The running meter.+ pub fn meter(&self) -> &LoudnessMeter {+ &self.meter+ }+}++impl AudioEffect for LoudnessMeterFx {+ param_plumbing!("loudness_meter");+ fn reset(&mut self) {+ self.meter.reset();+ }+ fn process(&mut self, channels: &mut [&mut [f32]]) {+ let n = block_len(channels);+ let nch = self.meter.channels().min(channels.len());+ if nch == 0 || n == 0 {+ return;+ }+ if nch == 1 {+ self.meter.process(&[&channels[0][..n]]);+ } else {+ self.meter.process(&[&channels[0][..n], &channels[1][..n]]);+ }+ }+}++// ----------------------------------------------------------------------------------- mute++/// Mute with a 5 ms ramp (keyframe it to silence passages without clicks).+pub struct Mute {+ pv: ParamValues,+ g: Smoothed,+}++impl Mute {+ pub const PARAMS: &'static [ParamSpec] = &[ParamSpec::toggle("mute", "Mute", false)];++ pub fn new(sample_rate: f32, _channels: usize) -> Self {+ let mut s = Mute { pv: ParamValues::new(Self::PARAMS), g: Smoothed::with_ms(1.0, sample_rate, 5.0) };+ s.apply_params(true);+ s+ }+ fn apply_params(&mut self, snap: bool) {+ self.g.set(if self.pv.on("mute") { 0.0 } else { 1.0 });+ if snap {+ self.g.snap();+ }+ }+}++impl AudioEffect for Mute {+ param_plumbing!("mute");+ fn reset(&mut self) {+ self.g.snap();+ }+ fn process(&mut self, channels: &mut [&mut [f32]]) {+ let n = block_len(channels);+ for i in 0..n {+ let g = self.g.tick();+ for ch in channels.iter_mut() {+ ch[i] *= g;+ }+ }+ }+}diff --git a/crates/audio-dsp/src/effects/util.rs b/crates/audio-dsp/src/effects/util.rsnew file mode 100644index 000000000..abb11d593--- /dev/null+++ b/crates/audio-dsp/src/effects/util.rs@@ -0,0 +1,246 @@+//! Small building blocks shared by the effect implementations: delay lines with fractional+//! reads, LFOs, one-pole filters, envelope followers.++use crate::{flush, flush32};+use std::f64::consts::PI;++/// One-pole smoothing coefficient for a time constant in ms (0 → instant).+#[inline]+pub(crate) fn coef(ms: f32, sr: f32) -> f32 {+ if ms <= 0.0 { 0.0 } else { (-1.0 / (ms * 0.001 * sr)).exp() }+}++/// Linear → dB with a −200 dB floor.+#[inline]+pub(crate) fn lin_db(x: f32) -> f32 {+ 20.0 * x.max(1e-10).log10()+}++/// Circular delay line with linear-interpolated fractional reads.+#[derive(Clone, Debug)]+pub(crate) struct DelayLine {+ buf: Vec<f32>,+ w: usize,+}++impl DelayLine {+ /// A line that can delay by up to `max` samples.+ pub(crate) fn new(max: usize) -> Self {+ DelayLine { buf: vec![0.0; max + 3], w: 0 }+ }+ pub(crate) fn reset(&mut self) {+ self.buf.iter_mut().for_each(|v| *v = 0.0);+ self.w = 0;+ }+ /// Longest usable delay in samples.+ pub(crate) fn max_delay(&self) -> f32 {+ (self.buf.len() - 3) as f32+ }+ /// Sample written `d` samples ago (`d` ≥ 0; 0 = the sample written by the last `push`).+ #[inline]+ pub(crate) fn read(&self, d: f32) -> f32 {+ let len = self.buf.len();+ let d = d.clamp(0.0, self.max_delay());+ let di = d.floor();+ let frac = d - di;+ let i0 = (self.w + len - 1 - di as usize) % len;+ let i1 = (i0 + len - 1) % len;+ self.buf[i0] + (self.buf[i1] - self.buf[i0]) * frac+ }+ /// Integer read (`d` samples ago, 0 = newest).+ #[inline]+ pub(crate) fn tap(&self, d: usize) -> f32 {+ let len = self.buf.len();+ self.buf[(self.w + len - 1 - d.min(len - 1)) % len]+ }+ #[inline]+ pub(crate) fn push(&mut self, x: f32) {+ self.buf[self.w] = flush32(x);+ self.w += 1;+ if self.w == self.buf.len() {+ self.w = 0;+ }+ }+}++/// Phase accumulator LFO (phase in cycles, 0..1).+#[derive(Clone, Copy, Debug, Default)]+pub(crate) struct Lfo {+ phase: f64,+}++impl Lfo {+ pub(crate) fn reset(&mut self) {+ self.phase = 0.0;+ }+ /// Current phase plus `offset` (cycles), wrapped to 0..1.+ #[inline]+ pub(crate) fn phase(&self, offset: f64) -> f64 {+ (self.phase + offset).rem_euclid(1.0)+ }+ #[inline]+ pub(crate) fn advance(&mut self, hz: f32, sr: f32) {+ self.phase += hz as f64 / sr as f64;+ if self.phase >= 1.0 {+ self.phase -= self.phase.floor();+ }+ }+}++/// Sine of a phase in cycles, mapped to 0..1.+#[inline]+pub(crate) fn uni_sine(phase: f64) -> f32 {+ (0.5 - 0.5 * (2.0 * PI * phase).cos()) as f32+}++/// Triangle of a phase in cycles, 0..1.+#[inline]+pub(crate) fn uni_tri(phase: f64) -> f32 {+ (if phase < 0.5 { 2.0 * phase } else { 2.0 - 2.0 * phase }) as f32+}++/// One-pole low-pass (`y += a (x − y)`), coefficient from a cutoff frequency.+#[derive(Clone, Copy, Debug, Default)]+pub(crate) struct OnePole {+ y: f64,+}++impl OnePole {+ /// Coefficient for a −3 dB cutoff at `hz` (matched-z).+ pub(crate) fn alpha(hz: f32, sr: f32) -> f64 {+ 1.0 - (-2.0 * PI * (hz.clamp(1.0, sr * 0.49) as f64) / sr as f64).exp()+ }+ #[inline]+ pub(crate) fn lp(&mut self, a: f64, x: f32) -> f32 {+ self.y = flush(self.y + a * (x as f64 - self.y));+ self.y as f32+ }+ /// High-pass as the complement of the low-pass.+ #[inline]+ pub(crate) fn hp(&mut self, a: f64, x: f32) -> f32 {+ x - self.lp(a, x)+ }+ pub(crate) fn reset(&mut self) {+ self.y = 0.0;+ }+}++/// DC blocker (`y = x − x₁ + R·y₁`, R ≈ 0.995 at 48 kHz → ~20 Hz).+#[derive(Clone, Copy, Debug, Default)]+pub(crate) struct DcBlock {+ x1: f64,+ y1: f64,+}++impl DcBlock {+ pub(crate) fn r(sr: f32) -> f64 {+ 1.0 - 2.0 * PI * 20.0 / sr as f64+ }+ #[inline]+ pub(crate) fn tick(&mut self, r: f64, x: f32) -> f32 {+ let y = x as f64 - self.x1 + r * self.y1;+ self.x1 = x as f64;+ self.y1 = flush(y);+ y as f32+ }+ pub(crate) fn reset(&mut self) {+ *self = DcBlock::default();+ }+}++/// First-order all-pass section `H(z) = (a + z⁻¹) / (1 + a z⁻¹)`.+#[derive(Clone, Copy, Debug, Default)]+pub(crate) struct AllPass1 {+ x1: f64,+ y1: f64,+}++impl AllPass1 {+ /// Coefficient placing the 90° phase point at `hz`.+ pub(crate) fn coef(hz: f32, sr: f32) -> f64 {+ let t = (PI * (hz.clamp(1.0, sr * 0.49) as f64) / sr as f64).tan();+ (t - 1.0) / (t + 1.0)+ }+ #[inline]+ pub(crate) fn tick(&mut self, a: f64, x: f64) -> f64 {+ let y = a * x + self.x1 - a * self.y1;+ self.x1 = x;+ self.y1 = flush(y);+ y+ }+ pub(crate) fn reset(&mut self) {+ *self = AllPass1::default();+ }+}++/// Peak envelope follower with separate attack / release coefficients (linear domain).+#[derive(Clone, Copy, Debug, Default)]+pub(crate) struct Envelope {+ pub(crate) env: f32,+}++impl Envelope {+ #[inline]+ pub(crate) fn tick(&mut self, att: f32, rel: f32, x: f32) -> f32 {+ let c = if x > self.env { att } else { rel };+ self.env = c * self.env + (1.0 - c) * x;+ if self.env < 1e-20 {+ self.env = 0.0;+ }+ self.env+ }+}++/// Tiny deterministic PRNG (xorshift64*) for generated impulse responses.+#[derive(Clone, Debug)]+pub(crate) struct Prng(u64);++impl Prng {+ pub(crate) fn new(seed: u64) -> Self {+ Prng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1)+ }+ pub(crate) fn next_u64(&mut self) -> u64 {+ let mut x = self.0;+ x ^= x >> 12;+ x ^= x << 25;+ x ^= x >> 27;+ self.0 = x;+ x.wrapping_mul(0x2545_F491_4F6C_DD1D)+ }+ /// Uniform in [-1, 1).+ pub(crate) fn uniform(&mut self) -> f32 {+ ((self.next_u64() >> 40) as f32 / (1u64 << 24) as f32) * 2.0 - 1.0+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn delay_line_reads_integer_and_fractional() {+ let mut d = DelayLine::new(8);+ for i in 0..5 {+ d.push(i as f32);+ }+ assert_eq!(d.read(0.0), 4.0);+ assert_eq!(d.tap(2), 2.0);+ assert!((d.read(1.5) - 2.5).abs() < 1e-6);+ }++ #[test]+ fn allpass_is_unit_magnitude() {+ let a = AllPass1::coef(1000.0, 48000.0);+ let mut ap = AllPass1::default();+ let mut e_in = 0.0;+ let mut e_out = 0.0;+ let mut r = Prng::new(3);+ for _ in 0..48000 {+ let x = r.uniform() as f64;+ let y = ap.tick(a, x);+ e_in += x * x;+ e_out += y * y;+ }+ assert!((e_out / e_in - 1.0).abs() < 0.01);+ }+}diff --git a/crates/audio-dsp/src/lib.rs b/crates/audio-dsp/src/lib.rsindex 7af30a29e..6c1f34159 100644--- a/crates/audio-dsp/src/lib.rs+++ b/crates/audio-dsp/src/lib.rs@@ -16,6 +16,7 @@//! portable to wasm).pub mod biquad;+pub mod design;pub mod ducking;pub mod effects;pub mod fft;@@ -126,6 +127,16 @@ pub trait AudioEffect: Send {fn latency(&self) -> usize {0}+ /// Analytic magnitude response (dB) at `freq` Hz for the current target settings, for+ /// filter/EQ effects (drives the graphical EQ editors). `None` when not applicable.+ fn response_db(&self, _freq: f64) -> Option<f64> {+ None+ }+ /// Static input → output level curve (dB) of a dynamics effect for `band` (0 for+ /// single-band processors), at the current settings. `None` when not applicable.+ fn transfer_db(&self, _band: usize, _input_db: f32) -> Option<f32> {+ None+ }}/// Parameter value storage shared by the effect implementations.diff --git a/docs/testing.md b/docs/testing.mdindex 3a6c49bf4..07f96611d 100644--- a/docs/testing.md+++ b/docs/testing.md@@ -76,6 +76,7 @@ are never linked or shipped ([AGENTS.md](../AGENTS.md) §2).| `isobmff` | `ffprobe -show_packets` on ffmpeg-made MP4/MOV | packet offsets, sizes, pts/dts, durations, key flags and stream parameters equal; remuxed files decode with `ffmpeg -v error` silent || `matroska` | `ffprobe -show_packets` | every packet (stream, size, key flag, pts, duration) equal; seeks land on the latest keyframe ≤ target || `audio-dsp` loudness | `tests/loudness_oracle.rs`: signals generated in Rust (997 Hz sine, pink noise at 48/96 kHz, speech-like bursts at 48/44.1 kHz, stereo with silence and sub-gate passages, an fs/4 inter-sample-peak tone) written as float WAV and measured with `ffmpeg -af ebur128=peak=true:metadata=1` | momentary and short-term every 100 ms **±0.1 LU**, integrated **±0.1 LU**, LRA **±0.5 LU**, true peak **±0.2 dB** (against the analytic value when one exists). Measured: ΔM/ΔS ≤ 0.0005 LU, ΔI ≤ 0.007 LU, ΔLRA ≤ 0.04 LU, ΔTP ≤ 0.045 dB against ffmpeg. On the fs/4 tone ffmpeg's own true peak is +0.6 dB high (−0.32 vs the analytic −0.92 dBTP); ours is −0.05 dB |+| `audio-dsp` effects | `src/effects/premiere_tests.rs`, `src/design.rs`, registry tests in `src/effects/mod.rs`: generated tones, noise and impulses | every effect: neutral settings = delayed identity (≤ 2·10⁻⁴), bit-exact determinism, latency constant and equal to where an impulse lands, block-size independence, finite / denormal-free tails at extreme settings, > 1× realtime; per effect a level or frequency-response check (measured tone vs analytic `response_db` within 0.1–0.2 dB, Butterworth vs closed form 10⁻⁶ dB, Chebyshev/elliptic ripple and stop-band bounds, LR4 crossover sum flat within 0.02 dB, comb-notch depth, echo positions to the sample, Schroeder RT60 of generated impulses within 25 %, click repair −20 dB) || `export` | our own demuxer/decoder reads the file back; ffprobe counts frames when present | expected size, duration, colour, audio level; exact frame count |Each codec README has the full fixture matrix and the measured results.