Skip to content

FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust

M7.4: Essential Sound DSP — DeEsser, DeReverb, Enhance Speech chain, Stereo Width, ducking analysis

Brandon Thomascd30edbed726
diff --git a/crates/audio-dsp/README.md b/crates/audio-dsp/README.md
index e1ae13a6c..83928438c 100644
--- a/crates/audio-dsp/README.md
+++ b/crates/audio-dsp/README.md
@@ -3,7 +3,8 @@
Real-time audio DSP for FilmCraft. Layer **L1**, **no dependencies**, compiles for
`wasm32-unknown-unknown`, no `unsafe`. Clean-room: written from the public standards
(ITU-R BS.1770-4, EBU R128 / Tech 3341 / Tech 3342) and textbook DSP (RBJ cookbook biquads,
-Householder FDN, phase vocoder).
+Householder FDN, phase vocoder, spectral subtraction with the statistical late-reverberation
+model).
## Conventions
@@ -50,6 +51,43 @@ id, name, range, default, `Unit`, log-scale hint and choice labels so UIs can be
| `dehum` | 50/60 Hz notch comb with up to 10 harmonics |
| `denoise` | STFT spectral gating, minimum-statistics noise floor (latency = FFT size) |
| `pitch_shifter` | ±12 semitones, phase vocoder with peak shifting + phase locking (latency = FFT size) |
+| `deesser` | high-pass sidechain at `frequency` (2–12 kHz) detects sibilance relative to the broadband level (`threshold`); a dynamic high shelf cuts the band by up to `reduction` dB (1 ms / 60 ms, stereo-linked); exact identity when idle |
+| `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) |
+
+Essential Sound builds on these (Repair: `denoise`, high-pass via `parametric_eq`, `dehum`,
+`deesser`, `dereverb`; Clarity: `compressor`, `simple_eq`, `speech_enhance`; Creative: `reverb`,
+`stereo_width`).
+
+**Enhance Speech decision.** No machine-learning model is bundled: we found no openly licensed
+speech-enhancement model that is also practical to ship here (pure Rust, wasm, asset rules).
+DeepFilterNet (MIT/Apache-2.0, with a Rust implementation on `tract`) is the candidate for a future
+optional integration behind a trait outside this dependency-free crate, once its weights' licence and
+size are vetted as an asset. Until then `speech_enhance` is the DSP chain above.
+
+Measured on synthetic signals (`effects::essential::tests`, 48 kHz):
+
+| Effect | Signal | Result |
+|---|---|---|
+| `deesser` | 150 Hz harmonic voice + 5–10 kHz noise bursts | sibilance −5.1 dB (8 dB max) / −9.8 dB (16 dB max) during bursts; voice band ±0.01 dB; non-sibilant passages ±0.001 dB |
+| `dereverb` (100 %) | harmonic syllables (100 ms / 400 ms gaps) + Polack-model late reverb, RT60 0.8 s | tail-to-burst energy −5.0 → −10.1 dB (5.0 dB better); burst energy −1.7 dB |
+| `speech_enhance` | voice + fricative noise syllables over −60 dBFS noise | presence/mud tilt +5.5 dB; noise between syllables −8.7 dB; overall level +1.0 dB |
+| Dialogue chain | `denoise` + `parametric_eq` (2 HP bands) + `dehum` + `deesser` + `dereverb` + `compressor` + `simple_eq` + `speech_enhance` + `reverb`, 60 s stereo | 1.36 s = **44× realtime** on one core (release, Apple Silicon; `cargo test --release -p filmcraft-audio-dsp dialogue_chain_realtime -- --ignored --nocapture`) |
+
+## Ducking analysis (`ducking`)
+
+Pure functions for Essential Sound auto-ducking:
+
+- `envelope_db(channels, sample_rate, hop_s, window_s)`: centred-window RMS level per hop (dBFS,
+ channel-averaged power, floor −120).
+- `activity(env_db, hop_s, threshold_db, min_on_s, bridge_s)`: regions above the threshold; gaps
+ shorter than `bridge_s` are merged first, then regions shorter than `min_on_s` are dropped.
+- `sensitivity_threshold_db(s)`: Sensitivity 0–10 → −20 − 4·s dBFS.
+- `duck_keyframes(regions, clip_start, clip_end, base_db, reduce_db, fade_s)`: (time, dB) volume
+ keyframes — ramp down over `fade_s` before each region, hold, ramp up after; overlapping ramps
+ merge; clamped to the clip (a ramp cut by an edge gets the ramp's value at the edge); strictly
+ increasing times.
## Known limits
diff --git a/crates/audio-dsp/src/ducking.rs b/crates/audio-dsp/src/ducking.rs
new file mode 100644
index 000000000..1ae11f563
--- /dev/null
+++ b/crates/audio-dsp/src/ducking.rs
@@ -0,0 +1,229 @@
+//! Offline analysis for Essential Sound auto-ducking: level envelope of the trigger audio
+//! (dialogue, SFX…), activity detection with blip removal and gap bridging, and the volume
+//! keyframes that duck a music clip under the detected regions.
+//!
+//! Pure functions on plain slices; times are seconds, levels dBFS / dB.
+
+/// Level floor (dBFS) for silence.
+pub const FLOOR_DB: f32 = -120.0;
+
+/// RMS level (dBFS) per hop: value `k` is the RMS of the window of `window_s` seconds centred on
+/// `k · hop_s` (clipped at the signal edges), with the power averaged over channels. The result
+/// has `ceil(len / hop)` entries; silence reads [`FLOOR_DB`].
+pub fn envelope_db(channels: &[&[f32]], sample_rate: f32, hop_s: f32, window_s: f32) -> Vec<f32> {
+ let len = channels.iter().map(|c| c.len()).min().unwrap_or(0);
+ if len == 0 || channels.is_empty() {
+ return Vec::new();
+ }
+ let hop = ((hop_s * sample_rate).round() as usize).max(1);
+ let half = ((window_s * sample_rate / 2.0).round() as usize).max(1);
+ // prefix sums of the channel-averaged power
+ let nch = channels.len() as f64;
+ let mut pre = Vec::with_capacity(len + 1);
+ pre.push(0.0f64);
+ let mut acc = 0.0f64;
+ for i in 0..len {
+ let p: f64 = channels.iter().map(|c| (c[i] as f64) * (c[i] as f64)).sum::<f64>() / nch;
+ acc += p;
+ pre.push(acc);
+ }
+ (0..len.div_ceil(hop))
+ .map(|k| {
+ let c = k * hop;
+ let (a, b) = (c.saturating_sub(half), (c + half).min(len));
+ let ms = (pre[b] - pre[a]).max(0.0) / (b - a).max(1) as f64;
+ if ms <= 1e-12 { FLOOR_DB } else { ((10.0 * ms.log10()) as f32).max(FLOOR_DB) }
+ })
+ .collect()
+}
+
+/// Regions `(start_s, end_s)` where the envelope exceeds `threshold_db`. Gaps shorter than
+/// `bridge_s` are merged first, then regions shorter than `min_on_s` are dropped. A frame `k`
+/// covers `[k·hop, (k+1)·hop)`.
+pub fn activity(env_db: &[f32], hop_s: f32, threshold_db: f32, min_on_s: f32, bridge_s: f32) -> Vec<(f64, f64)> {
+ // the f32 hop rounded to whole microseconds, so 0.01 means exactly 0.01 s
+ let hop = (hop_s as f64 * 1e6).round() / 1e6;
+ let mut raw: Vec<(f64, f64)> = Vec::new();
+ let mut start: Option<usize> = None;
+ for (k, &v) in env_db.iter().enumerate() {
+ match (v > threshold_db, start) {
+ (true, None) => start = Some(k),
+ (false, Some(s)) => {
+ raw.push((s as f64 * hop, k as f64 * hop));
+ start = None;
+ }
+ _ => {}
+ }
+ }
+ if let Some(s) = start {
+ raw.push((s as f64 * hop, env_db.len() as f64 * hop));
+ }
+ let mut merged: Vec<(f64, f64)> = Vec::new();
+ for r in raw {
+ match merged.last_mut() {
+ Some(last) if r.0 - last.1 < bridge_s as f64 - 1e-9 => last.1 = r.1,
+ _ => merged.push(r),
+ }
+ }
+ merged.retain(|(a, b)| b - a >= min_on_s as f64 - 1e-9);
+ merged
+}
+
+/// Essential Sound ducking "Sensitivity" (0…10) → detection threshold in dBFS:
+/// `−20 − 4·s` (5 → −40 dBFS; higher sensitivity reacts to quieter triggers).
+pub fn sensitivity_threshold_db(sensitivity: f32) -> f32 {
+ -20.0 - 4.0 * sensitivity.clamp(0.0, 10.0)
+}
+
+/// Volume keyframes `(time_s, level_db)` that duck by `reduce_db` under each region: ramp from
+/// `base_db` at `a − fade` down to `base_db − reduce_db` at `a`, hold until `b`, ramp back up to
+/// `base_db` at `b + fade`. Regions whose ramps would overlap are merged (the level stays
+/// ducked between them). Everything is clamped to `[clip_start_s, clip_end_s]`; a ramp cut by a
+/// clip edge gets a keyframe at the edge with the ramp's value there (fully ducked when the region
+/// itself reaches the edge). Times are strictly increasing; no regions → no keyframes. `fade_s` is
+/// at least 1 ms so a ramp never collapses into two keyframes at the same time.
+pub fn duck_keyframes(regions: &[(f64, f64)], clip_start_s: f64, clip_end_s: f64, base_db: f64, reduce_db: f64, fade_s: f64) -> Vec<(f64, f64)> {
+ let fade = fade_s.max(1e-3);
+ let ducked = base_db - reduce_db.abs();
+ let mut sorted: Vec<(f64, f64)> = regions.iter().copied().filter(|(a, b)| b > a && *b > clip_start_s && *a < clip_end_s).collect();
+ sorted.sort_by(|x, y| x.0.total_cmp(&y.0));
+ // merge regions whose ramps touch or overlap
+ let mut groups: Vec<(f64, f64)> = Vec::new();
+ for r in sorted {
+ match groups.last_mut() {
+ Some(g) if r.0 - fade <= g.1 + fade => g.1 = g.1.max(r.1),
+ _ => groups.push(r),
+ }
+ }
+ let mut out: Vec<(f64, f64)> = Vec::new();
+ let mut push = |t: f64, v: f64| {
+ if t < clip_start_s || t > clip_end_s {
+ return;
+ }
+ match out.last_mut() {
+ Some(last) if t <= last.0 + 1e-9 => {
+ last.1 = v;
+ }
+ _ => out.push((t, v)),
+ }
+ };
+ // value of the down-ramp ending at `a` / up-ramp starting at `b`, at time t
+ let down = |a: f64, t: f64| base_db + (ducked - base_db) * ((t - (a - fade)) / fade).clamp(0.0, 1.0);
+ let up = |b: f64, t: f64| ducked + (base_db - ducked) * ((t - b) / fade).clamp(0.0, 1.0);
+ for (a, b) in groups {
+ let ramp_start = a - fade;
+ if ramp_start >= clip_start_s {
+ push(ramp_start, base_db);
+ } else {
+ push(clip_start_s, down(a, clip_start_s));
+ }
+ push(a.max(clip_start_s), ducked);
+ if b < clip_end_s {
+ push(b, ducked);
+ if b + fade <= clip_end_s {
+ push(b + fade, base_db);
+ } else {
+ push(clip_end_s, up(b, clip_end_s));
+ }
+ } else {
+ push(clip_end_s, ducked);
+ }
+ }
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn envelope_levels() {
+ let sr = 1000.0;
+ // 1 s silence, 1 s of a ±0.1 square wave (−20 dBFS RMS)
+ let x: Vec<f32> = (0..2000)
+ .map(|i| {
+ if i < 1000 {
+ 0.0
+ } else if i % 2 == 0 {
+ 0.1
+ } else {
+ -0.1
+ }
+ })
+ .collect();
+ let e = envelope_db(&[&x, &x], sr, 0.01, 0.02);
+ assert_eq!(e.len(), 200);
+ assert_eq!(e[10], FLOOR_DB);
+ assert!((e[150] + 20.0).abs() < 0.01, "{}", e[150]);
+ // the window straddling the edge is in between
+ assert!(e[100] < -20.0 && e[100] > -30.0);
+ assert!(envelope_db(&[], sr, 0.01, 0.02).is_empty());
+ }
+
+ #[test]
+ fn activity_bridges_then_drops_blips() {
+ let hop = 0.01;
+ let mut env = vec![-80.0f32; 300];
+ // speech 0.50–1.00 and 1.10–1.50 (gap 0.1 s → bridged), blip 2.00–2.03 (dropped)
+ for (a, b) in [(50, 100), (110, 150), (200, 203)] {
+ env[a..b].iter_mut().for_each(|v| *v = -20.0);
+ }
+ let r = activity(&env, hop, -40.0, 0.1, 0.2);
+ assert_eq!(r.len(), 1);
+ assert!((r[0].0 - 0.5).abs() < 1e-6 && (r[0].1 - 1.5).abs() < 1e-6, "{r:?}");
+ // without bridging both remain, the blip still goes
+ let r = activity(&env, hop, -40.0, 0.1, 0.0);
+ assert_eq!(r.len(), 2);
+ // a region running to the end is closed at the end
+ let mut env2 = vec![-80.0f32; 10];
+ env2[5..].iter_mut().for_each(|v| *v = 0.0);
+ assert_eq!(activity(&env2, 0.1, -40.0, 0.0, 0.0), vec![(0.5, 1.0)]);
+ }
+
+ #[test]
+ fn sensitivity_mapping() {
+ assert_eq!(sensitivity_threshold_db(5.0), -40.0);
+ assert_eq!(sensitivity_threshold_db(0.0), -20.0);
+ assert_eq!(sensitivity_threshold_db(10.0), -60.0);
+ assert_eq!(sensitivity_threshold_db(99.0), -60.0);
+ }
+
+ fn strictly_increasing(k: &[(f64, f64)]) -> bool {
+ k.windows(2).all(|w| w[1].0 > w[0].0)
+ }
+
+ #[test]
+ fn duck_keyframes_basic_and_merge() {
+ let k = duck_keyframes(&[(2.0, 4.0)], 0.0, 10.0, 0.0, 15.0, 0.5);
+ assert_eq!(k, vec![(1.5, 0.0), (2.0, -15.0), (4.0, -15.0), (4.5, 0.0)]);
+ // ramps overlap (4.5 > 4.8 − 0.5 = 4.3) → stay ducked
+ let k = duck_keyframes(&[(2.0, 4.0), (4.8, 6.0)], 0.0, 10.0, -3.0, 12.0, 0.5);
+ assert_eq!(k, vec![(1.5, -3.0), (2.0, -15.0), (6.0, -15.0), (6.5, -3.0)]);
+ // separate regions
+ let k = duck_keyframes(&[(5.0, 6.0), (1.0, 2.0)], 0.0, 10.0, 0.0, 10.0, 0.25);
+ assert_eq!(k.len(), 8);
+ assert!(strictly_increasing(&k));
+ assert!(duck_keyframes(&[], 0.0, 10.0, 0.0, 10.0, 0.5).is_empty());
+ }
+
+ #[test]
+ fn duck_keyframes_clamped_to_clip() {
+ // region starts before the clip: fully ducked at the start edge
+ let k = duck_keyframes(&[(-1.0, 2.0)], 0.0, 10.0, 0.0, 10.0, 0.5);
+ assert_eq!(k, vec![(0.0, -10.0), (2.0, -10.0), (2.5, 0.0)]);
+ // ramp partially before the clip: ramp value at the edge
+ let k = duck_keyframes(&[(0.25, 2.0)], 0.0, 10.0, 0.0, 10.0, 0.5);
+ assert_eq!(k[0], (0.0, -5.0));
+ assert_eq!(k[1], (0.25, -10.0));
+ // region runs past the end: ducked at the end edge
+ let k = duck_keyframes(&[(8.0, 12.0)], 0.0, 10.0, 0.0, 10.0, 0.5);
+ assert_eq!(k, vec![(7.5, 0.0), (8.0, -10.0), (10.0, -10.0)]);
+ // up-ramp cut by the end
+ let k = duck_keyframes(&[(8.0, 9.75)], 0.0, 10.0, 0.0, 10.0, 0.5);
+ assert_eq!(*k.last().unwrap(), (10.0, -5.0));
+ // outside the clip: nothing; zero fade still strictly increasing
+ assert!(duck_keyframes(&[(11.0, 12.0)], 0.0, 10.0, 0.0, 10.0, 0.5).is_empty());
+ let k = duck_keyframes(&[(2.0, 3.0)], 0.0, 10.0, 0.0, 10.0, 0.0);
+ assert!(strictly_increasing(&k) && k.len() == 4);
+ }
+}
diff --git a/crates/audio-dsp/src/effects/essential.rs b/crates/audio-dsp/src/effects/essential.rs
new file mode 100644
index 000000000..4c46902cc
--- /dev/null
+++ b/crates/audio-dsp/src/effects/essential.rs
@@ -0,0 +1,764 @@
+//! Essential Sound processors: DeEsser (split-band), DeReverb (spectral late-reverberation
+//! suppression), Enhance Speech (a DSP voice-enhancement chain) and Stereo Width (mid/side).
+//!
+//! All written from textbook descriptions:
+//! * de-esser: complementary split (band = 2nd-order high-pass, rest = x − band) with a relative
+//! band-vs-broadband detector driving the band gain;
+//! * de-reverb: the statistical late-reverberation model (exponentially decaying diffuse tail,
+//! Polack): the late-reverb PSD at frame t is predicted from the reverberant PSD T_d earlier,
+//! λ_r(t) = e^{−2Δ·T_d}·λ_x(t − T_d), Δ = 3·ln10 / RT60, and removed by spectral subtraction
+//! with over-subtraction and a gain floor (Lebart et al. 2001; Habets 2007);
+//! * enhance speech: high-pass, de-mud cut, presence and air boosts (RBJ biquads), then one gain
+//! computer combining a downward expander (noise between words) and a soft-knee compressor.
+
+use super::stft::{Spectral, StftChannel, fft_size};
+use crate::biquad::{Biquad, Coeffs, FilterType};
+use crate::{AudioEffect, ParamSpec, ParamValues, Smoothed, Unit, block_len, db_to_gain, flush, param_plumbing};
+
+/// One-pole smoothing coefficient for a time constant in ms.
+fn coef(ms: f64, sr: f64) -> f64 {
+ if ms <= 0.0 { 0.0 } else { (-1.0 / (ms * 0.001 * sr)).exp() }
+}
+
+#[inline]
+fn pow_db(p: f64) -> f64 {
+ 10.0 * (p + 1e-20).log10()
+}
+
+// ---------------------------------------------------------------------------------------------
+
+/// De-esser: a 2nd-order high-pass sidechain at `frequency` detects sibilance (the band level
+/// exceeds the broadband level by more than `threshold`); the band above `frequency` is then cut
+/// by a dynamic RBJ high shelf whose gain follows the gain reduction (attack ~1 ms, release
+/// ~60 ms, stereo-linked). At 0 dB reduction the shelf is an exact identity, so non-sibilant
+/// passages pass unchanged. (A subtractive split `x − HP(x)` is not used: the high-pass phase
+/// shift around the crossover makes `x − (1 − g)·HP(x)` boost there instead of cutting.)
+pub struct DeEsser {
+ pv: ParamValues,
+ sr: f64,
+ freq: Smoothed,
+ coeffs: Coeffs,
+ hp: Vec<Biquad>,
+ shelf: Vec<Biquad>,
+ shelf_coeffs: Coeffs,
+ shelf_gr: f64,
+ env_band: f64,
+ env_full: f64,
+ /// Smoothed gain reduction (dB, ≤ 0).
+ gr: f64,
+ det: f64,
+ att: f64,
+ rel: f64,
+ threshold: f64,
+ reduction: f64,
+ gr_meter: f32,
+}
+
+impl DeEsser {
+ pub const PARAMS: &'static [ParamSpec] = &[
+ ParamSpec::log("frequency", "Frequency", 2000.0, 12000.0, 6000.0, Unit::Hertz),
+ ParamSpec::new("threshold", "Threshold", -40.0, 0.0, -12.0, Unit::Decibels),
+ ParamSpec::new("reduction", "Max Reduction", 0.0, 24.0, 8.0, Unit::Decibels),
+ ];
+
+ pub fn new(sample_rate: f32, channels: usize) -> Self {
+ let sr = sample_rate as f64;
+ let mut s = DeEsser {
+ pv: ParamValues::new(Self::PARAMS),
+ sr,
+ freq: Smoothed::with_ms(6000.0, sample_rate, 20.0),
+ coeffs: Coeffs::IDENTITY,
+ hp: vec![Biquad::new(); channels.max(1)],
+ shelf: vec![Biquad::new(); channels.max(1)],
+ shelf_coeffs: Coeffs::IDENTITY,
+ shelf_gr: 0.0,
+ env_band: 0.0,
+ env_full: 0.0,
+ gr: 0.0,
+ det: coef(2.0, sr),
+ att: coef(1.0, sr),
+ rel: coef(60.0, sr),
+ threshold: -12.0,
+ reduction: 8.0,
+ gr_meter: 0.0,
+ };
+ s.apply_params(true);
+ s
+ }
+
+ fn design(&mut self) {
+ self.coeffs = Coeffs::design(FilterType::HighPass, self.sr, self.freq.value() as f64, std::f64::consts::FRAC_1_SQRT_2, 0.0);
+ self.design_shelf();
+ }
+
+ fn design_shelf(&mut self) {
+ self.shelf_coeffs = if self.gr == 0.0 {
+ Coeffs::IDENTITY
+ } else {
+ Coeffs::design(FilterType::HighShelf, self.sr, self.freq.value() as f64, std::f64::consts::FRAC_1_SQRT_2, self.gr)
+ };
+ self.shelf_gr = self.gr;
+ }
+
+ fn apply_params(&mut self, snap: bool) {
+ self.freq.set(self.pv.v("frequency"));
+ self.threshold = self.pv.v("threshold") as f64;
+ self.reduction = self.pv.v("reduction") as f64;
+ if snap {
+ self.freq.snap();
+ self.design();
+ }
+ }
+
+ /// Current band gain reduction in dB (≤ 0), for metering.
+ pub fn gain_reduction_db(&self) -> f32 {
+ self.gr_meter
+ }
+}
+
+impl AudioEffect for DeEsser {
+ param_plumbing!("deesser");
+ fn reset(&mut self) {
+ self.freq.snap();
+ self.design();
+ self.hp.iter_mut().for_each(Biquad::reset);
+ self.shelf.iter_mut().for_each(Biquad::reset);
+ self.env_band = 0.0;
+ self.env_full = 0.0;
+ self.gr = 0.0;
+ self.gr_meter = 0.0;
+ self.design_shelf();
+ }
+ fn process(&mut self, channels: &mut [&mut [f32]]) {
+ let n = block_len(channels);
+ let nch = channels.len().min(self.hp.len());
+ for i in 0..n {
+ if self.freq.is_smoothing() {
+ self.freq.tick();
+ self.design();
+ }
+ let (mut pb, mut pf) = (0.0f64, 0.0f64);
+ for ch in 0..nch {
+ let x = channels[ch][i] as f64;
+ let b = self.hp[ch].tick(&self.coeffs, x);
+ pb += b * b;
+ pf += x * x;
+ }
+ self.env_band = flush(self.det * self.env_band + (1.0 - self.det) * pb);
+ self.env_full = flush(self.det * self.env_full + (1.0 - self.det) * pf);
+ let bdb = pow_db(self.env_band);
+ let excess = bdb - pow_db(self.env_full) - self.threshold;
+ let target = if bdb > -70.0 && excess > 0.0 { -(excess * 2.0).min(self.reduction) } else { 0.0 };
+ let c = if target < self.gr { self.att } else { self.rel };
+ self.gr = flush(c * self.gr + (1.0 - c) * target);
+ if target == 0.0 && self.gr > -1e-4 {
+ self.gr = 0.0;
+ }
+ if (self.gr - self.shelf_gr).abs() > 0.05 || (self.gr == 0.0) != (self.shelf_gr == 0.0) {
+ self.design_shelf();
+ }
+ for ch in 0..nch {
+ let x = channels[ch][i] as f64;
+ channels[ch][i] = self.shelf[ch].tick(&self.shelf_coeffs, x) as f32;
+ }
+ }
+ self.gr_meter = self.gr as f32;
+ }
+}
+
+// ---------------------------------------------------------------------------------------------
+
+/// Late-reverberation delay T_d (s): reflections later than this count as reverb.
+const DEREVERB_TD: f64 = 0.05;
+/// Time constant (s) of the PSD smoothing.
+const DEREVERB_PSD_TAU: f64 = 0.02;
+
+#[derive(Clone, Debug)]
+struct ReverbState {
+ psd: Vec<f32>,
+ /// Ring of past smoothed PSDs, `delay_frames` deep.
+ hist: Vec<f32>,
+ pos: usize,
+ gains: Vec<f32>,
+ frames: usize,
+}
+
+impl ReverbState {
+ fn new(bins: usize, delay: usize) -> Self {
+ ReverbState { psd: vec![0.0; bins], hist: vec![0.0; bins * delay], pos: 0, gains: vec![1.0; bins], frames: 0 }
+ }
+ fn reset(&mut self) {
+ self.psd.iter_mut().for_each(|v| *v = 0.0);
+ self.hist.iter_mut().for_each(|v| *v = 0.0);
+ self.gains.iter_mut().for_each(|v| *v = 1.0);
+ self.pos = 0;
+ self.frames = 0;
+ }
+}
+
+/// Spectral de-reverberation: suppresses the late reverberant tail predicted by the exponential
+/// decay model for the assumed `rt60`. `amount` sets the over-subtraction and the gain floor
+/// (0 % = identity apart from the STFT delay, 100 % ≈ −18 dB floor).
+pub struct DeReverb {
+ pv: ParamValues,
+ sr: f32,
+ n: usize,
+ hop: usize,
+ delay: usize,
+ spec: Spectral,
+ stft: Vec<StftChannel>,
+ state: Vec<ReverbState>,
+ smoothed_gains: Vec<f32>,
+ /// e^{−2Δ·T_d} (power decay over the delay).
+ decay: f32,
+ beta: f32,
+ floor: f32,
+ alpha: f32,
+}
+
+impl DeReverb {
+ pub const PARAMS: &'static [ParamSpec] =
+ &[ParamSpec::new("amount", "Amount", 0.0, 100.0, 50.0, Unit::Percent), ParamSpec::log("rt60", "Decay (RT60)", 0.1, 5.0, 0.8, Unit::Seconds)];
+
+ pub fn new(sample_rate: f32, channels: usize) -> Self {
+ let n = fft_size(sample_rate);
+ let hop = n / 4;
+ let bins = n / 2 + 1;
+ let delay = ((DEREVERB_TD * sample_rate as f64 / hop as f64).round() as usize).max(1);
+ let ch = channels.max(1);
+ let mut s = DeReverb {
+ pv: ParamValues::new(Self::PARAMS),
+ sr: sample_rate,
+ n,
+ hop,
+ delay,
+ spec: Spectral::new(n, true),
+ stft: vec![StftChannel::new(n); ch],
+ state: vec![ReverbState::new(bins, delay); ch],
+ smoothed_gains: vec![1.0; bins],
+ decay: 1.0,
+ beta: 1.0,
+ floor: 1.0,
+ alpha: (-(hop as f64) / (sample_rate as f64 * DEREVERB_PSD_TAU)).exp() as f32,
+ };
+ s.apply_params(true);
+ s
+ }
+
+ fn apply_params(&mut self, _snap: bool) {
+ let amount = self.pv.v("amount") / 100.0;
+ let rt60 = self.pv.v("rt60") as f64;
+ let delta = 3.0 * std::f64::consts::LN_10 / rt60;
+ let td = self.delay as f64 * self.hop as f64 / self.sr as f64;
+ self.decay = (-2.0 * delta * td).exp() as f32;
+ self.beta = 1.0 + amount;
+ self.floor = db_to_gain(-18.0 * amount);
+ }
+}
+
+impl AudioEffect for DeReverb {
+ param_plumbing!("dereverb");
+ fn latency(&self) -> usize {
+ self.n
+ }
+ fn reset(&mut self) {
+ self.stft.iter_mut().for_each(StftChannel::reset);
+ self.state.iter_mut().for_each(ReverbState::reset);
+ }
+ fn process(&mut self, channels: &mut [&mut [f32]]) {
+ let len = block_len(channels);
+ let nch = channels.len().min(self.stft.len());
+ let (n, hop, delay) = (self.n, self.hop, self.delay);
+ let (decay, beta, floor, alpha) = (self.decay, self.beta, self.floor, self.alpha);
+ let scale = 1.0 / (n as f32 * 2.0);
+ let bins = n / 2 + 1;
+ for ch in 0..nch {
+ let st = &mut self.state[ch];
+ let spec = &mut self.spec;
+ let sg = &mut self.smoothed_gains;
+ let mut frame = |input: &[f32], out: &mut [f32]| {
+ spec.analyse(input);
+ let warm = st.frames >= delay;
+ let base = st.pos * bins;
+ for k in 0..bins {
+ let p = spec.re[k] * spec.re[k] + spec.im[k] * spec.im[k];
+ let psd = alpha * st.psd[k] + (1.0 - alpha) * p;
+ st.psd[k] = if psd < 1e-30 { 0.0 } else { psd };
+ // Late reverb predicted from the PSD `delay` frames ago (the ring slot we are
+ // about to overwrite holds exactly that frame).
+ let late = if warm { decay * st.hist[base + k] } else { 0.0 };
+ st.hist[base + k] = st.psd[k];
+ let target = if st.psd[k] > 0.0 { (1.0 - beta * late / st.psd[k]).max(floor) } else { 1.0 };
+ let g = &mut st.gains[k];
+ // fast recovery on onsets, slower suppression (less musical noise)
+ let c = if target > *g { 0.8 } else { 0.5 };
+ *g += (target - *g) * c;
+ }
+ st.pos = (st.pos + 1) % delay;
+ st.frames = st.frames.saturating_add(1);
+ for k in 0..bins {
+ let a = st.gains[k.saturating_sub(1)];
+ let c = st.gains[(k + 1).min(bins - 1)];
+ sg[k] = 0.25 * a + 0.5 * st.gains[k] + 0.25 * c;
+ }
+ for k in 0..bins {
+ spec.re[k] *= sg[k];
+ spec.im[k] *= sg[k];
+ }
+ spec.synthesise_add(out, scale);
+ };
+ for v in channels[ch][..len].iter_mut() {
+ *v = self.stft[ch].tick(*v, hop, &mut frame);
+ }
+ }
+ }
+}
+
+// ---------------------------------------------------------------------------------------------
+
+const ENH_STAGES: usize = 4;
+/// Expander: below this level (dBFS) the signal is pushed down (noise between words).
+const ENH_EXP_THRESHOLD: f64 = -50.0;
+const ENH_EXP_RATIO: f64 = 3.0;
+const ENH_EXP_RANGE: f64 = 18.0;
+/// Compressor above this level (dBFS).
+const ENH_COMP_THRESHOLD: f64 = -24.0;
+const ENH_COMP_RATIO: f64 = 3.0;
+const ENH_COMP_KNEE: f64 = 6.0;
+/// Make-up gain: puts conversational speech (≈ −20 dBFS RMS) back near its input loudness.
+const ENH_MAKEUP: f64 = 3.0;
+
+/// Enhance Speech: a DSP voice-enhancement chain (no machine learning) — 80 Hz high-pass,
+/// de-mud cut, presence and air boosts, then a combined downward expander + soft-knee
+/// compressor with make-up gain. `tone` picks the cut/boost frequencies for lower or higher
+/// voices; `mix` blends with the dry signal.
+pub struct SpeechEnhance {
+ pv: ParamValues,
+ sr: f64,
+ coeffs: [Coeffs; ENH_STAGES],
+ filters: Vec<[Biquad; ENH_STAGES]>,
+ mix: Smoothed,
+ /// Detector mean square.
+ ms: f64,
+ /// Smoothed expander gain (dB, ≤ 0): opens fast, closes slowly.
+ env_exp: f64,
+ /// Smoothed compressor gain (dB, ≤ 0): fast attack, slow release.
+ env_comp: f64,
+ det: f64,
+ fast: f64,
+ exp_close: f64,
+ comp_rel: f64,
+}
+
+impl SpeechEnhance {
+ pub const PARAMS: &'static [ParamSpec] =
+ &[ParamSpec::new("mix", "Mix", 0.0, 100.0, 100.0, Unit::Percent), ParamSpec::choice("tone", "Tone", &["Low Tone", "High Tone"], 0)];
+
+ pub fn new(sample_rate: f32, channels: usize) -> Self {
+ let sr = sample_rate as f64;
+ let mut s = SpeechEnhance {
+ pv: ParamValues::new(Self::PARAMS),
+ sr,
+ coeffs: [Coeffs::IDENTITY; ENH_STAGES],
+ filters: vec![[Biquad::new(); ENH_STAGES]; channels.max(1)],
+ mix: Smoothed::with_ms(1.0, sample_rate, 20.0),
+ ms: 0.0,
+ env_exp: 0.0,
+ env_comp: 0.0,
+ det: coef(5.0, sr),
+ fast: coef(3.0, sr),
+ exp_close: coef(30.0, sr),
+ comp_rel: coef(120.0, sr),
+ };
+ s.apply_params(true);
+ s
+ }
+
+ fn apply_params(&mut self, snap: bool) {
+ let high = self.pv.idx("tone") == 1;
+ let (mud, presence) = if high { (350.0, 4000.0) } else { (250.0, 2500.0) };
+ let sr = self.sr;
+ self.coeffs = [
+ Coeffs::design(FilterType::HighPass, sr, 80.0, std::f64::consts::FRAC_1_SQRT_2, 0.0),
+ Coeffs::design(FilterType::Peaking, sr, mud, 1.0, -3.0),
+ Coeffs::design(FilterType::Peaking, sr, presence, 1.0, 4.0),
+ Coeffs::design(FilterType::HighShelf, sr, 10000.0, std::f64::consts::FRAC_1_SQRT_2, 2.0),
+ ];
+ self.mix.set(self.pv.v("mix") / 100.0);
+ if snap {
+ self.mix.snap();
+ }
+ }
+
+ /// Static downward-expander gain (dB) for a detector level (dBFS).
+ fn expander_db(level: f64) -> f64 {
+ if level < ENH_EXP_THRESHOLD { ((level - ENH_EXP_THRESHOLD) * (ENH_EXP_RATIO - 1.0)).max(-ENH_EXP_RANGE) } else { 0.0 }
+ }
+
+ /// Static soft-knee compressor gain (dB) for a detector level (dBFS).
+ fn compressor_db(level: f64) -> f64 {
+ let d = level - ENH_COMP_THRESHOLD;
+ if 2.0 * d.abs() <= ENH_COMP_KNEE {
+ (1.0 / ENH_COMP_RATIO - 1.0) * (d + ENH_COMP_KNEE / 2.0).powi(2) / (2.0 * ENH_COMP_KNEE)
+ } else if d > 0.0 {
+ d / ENH_COMP_RATIO - d
+ } else {
+ 0.0
+ }
+ }
+}
+
+impl AudioEffect for SpeechEnhance {
+ param_plumbing!("speech_enhance");
+ fn reset(&mut self) {
+ self.filters.iter_mut().for_each(|f| f.iter_mut().for_each(Biquad::reset));
+ self.mix.snap();
+ self.ms = 0.0;
+ self.env_exp = 0.0;
+ self.env_comp = 0.0;
+ }
+ fn process(&mut self, channels: &mut [&mut [f32]]) {
+ let n = block_len(channels);
+ let nch = channels.len().min(self.filters.len()).min(8);
+ let mut wet = [0.0f64; 8];
+ for i in 0..n {
+ let mut sq = 0.0f64;
+ for ch in 0..nch {
+ let mut x = channels[ch][i] as f64;
+ for (st, c) in self.filters[ch].iter_mut().zip(self.coeffs.iter()) {
+ x = st.tick(c, x);
+ }
+ wet[ch] = x;
+ sq = sq.max(x * x);
+ }
+ self.ms = flush(self.det * self.ms + (1.0 - self.det) * sq);
+ let level = pow_db(self.ms);
+ let te = Self::expander_db(level);
+ let c = if te > self.env_exp { self.fast } else { self.exp_close };
+ self.env_exp = c * self.env_exp + (1.0 - c) * te;
+ let tc = Self::compressor_db(level);
+ let c = if tc < self.env_comp { self.fast } else { self.comp_rel };
+ self.env_comp = c * self.env_comp + (1.0 - c) * tc;
+ if self.env_exp.abs() < 1e-9 {
+ self.env_exp = 0.0;
+ }
+ if self.env_comp.abs() < 1e-9 {
+ self.env_comp = 0.0;
+ }
+ let g = 10f64.powf((self.env_exp + self.env_comp + ENH_MAKEUP) / 20.0);
+ let m = self.mix.tick() as f64;
+ for (ch, w) in wet.iter().enumerate().take(nch) {
+ let dry = channels[ch][i] as f64;
+ channels[ch][i] = (dry + m * (w * g - dry)) as f32;
+ }
+ }
+ }
+}
+
+// ---------------------------------------------------------------------------------------------
+
+/// Stereo width by mid/side scaling: 0 % = mono, 100 % = unchanged, 200 % = side doubled.
+/// Only the first two channels are processed; mono input passes through.
+pub struct StereoWidth {
+ pv: ParamValues,
+ width: Smoothed,
+}
+
+impl StereoWidth {
+ pub const PARAMS: &'static [ParamSpec] = &[ParamSpec::new("width", "Width", 0.0, 200.0, 100.0, Unit::Percent)];
+
+ pub fn new(sample_rate: f32, _channels: usize) -> Self {
+ let mut s = StereoWidth { pv: ParamValues::new(Self::PARAMS), width: Smoothed::with_ms(1.0, sample_rate, 20.0) };
+ s.apply_params(true);
+ s
+ }
+ fn apply_params(&mut self, snap: bool) {
+ self.width.set(self.pv.v("width") / 100.0);
+ if snap {
+ self.width.snap();
+ }
+ }
+}
+
+impl AudioEffect for StereoWidth {
+ param_plumbing!("stereo_width");
+ fn reset(&mut self) {
+ self.width.snap();
+ }
+ fn process(&mut self, channels: &mut [&mut [f32]]) {
+ let n = block_len(channels);
+ if channels.len() < 2 {
+ // keep the smoother in step with time
+ for _ in 0..n {
+ self.width.tick();
+ }
+ return;
+ }
+ let (l, rest) = channels.split_at_mut(1);
+ let (l, r) = (&mut l[0], &mut rest[0]);
+ for i in 0..n {
+ let w = self.width.tick();
+ let m = 0.5 * (l[i] + r[i]);
+ let s = 0.5 * (l[i] - r[i]) * w;
+ l[i] = m + s;
+ r[i] = m - s;
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::testutil::*;
+
+ const SR: f32 = 48000.0;
+
+ fn energy(x: &[f32]) -> f64 {
+ x.iter().map(|&v| (v as f64) * (v as f64)).sum::<f64>()
+ }
+
+ /// Band-limited energy via a 4th-order band-pass (two cascaded RBJ band-passes at the
+ /// geometric centre) — good enough for relative before/after comparisons.
+ fn band_energy(x: &[f32], lo: f64, hi: f64) -> f64 {
+ let fc = (lo * hi).sqrt();
+ let q = fc / (hi - lo);
+ let c = Coeffs::design(FilterType::BandPass, SR as f64, fc, q, 0.0);
+ let (mut a, mut b) = (Biquad::new(), Biquad::new());
+ x.iter().map(|&v| b.tick(&c, a.tick(&c, v as f64))).map(|v| v * v).sum::<f64>()
+ }
+
+ fn harmonic_voice(n: usize, f0: f64, amp: f64) -> Vec<f32> {
+ let mut v = vec![0.0f32; n];
+ let mut k = 1;
+ while f0 * k as f64 <= 1500.0 {
+ let s = sine(f0 * k as f64, amp / k as f64, SR as f64, n, k as f64 * 0.7);
+ for (o, x) in v.iter_mut().zip(&s) {
+ *o += x;
+ }
+ k += 1;
+ }
+ v
+ }
+
+ fn bandpassed_noise(seed: u64, n: usize, lo: f64, hi: f64, amp: f32) -> Vec<f32> {
+ let mut r = Rng::new(seed);
+ let fc = (lo * hi).sqrt();
+ let c = Coeffs::design(FilterType::BandPass, SR as f64, fc, fc / (hi - lo), 0.0);
+ let (mut a, mut b) = (Biquad::new(), Biquad::new());
+ (0..n).map(|_| (b.tick(&c, a.tick(&c, (r.uniform() * amp) as f64)) * 2.0) as f32).collect()
+ }
+
+ #[test]
+ fn deesser_zero_reduction_is_identity() {
+ let mut d = DeEsser::new(SR, 1);
+ d.set_param("reduction", 0.0);
+ d.reset();
+ let mut r = Rng::new(3);
+ let x: Vec<f32> = (0..20000).map(|_| r.uniform() * 0.5).collect();
+ let mut y = x.clone();
+ d.process(&mut [&mut y]);
+ for (a, b) in x.iter().zip(&y) {
+ assert!((a - b).abs() < 1e-6);
+ }
+ }
+
+ #[test]
+ fn deesser_reduces_sibilance_keeps_voice() {
+ let n = SR as usize * 4;
+ let voice = harmonic_voice(n, 150.0, 0.15);
+ let sib = bandpassed_noise(11, n, 5000.0, 10000.0, 0.6);
+ // sibilant bursts: 150 ms every 500 ms (from 250 ms)
+ let burst = |i: usize| {
+ let p = i % (SR as usize / 2);
+ p >= SR as usize / 4 && p < SR as usize / 4 + (0.15 * SR) as usize
+ };
+ let x: Vec<f32> = (0..n).map(|i| voice[i] + if burst(i) { sib[i] } else { 0.0 }).collect();
+ for (reduction, need) in [(8.0f32, 5.0f64), (16.0, 6.0)] {
+ let mut d = DeEsser::new(SR, 1);
+ d.set_param("reduction", reduction);
+ d.reset();
+ let mut y = x.clone();
+ d.process(&mut [&mut y]);
+ let pick = |v: &[f32], on: bool| -> Vec<f32> { v.iter().enumerate().skip(SR as usize).filter(|(i, _)| burst(*i) == on).map(|(_, s)| *s).collect() };
+ let (xb, yb) = (pick(&x, true), pick(&y, true));
+ let sib_drop = 10.0 * (band_energy(&yb, 5000.0, 10000.0) / band_energy(&xb, 5000.0, 10000.0)).log10();
+ let low_change = 10.0 * (band_energy(&y, 150.0, 1500.0) / band_energy(&x, 150.0, 1500.0)).log10();
+ let (xq, yq) = (pick(&x, false), pick(&y, false));
+ let quiet_change = 10.0 * (energy(&yq) / energy(&xq)).log10();
+ println!("deesser reduction {reduction} dB: sibilance {sib_drop:.2} dB, voice band {low_change:.3} dB, non-sibilant passages {quiet_change:.3} dB");
+ assert!(sib_drop < -need, "sibilance only {sib_drop} dB");
+ assert!(low_change.abs() < 1.0, "voice band changed {low_change} dB");
+ assert!(quiet_change.abs() < 0.5, "non-sibilant passages changed {quiet_change} dB");
+ }
+ }
+
+ #[test]
+ fn dereverb_suppresses_tail() {
+ let sr = SR as f64;
+ let n = SR as usize * 6;
+ let period = (0.5 * sr) as usize;
+ let on = (0.1 * sr) as usize;
+ let dry_src = harmonic_voice(n, 180.0, 0.25);
+ let dry: Vec<f32> = (0..n).map(|i| if i % period < on { dry_src[i] } else { 0.0 }).collect();
+ // Statistical late reverb (Polack): white noise shaped by the energy envelope of the dry
+ // signal convolved with an exponential decay — a one-pole filter on the energy.
+ let rt60 = 0.8;
+ let a = (-6.0 * std::f64::consts::LN_10 / (rt60 * sr)).exp(); // power decay per sample
+ let mut e = 0.0f64;
+ let mut rng = Rng::new(77);
+ let wet_gain = 1.0 - a; // tail energy ≈ direct energy (DRR ≈ 0 dB)
+ let x: Vec<f32> = dry
+ .iter()
+ .map(|&d| {
+ e = a * e + wet_gain * (d as f64) * (d as f64);
+ d + (rng.uniform() as f64 * 3f64.sqrt() * e.sqrt()) as f32
+ })
+ .collect();
+ let mut fx = DeReverb::new(SR, 1);
+ fx.set_param("amount", 100.0);
+ fx.reset();
+ let lat = fx.latency();
+ let mut y = x.clone();
+ fx.process(&mut [&mut y]);
+ let y = &y[lat..];
+ let start = SR as usize; // after warm-up
+ let split = |v: &[f32]| {
+ let (mut b, mut g) = (0.0, 0.0);
+ for (i, s) in v.iter().enumerate().take(n - lat).skip(start) {
+ let p = (*s as f64) * (*s as f64);
+ if i % period < on { b += p } else { g += p }
+ }
+ (b, g)
+ };
+ let (xb, xg) = split(&x);
+ let (yb, yg) = split(y);
+ let before = 10.0 * (xg / xb).log10();
+ let after = 10.0 * (yg / yb).log10();
+ let burst_loss = 10.0 * (yb / xb).log10();
+ println!("dereverb: tail/burst {before:.2} dB → {after:.2} dB (improvement {:.2} dB), burst energy {burst_loss:.2} dB", before - after);
+ assert!(before - after >= 4.0, "tail improvement only {} dB", before - after);
+ assert!(burst_loss > -3.0, "burst energy lost {burst_loss} dB");
+ }
+
+ #[test]
+ fn dereverb_zero_amount_is_delayed_identity() {
+ let mut d = DeReverb::new(SR, 1);
+ d.set_param("amount", 0.0);
+ let lat = d.latency();
+ let mut rng = Rng::new(9);
+ let x: Vec<f32> = (0..20000).map(|_| rng.uniform() * 0.5).collect();
+ let mut y = x.clone();
+ d.process(&mut [&mut y]);
+ for i in lat..x.len() {
+ assert!((y[i] - x[i - lat]).abs() < 1e-4);
+ }
+ }
+
+ #[test]
+ fn speech_enhance_presence_noise_and_level() {
+ let sr = SR as usize;
+ let n = sr * 4;
+ let voice = harmonic_voice(n, 140.0, 0.08);
+ let fric = bandpassed_noise(5, n, 1500.0, 6000.0, 0.05);
+ let mut rng = Rng::new(42);
+ // syllables: 200 ms on, 200 ms off; −60 dBFS-ish background noise throughout
+ let syl = |i: usize| (i / (sr / 5)).is_multiple_of(2);
+ let x: Vec<f32> = (0..n).map(|i| rng.uniform() * 0.0017 + if syl(i) { voice[i] + fric[i] } else { 0.0 }).collect();
+ let mut fx = SpeechEnhance::new(SR, 1);
+ let mut y = x.clone();
+ fx.process(&mut [&mut y]);
+ let pick = |v: &[f32], on: bool| -> Vec<f32> {
+ v.iter()
+ .enumerate()
+ .skip(sr)
+ .filter(|(i, _)| {
+ let p = i % (2 * sr / 5);
+ // skip 50 ms after each edge
+ syl(*i) == on && p % (sr / 5) > sr / 20
+ })
+ .map(|(_, s)| *s)
+ .collect()
+ };
+ let (xs, ys) = (pick(&x, true), pick(&y, true));
+ let tilt_in = 10.0 * (band_energy(&xs, 2000.0, 5000.0) / band_energy(&xs, 200.0, 400.0)).log10();
+ let tilt_out = 10.0 * (band_energy(&ys, 2000.0, 5000.0) / band_energy(&ys, 200.0, 400.0)).log10();
+ let noise = 10.0 * (energy(&pick(&y, false)) / energy(&pick(&x, false))).log10();
+ let level = 10.0 * (energy(&y[sr..]) / energy(&x[sr..])).log10();
+ println!(
+ "enhance speech: presence/mud tilt {tilt_in:.2} → {tilt_out:.2} dB (+{:.2}), noise between syllables {noise:.2} dB, level {level:.2} dB",
+ tilt_out - tilt_in
+ );
+ assert!(tilt_out - tilt_in > 3.0);
+ assert!(noise <= -3.0, "noise floor only {noise} dB");
+ assert!(level.abs() <= 3.0, "level changed {level} dB");
+ // mix 0 is identity
+ let mut fx = SpeechEnhance::new(SR, 1);
+ fx.set_param("mix", 0.0);
+ fx.reset();
+ let mut z = x.clone();
+ fx.process(&mut [&mut z]);
+ assert!(z.iter().zip(&x).all(|(a, b)| (a - b).abs() < 1e-6));
+ }
+
+ #[test]
+ fn stereo_width_laws() {
+ let mut rng = Rng::new(1);
+ let l0: Vec<f32> = (0..4000).map(|_| rng.uniform() * 0.5).collect();
+ let r0: Vec<f32> = (0..4000).map(|_| rng.uniform() * 0.5).collect();
+ let run = |w: f32| {
+ let mut fx = StereoWidth::new(SR, 2);
+ fx.set_param("width", w);
+ fx.reset();
+ let (mut l, mut r) = (l0.clone(), r0.clone());
+ fx.process(&mut [&mut l, &mut r]);
+ (l, r)
+ };
+ let (l, r) = run(0.0);
+ assert!(l.iter().zip(&r).all(|(a, b)| (a - b).abs() < 1e-7));
+ let (l, r) = run(100.0);
+ assert!(l.iter().zip(&l0).chain(r.iter().zip(&r0)).all(|(a, b)| (a - b).abs() < 1e-6));
+ let (l, r) = run(200.0);
+ for i in 0..l.len() {
+ let (m, s) = (0.5 * (l0[i] + r0[i]), 0.5 * (l0[i] - r0[i]));
+ assert!((0.5 * (l[i] + r[i]) - m).abs() < 1e-6);
+ assert!((0.5 * (l[i] - r[i]) - 2.0 * s).abs() < 1e-6);
+ }
+ // mono passes through
+ let mut fx = StereoWidth::new(SR, 2);
+ fx.set_param("width", 0.0);
+ let mut m = l0.clone();
+ fx.process(&mut [&mut m]);
+ assert_eq!(m, l0);
+ }
+
+ /// The Essential Sound "Dialogue" chain on 60 s of stereo 48 kHz.
+ /// `cargo test --release -p filmcraft-audio-dsp dialogue_chain_realtime -- --ignored --nocapture`
+ #[test]
+ #[ignore]
+ fn dialogue_chain_realtime() {
+ let sr = SR as usize;
+ let n = sr * 60;
+ let mut rng = Rng::new(3);
+ let voice = harmonic_voice(n, 140.0, 0.1);
+ let mut l: Vec<f32> = (0..n).map(|i| voice[i] + rng.uniform() * 0.01).collect();
+ let mut r: Vec<f32> = l.iter().map(|v| v * 0.9 + rng.uniform() * 0.01).collect();
+ let mut chain: Vec<Box<dyn AudioEffect>> =
+ ["denoise", "parametric_eq", "dehum", "deesser", "dereverb", "compressor", "simple_eq", "speech_enhance", "reverb"]
+ .iter()
+ .map(|id| crate::create_effect(id, SR, 2).unwrap())
+ .collect();
+ chain[1].set_param("b1.on", 1.0);
+ chain[1].set_param("b2.on", 1.0);
+ chain[1].set_param("b2.type", 4.0);
+ chain[1].set_param("b2.freq", 80.0);
+ let t0 = std::time::Instant::now();
+ for (lb, rb) in l.chunks_mut(1024).zip(r.chunks_mut(1024)) {
+ for fx in chain.iter_mut() {
+ fx.process(&mut [&mut *lb, &mut *rb]);
+ }
+ }
+ let secs = t0.elapsed().as_secs_f64();
+ println!("dialogue chain: 60 s stereo in {secs:.3} s = {:.1}× realtime (one core)", 60.0 / secs);
+ assert!(l.iter().chain(&r).all(|v| v.is_finite()));
+ }
+}
diff --git a/crates/audio-dsp/src/effects/mod.rs b/crates/audio-dsp/src/effects/mod.rs
index 1be4f57b1..fd11ffc99 100644
--- a/crates/audio-dsp/src/effects/mod.rs
+++ b/crates/audio-dsp/src/effects/mod.rs
@@ -3,6 +3,7 @@
pub mod channel;
pub mod dynamics;
pub mod eq;
+pub mod essential;
pub mod pitch;
pub mod restoration;
mod stft;
@@ -11,6 +12,7 @@ pub mod time;
pub use channel::{Amplify, Balance, ChannelVolume, Invert, Route, Routing};
pub use dynamics::{Compressor, Gate, Limiter};
pub use eq::{ParametricEq, SimpleEq};
+pub use essential::{DeEsser, DeReverb, SpeechEnhance, StereoWidth};
pub use pitch::PitchShifter;
pub use restoration::{DeHum, DeNoise};
pub use time::{Delay, Reverb};
@@ -92,6 +94,10 @@ static REGISTRY: &[EffectInfo] = &[
entry!("dehum", "DeHum", Restoration, DeHum),
entry!("denoise", "DeNoise", Restoration, DeNoise),
entry!("pitch_shifter", "Pitch Shifter", Pitch, PitchShifter),
+ entry!("deesser", "DeEsser", Restoration, DeEsser),
+ entry!("dereverb", "DeReverb", Restoration, DeReverb),
+ entry!("speech_enhance", "Enhance Speech", Filter, SpeechEnhance),
+ entry!("stereo_width", "Stereo Width", Channel, StereoWidth),
];
/// All registered effects.
diff --git a/crates/audio-dsp/src/lib.rs b/crates/audio-dsp/src/lib.rs
index 15edf5b04..9908cf6b1 100644
--- a/crates/audio-dsp/src/lib.rs
+++ b/crates/audio-dsp/src/lib.rs
@@ -15,6 +15,7 @@
//! portable to wasm).
pub mod biquad;
+pub mod ducking;
pub mod effects;
pub mod fft;
pub mod loudness;