Skip to main content

alpha2_audio/
reverb.rs

1#![allow(
2    clippy::cast_possible_truncation,
3    clippy::cast_precision_loss,
4    clippy::cast_sign_loss
5)]
6
7use crate::biquad::flush_denormal;
8use crate::{ProcessCtx, Processor, StateBlob, StateError};
9
10/// Allocation-free prepared Schroeder reverb with four combs and two allpasses.
11///
12/// Retuned ([`Processor::control`]), its wet mix moves in a straight line from one control
13/// point's value to the next's.
14#[derive(Clone, Debug)]
15pub struct SchroederReverb {
16    room_size: f32,
17    /// The authored damping coefficient at [`REFERENCE_RATE`].
18    damping: f32,
19    /// [`Self::damping`] converted to the prepared rate, keeping its time constant.
20    damping_coefficient: f32,
21    wet: f32,
22    combs: Vec<DelayLine>,
23    allpasses: Vec<DelayLine>,
24    bypass: bool,
25    ramp: Option<WetRamp>,
26}
27
28#[derive(Clone, Copy, Debug)]
29struct WetRamp {
30    from: f32,
31    change: f32,
32    phase: usize,
33}
34
35impl WetRamp {
36    fn at(&self, frame: usize) -> f32 {
37        let progress = crate::control::progress(self.phase, frame);
38        self.from + self.change * progress
39    }
40}
41
42/// The loudest mono sample the lines take, low enough that no comb or allpass state overflows.
43const MAX_LINE_INPUT: f32 = 1.0e30;
44
45const REFERENCE_RATE: f64 = 44_100.0;
46/// Comb lengths at [`REFERENCE_RATE`], shortest first.
47const COMB_LENGTHS: [usize; 4] = [1116, 1188, 1277, 1356];
48/// Allpass lengths at [`REFERENCE_RATE`].
49const ALLPASS_LENGTHS: [usize; 2] = [556, 441];
50
51/// `rate` capped at 768 kHz, the highest `AudioContext` rate, so absurd rates cannot oversize
52/// the lines (at 768 kHz they hold about 103 000 samples, 413 KB).
53fn line_rate(rate: u32) -> u32 {
54    rate.clamp(1, crate::MAX_RESAMPLE_RATE)
55}
56
57fn line_length(length: usize, rate: u32) -> usize {
58    (length as f32 * (rate as f32 / REFERENCE_RATE as f32)).round() as usize
59}
60
61/// The one-pole coefficient at `rate` matching `damping` at [`REFERENCE_RATE`]:
62/// d^(44100 / rate).
63fn damping_at(damping: f32, rate: u32) -> f32 {
64    if damping > 0.0 && damping < 1.0 {
65        libm::pow(f64::from(damping), REFERENCE_RATE / f64::from(rate)) as f32
66    } else {
67        damping
68    }
69}
70
71#[derive(Clone, Debug)]
72struct DelayLine {
73    samples: Vec<f32>,
74    cursor: usize,
75    filter: f32,
76}
77
78impl DelayLine {
79    fn new(length: usize) -> Self {
80        Self {
81            samples: vec![0.0; length.max(1)],
82            cursor: 0,
83            filter: 0.0,
84        }
85    }
86    fn comb(&mut self, input: f32, feedback: f32, damping: f32) -> f32 {
87        let delayed = self.samples[self.cursor];
88        self.filter = flush_denormal(delayed * (1.0 - damping) + self.filter * damping);
89        self.samples[self.cursor] = flush_denormal(input + self.filter * feedback);
90        self.cursor = (self.cursor + 1) % self.samples.len();
91        delayed
92    }
93    fn allpass(&mut self, input: f32) -> f32 {
94        let delayed = self.samples[self.cursor];
95        let output = delayed - input;
96        self.samples[self.cursor] = flush_denormal(input + delayed * 0.5);
97        self.cursor = (self.cursor + 1) % self.samples.len();
98        output
99    }
100}
101
102impl SchroederReverb {
103    /// Creates a reverb with room, damping, and wet controls clamped to the unit interval.
104    /// Non-finite values fall back to 0.7, 0.3, and 0.25.
105    #[must_use]
106    pub fn new(room_size: f32, damping: f32, wet: f32) -> Self {
107        Self {
108            room_size: unit(room_size, 0.7),
109            damping: unit(damping, 0.3),
110            damping_coefficient: unit(damping, 0.3),
111            wet: unit(wet, 0.25),
112            combs: Vec::new(),
113            allpasses: Vec::new(),
114            bypass: false,
115            ramp: None,
116        }
117    }
118    /// Enables transparent bypass while the tail continues evolving.
119    pub fn set_bypass(&mut self, bypass: bool) {
120        self.bypass = bypass;
121    }
122    /// How long the reverb rings after its input stops, in samples at `sample_rate`: the time
123    /// for low frequencies to fall 60 dB through the longest comb plus the allpasses' 60 dB.
124    /// A room of 1 rings about four seconds.
125    #[must_use]
126    pub fn tail_samples(&self, sample_rate: u32) -> u64 {
127        let safe_rate = line_rate(sample_rate);
128        let longest = line_length(COMB_LENGTHS[COMB_LENGTHS.len() - 1], safe_rate) as f64;
129        let damping = f64::from(damping_at(self.damping, safe_rate));
130        let comb = if damping >= 1.0 {
131            // With zero feedback a comb repeats its input once.
132            longest
133        } else {
134            let feedback = f64::from(self.feedback());
135            // Each cycle loses ln(feedback) at low frequencies and lasts the line plus the
136            // filter's group delay.
137            let cycles = libm::log(1_000.0) / -libm::log(feedback);
138            longest + cycles * (longest + damping / (1.0 - damping))
139        };
140        // An allpass's feedback of 0.5 loses 60 dB in ten trips.
141        let allpasses = ALLPASS_LENGTHS
142            .into_iter()
143            .map(|length| line_length(length, safe_rate) as f64 * 10.0)
144            .sum::<f64>();
145        libm::ceil(comb + allpasses) as u64
146    }
147    /// The combs' feedback gain.
148    fn feedback(&self) -> f32 {
149        0.65 + self.room_size * 0.3
150    }
151}
152
153impl SchroederReverb {
154    fn run(
155        &mut self,
156        inputs: &[&[f32]],
157        outputs: &mut [&mut [f32]],
158        wet_at_frame: impl Fn(usize) -> f32,
159    ) -> usize {
160        let channels = inputs.len().min(outputs.len()).min(2);
161        let frames = inputs
162            .iter()
163            .take(channels)
164            .map(|v| v.len())
165            .chain(outputs.iter().take(channels).map(|v| v.len()))
166            .min()
167            .unwrap_or(0);
168        if self.combs.is_empty() {
169            return 0;
170        }
171        for frame in 0..frames {
172            let wet = wet_at_frame(frame);
173            let mono = inputs[..channels]
174                .iter()
175                .map(|channel| channel[frame])
176                .sum::<f32>()
177                / channels.max(1) as f32;
178            // A non-finite value would circulate until reset, so treat it as silence, and clamp
179            // finite ones so no line overflows (comb gain < 1 / (1 - 0.95) = 20, allpass < 2).
180            let mono = if mono.is_finite() {
181                mono.clamp(-MAX_LINE_INPUT, MAX_LINE_INPUT)
182            } else {
183                0.0
184            };
185            let (feedback, damping) = (self.feedback(), self.damping_coefficient);
186            let mut reverberant = self
187                .combs
188                .iter_mut()
189                .map(|comb| comb.comb(mono, feedback, damping))
190                .sum::<f32>()
191                / self.combs.len() as f32;
192            for allpass in &mut self.allpasses {
193                reverberant = allpass.allpass(reverberant);
194            }
195            for channel in 0..channels {
196                let input = finite_or_zero(inputs[channel][frame]);
197                outputs[channel][frame] = if self.bypass {
198                    input
199                } else {
200                    input * (1.0 - wet) + reverberant * wet
201                };
202            }
203        }
204        frames
205    }
206}
207
208impl Processor for SchroederReverb {
209    fn history_samples(&self) -> u32 {
210        let delay = self
211            .combs
212            .iter()
213            .map(|line| line.samples.len())
214            .max()
215            .unwrap_or(0);
216        let delay = u32::try_from(delay).unwrap_or(u32::MAX);
217        let comb = if self.damping_coefficient >= 1.0 {
218            // The zero-initialized feedback filter never changes in this case.
219            f64::from(delay)
220        } else {
221            let damping = f64::from(self.damping_coefficient);
222            let feedback = f64::from(self.feedback());
223            (f64::from(delay) + 1.0 / (1.0 - damping)) * 32.0 / (1.0 - feedback)
224        };
225        let comb = libm::ceil(comb) as u32;
226        self.allpasses.iter().fold(comb, |total, line| {
227            total.saturating_add(
228                u32::try_from(line.samples.len())
229                    .unwrap_or(u32::MAX)
230                    .saturating_mul(crate::processor::settling_samples(0.5)),
231            )
232        })
233    }
234
235    /// The wet mix.
236    fn control_params(&self) -> usize {
237        1
238    }
239
240    fn control(&mut self, span: &crate::ControlSpan<'_>) {
241        let (&[wet], &[next_wet]) = (span.from, span.to) else {
242            return;
243        };
244        let wet = unit(wet, 0.25);
245        if span.is_steady() {
246            self.wet = wet;
247            self.ramp = None;
248            return;
249        }
250        self.ramp = Some(WetRamp {
251            from: wet,
252            change: unit(next_wet, 0.25) - wet,
253            phase: span.phase,
254        });
255    }
256
257    fn prepare(&mut self, sample_rate: u32, _max_block: usize) {
258        let safe_rate = line_rate(sample_rate);
259        self.combs = COMB_LENGTHS
260            .into_iter()
261            .map(|length| DelayLine::new(line_length(length, safe_rate)))
262            .collect();
263        self.allpasses = ALLPASS_LENGTHS
264            .into_iter()
265            .map(|length| DelayLine::new(line_length(length, safe_rate)))
266            .collect();
267        self.damping_coefficient = damping_at(self.damping, safe_rate);
268    }
269    fn process(&mut self, _ctx: &ProcessCtx, inputs: &[&[f32]], outputs: &mut [&mut [f32]]) {
270        match self.ramp {
271            None => {
272                let steady = self.wet;
273                self.run(inputs, outputs, |_| steady);
274            }
275            Some(ramp) => {
276                let frames = self.run(inputs, outputs, |frame| ramp.at(frame));
277                self.ramp = Some(WetRamp {
278                    phase: ramp.phase.saturating_add(frames),
279                    ..ramp
280                });
281            }
282        }
283    }
284    fn reset(&mut self) {
285        for delay in self.combs.iter_mut().chain(&mut self.allpasses) {
286            delay.samples.fill(0.0);
287            delay.cursor = 0;
288            delay.filter = 0.0;
289        }
290    }
291    fn save_state(&self) -> StateBlob {
292        let mut bytes = Vec::new();
293        for delay in self.combs.iter().chain(&self.allpasses) {
294            bytes.extend_from_slice(&(u64::try_from(delay.cursor).unwrap_or(0)).to_le_bytes());
295            bytes.extend_from_slice(&delay.filter.to_le_bytes());
296            for sample in &delay.samples {
297                bytes.extend_from_slice(&sample.to_le_bytes());
298            }
299        }
300        StateBlob::new(bytes)
301    }
302    fn load_state(&mut self, state: &StateBlob) -> Result<(), StateError> {
303        let bytes = state.as_bytes();
304        // Each line saves cursor, filter, then samples; validate all before loading any.
305        let expected = self
306            .combs
307            .iter()
308            .chain(&self.allpasses)
309            .map(|delay| 12 + delay.samples.len() * 4)
310            .sum::<usize>();
311        if bytes.len() != expected {
312            return Err(StateError::Mismatch);
313        }
314        let mut offset = 0;
315        for delay in self.combs.iter().chain(&self.allpasses) {
316            let cursor = usize::try_from(u64::from_le_bytes(
317                bytes[offset..offset + 8].try_into().expect("fixed range"),
318            ))
319            .ok();
320            let values = bytes[offset + 8..offset + 12 + delay.samples.len() * 4]
321                .as_chunks::<4>()
322                .0
323                .iter()
324                .map(|word| f32::from_le_bytes(*word));
325            if cursor.is_none_or(|value| value >= delay.samples.len())
326                || values.clone().any(|value| !value.is_finite())
327            {
328                return Err(StateError::Invalid);
329            }
330            offset += 12 + delay.samples.len() * 4;
331        }
332        let mut offset = 0;
333        for delay in self.combs.iter_mut().chain(&mut self.allpasses) {
334            let mut values = bytes[offset + 8..offset + 12 + delay.samples.len() * 4]
335                .as_chunks::<4>()
336                .0
337                .iter()
338                .map(|word| f32::from_le_bytes(*word));
339            delay.cursor = usize::try_from(u64::from_le_bytes(
340                bytes[offset..offset + 8].try_into().expect("fixed range"),
341            ))
342            .unwrap_or(0);
343            delay.filter = values.next().unwrap_or(0.0);
344            for (target, value) in delay.samples.iter_mut().zip(values) {
345                *target = value;
346            }
347            offset += 12 + delay.samples.len() * 4;
348        }
349        Ok(())
350    }
351}
352
353fn unit(value: f32, fallback: f32) -> f32 {
354    if value.is_finite() {
355        value.clamp(0.0, 1.0)
356    } else {
357        fallback
358    }
359}
360
361fn finite_or_zero(value: f32) -> f32 {
362    if value.is_finite() { value } else { 0.0 }
363}
364
365#[cfg(test)]
366mod tests {
367    use super::SchroederReverb;
368    use crate::{ProcessCtx, Processor, TransportState};
369    use alpha2_time::MediaTime;
370
371    /// The impulse response of a fully wet reverb, `seconds` long.
372    fn impulse_response(room_size: f32, damping: f32, sample_rate: u32, seconds: f64) -> Vec<f32> {
373        let mut reverb = SchroederReverb::new(room_size, damping, 1.0);
374        reverb.prepare(sample_rate, 512);
375        let ctx = ProcessCtx {
376            position: MediaTime::ZERO,
377            sample_position: 0,
378            sample_rate,
379            transport: TransportState::Playing,
380        };
381        let frames = (f64::from(sample_rate) * seconds) as usize;
382        let mut input = vec![0.0; frames];
383        input[0] = 1.0;
384        let mut output = vec![0.0; frames];
385        for (input, output) in input.chunks(512).zip(output.chunks_mut(512)) {
386            reverb.process(&ctx, &[input], &mut [output]);
387        }
388        output
389    }
390
391    /// Decay in dB per second around `frequency`: energy through a fourth-order band-pass (two RBJ
392    /// sections, Q 1.414) over 0.2 to 0.4 s against 0.6 to 0.8 s.
393    fn band_decay_db_per_second(response: &[f32], sample_rate: u32, frequency: f64) -> f64 {
394        let omega = core::f64::consts::TAU * frequency / f64::from(sample_rate);
395        let alpha = libm::sin(omega) / (2.0 * 1.414);
396        let a0 = 1.0 + alpha;
397        let (b0, b2, a1, a2) = (
398            alpha / a0,
399            -alpha / a0,
400            -2.0 * libm::cos(omega) / a0,
401            (1.0 - alpha) / a0,
402        );
403        let mut signal = response
404            .iter()
405            .map(|&sample| f64::from(sample))
406            .collect::<Vec<_>>();
407        for _ in 0..2 {
408            let (mut x1, mut x2, mut y1, mut y2) = (0.0, 0.0, 0.0, 0.0);
409            for sample in &mut signal {
410                let y = b0 * *sample + b2 * x2 - a1 * y1 - a2 * y2;
411                (x2, x1, y2, y1) = (x1, *sample, y1, y);
412                *sample = y;
413            }
414        }
415        let energy = |from: f64, to: f64| {
416            let rate = f64::from(sample_rate);
417            signal[(from * rate) as usize..(to * rate) as usize]
418                .iter()
419                .map(|sample| sample * sample)
420                .sum::<f64>()
421        };
422        10.0 * libm::log10(energy(0.2, 0.4) / energy(0.6, 0.8)) / 0.4
423    }
424
425    #[test]
426    fn a_room_decays_alike_in_every_band_at_any_project_rate() {
427        for (room_size, damping) in [(0.7, 0.3), (0.7, 0.5), (0.9, 0.2)] {
428            for frequency in [500.0, 5_000.0, 8_000.0] {
429                let reference = band_decay_db_per_second(
430                    &impulse_response(room_size, damping, 48_000, 1.0),
431                    48_000,
432                    frequency,
433                );
434                for sample_rate in [44_100, 96_000] {
435                    let decay = band_decay_db_per_second(
436                        &impulse_response(room_size, damping, sample_rate, 1.0),
437                        sample_rate,
438                        frequency,
439                    );
440                    let difference = (decay / reference - 1.0).abs();
441                    assert!(
442                        difference < 0.08,
443                        "room {room_size} damping {damping} at {frequency} Hz: {decay:.1} dB/s at {sample_rate} Hz, {reference:.1} at 48 kHz"
444                    );
445                }
446            }
447        }
448    }
449
450    #[test]
451    fn the_tail_bound_outlasts_every_room_without_overstating_it() {
452        for sample_rate in [44_100, 48_000, 96_000] {
453            for room_size in [1.0, 0.95, 0.9, 0.5, 0.0] {
454                for damping in [0.0, 0.3, 0.7, 1.0] {
455                    let response = impulse_response(room_size, damping, sample_rate, 5.5);
456                    let peak = response
457                        .iter()
458                        .fold(0.0_f32, |peak, sample| peak.max(sample.abs()));
459                    // The last sample within 60 dB of the peak.
460                    let rings = response
461                        .iter()
462                        .rposition(|sample| sample.abs() >= peak * 1.0e-3)
463                        .expect("a response") as u64;
464                    assert!(
465                        rings < response.len() as u64 - u64::from(sample_rate) / 4,
466                        "the response is long enough to measure"
467                    );
468                    let mut reverb = SchroederReverb::new(room_size, damping, 1.0);
469                    let tail = reverb.tail_samples(sample_rate);
470                    reverb.prepare(sample_rate, 512);
471                    assert_eq!(reverb.tail_samples(sample_rate), tail, "prepared or not");
472                    assert!(
473                        rings <= tail,
474                        "room {room_size} damping {damping} at {sample_rate} Hz rings {rings} samples, past {tail}"
475                    );
476                    assert!(
477                        tail <= rings * 3,
478                        "room {room_size} damping {damping} at {sample_rate} Hz rings {rings} samples, far under {tail}"
479                    );
480                }
481            }
482        }
483    }
484
485    #[test]
486    fn a_decaying_tail_never_leaves_subnormal_state() {
487        // A small, bright room empties its combs within seconds; the allpasses then only halve.
488        let mut reverb = SchroederReverb::new(0.0, 0.0, 1.0);
489        reverb.prepare(48_000, 128);
490        let ctx = ProcessCtx {
491            position: MediaTime::ZERO,
492            sample_position: 0,
493            sample_rate: 48_000,
494            transport: TransportState::Playing,
495        };
496        let burst = [0.5_f32; 128];
497        let silence = [0.0_f32; 128];
498        let mut output = [0.0_f32; 128];
499        reverb.process(&ctx, &[&burst], &mut [&mut output]);
500        for block in 0..3_750 {
501            reverb.process(&ctx, &[&silence], &mut [&mut output]);
502            let subnormal = reverb
503                .combs
504                .iter()
505                .chain(&reverb.allpasses)
506                .flat_map(|line| line.samples.iter().chain([&line.filter]))
507                .find(|value| value.is_subnormal());
508            assert_eq!(subnormal, None, "block {block}");
509        }
510    }
511}