Skip to main content

qualia_audio/fx/reverb/
fdn.rs

1//! Feedback Delay Network reverb — 4 lines, 4×4 Hadamard feedback matrix.
2//!
3//! Hadamard mixing delegated to [`etalon_signal::reverb::fdn4_hadamard_mix`].
4
5use crate::types::AudioError;
6
7/// Base delay-line lengths (samples @ 44.1 kHz), mutually prime to avoid
8/// coincident echoes. Scaled to the working sample rate at construction.
9const BASE_DELAYS: [usize; 4] = [1687, 1801, 1949, 2053];
10
11/// 4×4 feedback delay network reverb with Hadamard mixing.
12#[derive(Debug, Clone)]
13pub struct FdnReverb {
14    lines: [Vec<f32>; 4],
15    idx: [usize; 4],
16    lp: [f32; 4],
17    decay: f32,
18    damping: f32,
19    wet: f32,
20    dry: f32,
21}
22
23impl FdnReverb {
24    /// Construct for `sample_rate`. `decay` in `[0, 1)` (tail length), `damping`
25    /// in `[0, 1)`, plus wet/dry linear mix. Allocates all four delay lines once.
26    pub fn new(
27        sample_rate: u32,
28        decay: f32,
29        damping: f32,
30        wet: f32,
31        dry: f32,
32    ) -> Result<Self, AudioError> {
33        if sample_rate == 0
34            || !decay.is_finite()
35            || !damping.is_finite()
36            || !wet.is_finite()
37            || !dry.is_finite()
38        {
39            return Err(AudioError::InvalidParameter);
40        }
41        let scale = sample_rate as f32 / 44_100.0;
42        let d = |t: usize| ((t as f32 * scale) as usize).max(1);
43        let lines = [
44            vec![0.0; d(BASE_DELAYS[0])],
45            vec![0.0; d(BASE_DELAYS[1])],
46            vec![0.0; d(BASE_DELAYS[2])],
47            vec![0.0; d(BASE_DELAYS[3])],
48        ];
49        Ok(Self {
50            lines,
51            idx: [0; 4],
52            lp: [0.0; 4],
53            decay: decay.clamp(0.0, 0.999),
54            damping: damping.clamp(0.0, 0.999),
55            wet,
56            dry,
57        })
58    }
59
60    /// Live-update decay (tail length). Clamped to `[0, 1)`.
61    #[inline]
62    pub fn set_decay(&mut self, decay: f32) {
63        if decay.is_finite() {
64            self.decay = decay.clamp(0.0, 0.999);
65        }
66    }
67
68    /// Live-update damping. Clamped to `[0, 1)`.
69    #[inline]
70    pub fn set_damping(&mut self, damping: f32) {
71        if damping.is_finite() {
72            self.damping = damping.clamp(0.0, 0.999);
73        }
74    }
75
76    /// Set wet/dry linear mix gains.
77    pub fn set_mix(&mut self, wet: f32, dry: f32) {
78        if wet.is_finite() {
79            self.wet = wet;
80        }
81        if dry.is_finite() {
82            self.dry = dry;
83        }
84    }
85
86    /// Clear all delay lines and lowpass state. No allocation.
87    pub fn reset(&mut self) {
88        for line in self.lines.iter_mut() {
89            for s in line.iter_mut() {
90                *s = 0.0;
91            }
92        }
93        self.idx = [0; 4];
94        self.lp = [0.0; 4];
95    }
96
97    /// Process one sample. **Zero-alloc, no locks.**
98    #[inline]
99    pub fn process_sample(&mut self, input: f32) -> f32 {
100        let d0 = self.lines[0][self.idx[0]];
101        let d1 = self.lines[1][self.idx[1]];
102        let d2 = self.lines[2][self.idx[2]];
103        let d3 = self.lines[3][self.idx[3]];
104
105        let damp = self.damping;
106        let one = 1.0 - damp;
107        self.lp[0] = d0 * one + self.lp[0] * damp;
108        self.lp[1] = d1 * one + self.lp[1] * damp;
109        self.lp[2] = d2 * one + self.lp[2] * damp;
110        self.lp[3] = d3 * one + self.lp[3] * damp;
111
112        let [m0, m1, m2, m3] = etalon_signal::reverb::fdn4_hadamard_mix(self.lp);
113
114        let g = self.decay;
115        self.lines[0][self.idx[0]] = input + g * m0;
116        self.lines[1][self.idx[1]] = input + g * m1;
117        self.lines[2][self.idx[2]] = input + g * m2;
118        self.lines[3][self.idx[3]] = input + g * m3;
119
120        for i in 0..4 {
121            self.idx[i] += 1;
122            if self.idx[i] >= self.lines[i].len() {
123                self.idx[i] = 0;
124            }
125        }
126
127        let wet_sig = 0.25 * (d0 + d1 + d2 + d3);
128        wet_sig * self.wet + input * self.dry
129    }
130
131    /// Block process. **Zero-alloc.** Errors if `output` is shorter than `input`.
132    pub fn process(&mut self, input: &[f32], output: &mut [f32]) -> Result<(), AudioError> {
133        if output.len() < input.len() {
134            return Err(AudioError::OutputBufferTooSmall);
135        }
136        for (o, &x) in output.iter_mut().zip(input.iter()) {
137            *o = self.process_sample(x);
138        }
139        Ok(())
140    }
141}
142
143#[cfg(test)]
144mod tests {
145    use super::*;
146
147    #[test]
148    fn impulse_produces_bounded_decaying_tail() {
149        let mut r = FdnReverb::new(44_100, 0.85, 0.2, 1.0, 0.0).unwrap();
150        let n = 44_100;
151        let mut input = vec![0.0f32; n];
152        input[0] = 1.0;
153        let mut out = vec![0.0f32; n];
154        r.process(&input, &mut out).unwrap();
155
156        assert!(out.iter().all(|x| x.is_finite()), "FDN produced NaN/Inf");
157        assert!(out.iter().all(|x| x.abs() < 4.0), "FDN tail not bounded");
158
159        let win = 4_410;
160        let early: f32 = out[win..2 * win].iter().map(|x| x * x).sum();
161        let late: f32 = out[9 * win..10 * win].iter().map(|x| x * x).sum();
162        assert!(early > 0.0, "expected non-zero tail energy");
163        assert!(
164            late < early,
165            "late energy {} must be < early {}",
166            late,
167            early
168        );
169    }
170
171    #[test]
172    fn higher_decay_gives_longer_tail() {
173        let n = 44_100;
174        let mut input = vec![0.0f32; n];
175        input[0] = 1.0;
176        let mut short = FdnReverb::new(44_100, 0.5, 0.2, 1.0, 0.0).unwrap();
177        let mut long = FdnReverb::new(44_100, 0.9, 0.2, 1.0, 0.0).unwrap();
178        let mut os = vec![0.0f32; n];
179        let mut ol = vec![0.0f32; n];
180        short.process(&input, &mut os).unwrap();
181        long.process(&input, &mut ol).unwrap();
182        let es: f32 = os[30_000..].iter().map(|x| x * x).sum();
183        let el: f32 = ol[30_000..].iter().map(|x| x * x).sum();
184        assert!(
185            el > es,
186            "long-decay late energy {} should exceed short {}",
187            el,
188            es
189        );
190    }
191
192    #[test]
193    fn dry_only_passes_input_through() {
194        let mut r = FdnReverb::new(48_000, 0.7, 0.3, 0.0, 1.0).unwrap();
195        let input = [0.3f32, -0.2, 0.5, 0.1, -0.4];
196        let mut out = [0.0f32; 5];
197        r.process(&input, &mut out).unwrap();
198        for (o, x) in out.iter().zip(input.iter()) {
199            assert!((o - x).abs() < 1e-6);
200        }
201    }
202
203    #[test]
204    fn invalid_params_rejected() {
205        assert_eq!(
206            FdnReverb::new(0, 0.5, 0.5, 1.0, 0.0).err(),
207            Some(AudioError::InvalidParameter)
208        );
209    }
210}