SPB Git

Repository Public

reverb.rs 8.4 KB 193 lines rust

1//! ORIX Sonata2//! File: crates/sonata-dsp/src/effects/reverb.rs3//! Description: Algorithmic reverberation: an 8-line feedback delay network with Householder4//! mixing, per-line damping, input diffusion, pre-delay and slow modulation.5//!6//! Author: Simon-Pierre Boucher7//! Contact: contact@spboucher.ai89use super::{desc, num, preset};10use crate::core::{flush, DelayLine};11use crate::effect::Effect;12use crate::filter::OnePole;13use sonata_ir::{EffectDesc, LatencySpec, Unit};1415const LINES: usize = 8;16/// Loop delays at size 1, milliseconds (mutually prime sample counts at common rates).17const BASE_MS: [f32; LINES] = [29.7, 37.1, 41.1, 43.7, 53.3, 59.9, 67.7, 73.1];18/// Input diffuser delays, milliseconds (left chain, right chain).19const DIFF_MS: [[f32; 4]; 2] = [[4.77, 3.59, 12.73, 9.31], [4.93, 3.71, 12.31, 9.67]];2021/// Feedback delay network reverb.22///23/// Model: `x -> pre-delay -> 4 series all-passes per channel -> 8 delay lines` fed back through24/// a Householder reflection (`I - 2/N 11^T`, lossless) with, in each loop, a gain setting the25/// mid-frequency decay time (`g_i = 10^(-3 L_i / (T60 fs))`) and a one-pole low-pass setting how26/// much faster high frequencies die (`damping`). Two lines are slowly modulated (+/- 0.25 ms at27/// 0.37 and 0.53 Hz) to break up metallic modes. It is an artificial reverberator in the28/// Jot / Schroeder tradition, not a model of any real room.29pub struct Reverb {30    sr: f32,31    p: [f32; 7],32    lines: [DelayLine; LINES],33    len: [f32; LINES],34    gain: [f32; LINES],35    damp: [OnePole; LINES],36    pre: [DelayLine; 2],37    diff: [[DelayLine; 4]; 2],38    low_cut: [OnePole; 2],39    phase: [f32; 2],40    dirty: bool,41}4243impl Reverb {44    pub fn new() -> Reverb {45        let dl = || DelayLine::new(8);46        Reverb {47            sr: 48_000.0,48            p: [1.8, 0.6, 6000.0, 0.01, 0.8, 100.0, 1.0],49            lines: std::array::from_fn(|_| dl()),50            len: [100.0; LINES],51            gain: [0.0; LINES],52            damp: [OnePole::new(6000.0, 48_000.0); LINES],53            pre: [dl(), dl()],54            diff: std::array::from_fn(|_| std::array::from_fn(|_| dl())),55            low_cut: [OnePole::new(100.0, 48_000.0); 2],56            phase: [0.0, 0.25],57            dirty: true,58        }59    }60    pub fn desc() -> EffectDesc {61        desc(62            "reverb",63            "Reverb",64            "space",65            "Algorithmic reverberation (8-line feedback delay network). `decay` is the mid-frequency RT60; `damping` is the frequency above which the tail dies faster.",66            vec![67                num("decay", Unit::Seconds, 0.1, 30.0, 1.8, "Reverberation time (RT60) at mid frequencies."),68                num("size", Unit::Ratio, 0.0, 1.0, 0.6, "Scale of the delay network: small values give dense, coloured rooms; large values give sparse, spacious halls. Changing it while sounding is audible."),69                num("damping", Unit::Hertz, 500.0, 20_000.0, 6000.0, "Corner of the low-pass inside the loops."),70                num("predelay", Unit::Seconds, 0.0, 0.25, 0.01, "Delay before the reverberation starts."),71                num("diffusion", Unit::Ratio, 0.0, 1.0, 0.8, "Smearing of the input by the all-pass chain."),72                num("low_cut", Unit::Hertz, 20.0, 1000.0, 100.0, "High-pass on the reverberated signal."),73                num("width", Unit::Ratio, 0.0, 1.0, 1.0, "Stereo width of the tail (0 = mono)."),74            ],75            vec![76                preset("room", "Small live room.", &[("decay", 0.6), ("size", 0.25), ("damping", 7000.0), ("predelay", 0.005), ("diffusion", 0.7)]),77                preset("chamber", "Echo chamber.", &[("decay", 1.1), ("size", 0.4), ("damping", 8000.0), ("predelay", 0.01), ("diffusion", 0.75)]),78                preset("hall", "Concert hall.", &[("decay", 2.4), ("size", 0.75), ("damping", 6000.0), ("predelay", 0.02), ("diffusion", 0.8)]),79                preset("plate", "Bright, dense plate.", &[("decay", 1.6), ("size", 0.45), ("damping", 12_000.0), ("predelay", 0.0), ("diffusion", 1.0), ("low_cut", 200.0)]),80                preset("cathedral", "Very long, dark.", &[("decay", 6.5), ("size", 1.0), ("damping", 4500.0), ("predelay", 0.04), ("diffusion", 0.9)]),81            ],82            LatencySpec::default(),83            0.25,84        )85    }86    fn update(&mut self) {87        let scale = 0.3 + 0.9 * self.p[1].clamp(0.0, 1.0);88        let t60 = self.p[0].max(0.05);89        for i in 0..LINES {90            self.len[i] = (BASE_MS[i] * 0.001 * scale * self.sr).round().max(8.0);91            self.gain[i] = 10f32.powf(-3.0 * self.len[i] / (t60 * self.sr));92            self.damp[i].set(self.p[2], self.sr);93        }94        for f in &mut self.low_cut {95            f.set(self.p[5], self.sr);96        }97        self.dirty = false;98    }99}100101impl Default for Reverb {102    fn default() -> Self {103        Self::new()104    }105}106107impl Effect for Reverb {108    fn prepare(&mut self, sample_rate: f32, _: usize) {109        self.sr = sample_rate;110        let max_line = (BASE_MS[LINES - 1] * 0.001 * 1.2 * sample_rate) as usize + 64;111        self.lines = std::array::from_fn(|_| DelayLine::new(max_line));112        self.pre = std::array::from_fn(|_| DelayLine::new((0.25 * sample_rate) as usize + 8));113        self.diff = std::array::from_fn(|c| std::array::from_fn(|k| DelayLine::new((DIFF_MS[c][k] * 0.001 * sample_rate) as usize + 8)));114        self.damp = [OnePole::new(self.p[2], sample_rate); LINES];115        self.low_cut = [OnePole::new(self.p[5], sample_rate); 2];116        self.dirty = true;117        self.reset();118    }119    fn reset(&mut self) {120        for l in self.lines.iter_mut().chain(self.pre.iter_mut()).chain(self.diff.iter_mut().flatten()) {121            l.clear();122        }123        for f in self.damp.iter_mut().chain(self.low_cut.iter_mut()) {124            f.reset();125        }126        self.phase = [0.0, 0.25];127    }128    fn set_param(&mut self, index: usize, value: f32) {129        if let Some(p) = self.p.get_mut(index) {130            if *p != value {131                *p = value;132                self.dirty = true;133            }134        }135    }136    fn process(&mut self, left: &mut [f32], right: &mut [f32]) {137        if self.dirty {138            self.update();139        }140        let pre = (self.p[3] * self.sr).max(1.0);141        let g = 0.7 * self.p[4].clamp(0.0, 1.0);142        let width = self.p[6].clamp(0.0, 1.0);143        let mod_depth = 0.00025 * self.sr;144        let incs = [0.37 / self.sr, 0.53 / self.sr];145        for i in 0..left.len() {146            // Pre-delay and input diffusion.147            let mut input = [left[i], right[i]];148            for c in 0..2 {149                let d = self.pre[c].read(pre);150                self.pre[c].write(input[c]);151                let mut x = if self.p[3] * self.sr < 1.0 { input[c] } else { d };152                for k in 0..4 {153                    let n = (DIFF_MS[c][k] * 0.001 * self.sr) as usize;154                    let delayed = self.diff[c][k].read_int(n.max(1));155                    let v = x + g * delayed;156                    self.diff[c][k].write(flush(v));157                    x = delayed - g * v;158                }159                input[c] = x;160            }161            // Read the lines (two of them slowly modulated).162            let mut y = [0.0f32; LINES];163            for k in 0..LINES {164                y[k] = if k < 2 {165                    self.phase[k] += incs[k];166                    if self.phase[k] >= 1.0 {167                        self.phase[k] -= 1.0;168                    }169                    self.lines[k].read(self.len[k] + mod_depth * (std::f32::consts::TAU * self.phase[k]).sin())170                } else {171                    self.lines[k].read_int(self.len[k] as usize)172                };173            }174            // Householder reflection, loop filters, injection.175            let sum: f32 = y.iter().sum::<f32>() * (2.0 / LINES as f32);176            for k in 0..LINES {177                let fb = self.damp[k].lowpass((y[k] - sum) * self.gain[k]);178                self.lines[k].write(flush(fb + input[k & 1] * 0.5));179            }180            // Decorrelated outputs: alternating signs over the even / odd lines.181            let l = (y[0] - y[2] + y[4] - y[6]) * 0.5;182            let r = (y[1] - y[3] + y[5] - y[7]) * 0.5;183            let (l, r) = (self.low_cut[0].highpass(l), self.low_cut[1].highpass(r));184            let (mid, side) = (0.5 * (l + r), 0.5 * (l - r) * width);185            left[i] = mid + side;186            right[i] = mid - side;187        }188    }189    fn tail_seconds(&self) -> f32 {190        self.p[0] + self.p[3]191    }192}193
Files main
Menu

Theme