Skip to main content

qualia_audio/fx/reverb/
schroeder.rs

1//! Freeverb / Schroeder reverb — parallel combs → series allpasses.
2//!
3//! Eight feedback [`CombFilter`]s run in parallel (their outputs summed), then
4//! the sum passes through four series [`Allpass`] diffusers. `room_size` sets the
5//! comb feedback (tail length), `damping` the in-loop lowpass (tail brightness),
6//! and `wet`/`dry` the mix.
7//!
8//! All delay buffers are allocated **once** in [`SchroederReverb::new`]. The
9//! `process_sample` / `process` paths never allocate, lock, or touch the FS.
10
11use crate::fx::reverb::allpass::Allpass;
12use crate::fx::reverb::comb::CombFilter;
13use crate::types::AudioError;
14
15/// Freeverb comb delay tunings (samples @ 44.1 kHz), scaled to the target rate.
16const COMB_TUNINGS: [usize; 8] = [1116, 1188, 1277, 1356, 1422, 1491, 1557, 1617];
17/// Freeverb allpass delay tunings (samples @ 44.1 kHz).
18const ALLPASS_TUNINGS: [usize; 4] = [556, 441, 341, 225];
19
20/// Freeverb parameter scaling constants.
21const SCALE_ROOM: f32 = 0.28;
22const OFFSET_ROOM: f32 = 0.7;
23const SCALE_DAMP: f32 = 0.4;
24const FIXED_GAIN: f32 = 0.015;
25
26/// Schroeder/Freeverb-style reverb (8 parallel combs + 4 series allpasses).
27#[derive(Debug, Clone)]
28pub struct SchroederReverb {
29    combs: [CombFilter; 8],
30    allpasses: [Allpass; 4],
31    wet: f32,
32    dry: f32,
33}
34
35impl SchroederReverb {
36    /// Construct for `sample_rate`. `room_size` and `damping` in `[0, 1]`;
37    /// `wet`/`dry` are the linear mix gains. Allocates all delay lines once.
38    pub fn new(
39        sample_rate: u32,
40        room_size: f32,
41        damping: f32,
42        wet: f32,
43        dry: f32,
44    ) -> Result<Self, AudioError> {
45        if sample_rate == 0
46            || !room_size.is_finite()
47            || !damping.is_finite()
48            || !wet.is_finite()
49            || !dry.is_finite()
50        {
51            return Err(AudioError::InvalidParameter);
52        }
53        let feedback = room_size.clamp(0.0, 1.0) * SCALE_ROOM + OFFSET_ROOM;
54        let damp = damping.clamp(0.0, 1.0) * SCALE_DAMP;
55        // Scale the 44.1k reference tunings to the working sample rate.
56        let scale = sample_rate as f32 / 44_100.0;
57        let d = |t: usize| ((t as f32 * scale) as usize).max(1);
58
59        // Build each filter once (constructor allocation only).
60        let combs = [
61            CombFilter::new(d(COMB_TUNINGS[0]), feedback, damp)?,
62            CombFilter::new(d(COMB_TUNINGS[1]), feedback, damp)?,
63            CombFilter::new(d(COMB_TUNINGS[2]), feedback, damp)?,
64            CombFilter::new(d(COMB_TUNINGS[3]), feedback, damp)?,
65            CombFilter::new(d(COMB_TUNINGS[4]), feedback, damp)?,
66            CombFilter::new(d(COMB_TUNINGS[5]), feedback, damp)?,
67            CombFilter::new(d(COMB_TUNINGS[6]), feedback, damp)?,
68            CombFilter::new(d(COMB_TUNINGS[7]), feedback, damp)?,
69        ];
70        let allpasses = [
71            Allpass::new(d(ALLPASS_TUNINGS[0]), 0.5)?,
72            Allpass::new(d(ALLPASS_TUNINGS[1]), 0.5)?,
73            Allpass::new(d(ALLPASS_TUNINGS[2]), 0.5)?,
74            Allpass::new(d(ALLPASS_TUNINGS[3]), 0.5)?,
75        ];
76        Ok(Self {
77            combs,
78            allpasses,
79            wet,
80            dry,
81        })
82    }
83
84    /// Live-update room size (comb feedback) across all combs.
85    pub fn set_room_size(&mut self, room_size: f32) {
86        if room_size.is_finite() {
87            let fb = room_size.clamp(0.0, 1.0) * SCALE_ROOM + OFFSET_ROOM;
88            for c in self.combs.iter_mut() {
89                c.set_feedback(fb);
90            }
91        }
92    }
93
94    /// Live-update damping across all combs.
95    pub fn set_damping(&mut self, damping: f32) {
96        if damping.is_finite() {
97            let damp = damping.clamp(0.0, 1.0) * SCALE_DAMP;
98            for c in self.combs.iter_mut() {
99                c.set_damp(damp);
100            }
101        }
102    }
103
104    /// Set wet/dry linear mix gains.
105    pub fn set_mix(&mut self, wet: f32, dry: f32) {
106        if wet.is_finite() {
107            self.wet = wet;
108        }
109        if dry.is_finite() {
110            self.dry = dry;
111        }
112    }
113
114    /// Clear all delay/state buffers. No allocation.
115    pub fn reset(&mut self) {
116        for c in self.combs.iter_mut() {
117            c.reset();
118        }
119        for a in self.allpasses.iter_mut() {
120            a.reset();
121        }
122    }
123
124    /// Process one sample through the full network. **Zero-alloc, no locks.**
125    #[inline]
126    pub fn process_sample(&mut self, input: f32) -> f32 {
127        let scaled = input * FIXED_GAIN;
128        // Parallel combs, summed.
129        let mut acc = 0.0f32;
130        for c in self.combs.iter_mut() {
131            acc += c.process_sample(scaled);
132        }
133        // Series allpasses.
134        for a in self.allpasses.iter_mut() {
135            acc = a.process_sample(acc);
136        }
137        acc * self.wet + input * self.dry
138    }
139
140    /// Block process. **Zero-alloc.** Errors if `output` is shorter than `input`.
141    pub fn process(&mut self, input: &[f32], output: &mut [f32]) -> Result<(), AudioError> {
142        if output.len() < input.len() {
143            return Err(AudioError::OutputBufferTooSmall);
144        }
145        for (o, &x) in output.iter_mut().zip(input.iter()) {
146            *o = self.process_sample(x);
147        }
148        Ok(())
149    }
150}
151
152#[cfg(test)]
153mod tests {
154    use super::*;
155
156    #[test]
157    fn impulse_produces_bounded_decaying_tail() {
158        // Fully wet so we measure only the reverberant tail.
159        let mut r = SchroederReverb::new(44_100, 0.8, 0.3, 1.0, 0.0).unwrap();
160        let n = 44_100; // 1 second
161        let mut input = vec![0.0f32; n];
162        input[0] = 1.0;
163        let mut out = vec![0.0f32; n];
164        r.process(&input, &mut out).unwrap();
165
166        // Everything finite & bounded (stable network, feedback < 1).
167        assert!(out.iter().all(|x| x.is_finite()), "reverb produced NaN/Inf");
168        assert!(out.iter().all(|x| x.abs() < 4.0), "reverb tail not bounded");
169
170        // RT-style decay: energy in a late window is well below an early window.
171        let win = 4_410; // 100 ms
172        let early: f32 = out[win..2 * win].iter().map(|x| x * x).sum();
173        let late: f32 = out[8 * win..9 * win].iter().map(|x| x * x).sum();
174        assert!(early > 0.0, "expected non-zero early tail energy");
175        assert!(
176            late < early,
177            "late energy {} must be < early {}",
178            late,
179            early
180        );
181        // Meaningful decay, not a plateau.
182        assert!(
183            late < early * 0.5,
184            "tail did not decay enough: late {} early {}",
185            late,
186            early
187        );
188    }
189
190    #[test]
191    fn dry_only_passes_input_through() {
192        let mut r = SchroederReverb::new(48_000, 0.5, 0.5, 0.0, 1.0).unwrap();
193        let input: Vec<f32> = (0..256)
194            .map(|i| (2.0 * core::f32::consts::PI * 440.0 * i as f32 / 48_000.0).sin())
195            .collect();
196        let mut out = vec![0.0f32; 256];
197        r.process(&input, &mut out).unwrap();
198        for (o, x) in out.iter().zip(input.iter()) {
199            assert!((o - x).abs() < 1e-6, "dry path should be identity");
200        }
201    }
202
203    #[test]
204    fn sample_rate_scales_delays() {
205        let r44 = SchroederReverb::new(44_100, 0.5, 0.5, 1.0, 0.0).unwrap();
206        let r88 = SchroederReverb::new(88_200, 0.5, 0.5, 1.0, 0.0).unwrap();
207        // Doubling the rate roughly doubles each comb delay length.
208        assert!(r88.combs[0].delay() > r44.combs[0].delay());
209    }
210
211    #[test]
212    fn invalid_params_rejected() {
213        assert_eq!(
214            SchroederReverb::new(0, 0.5, 0.5, 1.0, 0.0).err(),
215            Some(AudioError::InvalidParameter)
216        );
217        assert_eq!(
218            SchroederReverb::new(44_100, f32::NAN, 0.5, 1.0, 0.0).err(),
219            Some(AudioError::InvalidParameter)
220        );
221    }
222}