SPB Git

Repository Public

convolution.rs 17.3 KB 445 lines rust

1//! ORIX Sonata2//! File: crates/sonata-dsp/src/effects/convolution.rs3//! Description: Convolution reverb: zero-latency partitioned FFT convolution (direct head plus4//! uniformly partitioned tail) with synthetic impulse responses generated at prepare time.5//!6//! Author: Simon-Pierre Boucher7//! Contact: contact@spboucher.ai89use super::{choice, desc, fixed, num, preset};10use crate::analysis::fft::Fft;11use crate::core::Rng;12use crate::effect::Effect;13use crate::filter::{Biquad, BiquadCoefs, BiquadKind};14use sonata_ir::{EffectDesc, LatencySpec, Unit};1516/// Most partitions of an impulse response (bounds the per-block work).17const MAX_PARTS: usize = 750;1819/// One channel of a zero-latency convolver (Gardner 1995).20///21/// The first `P` taps are applied by a direct FIR; the rest is split in partitions of `P` taps,22/// each convolved in the frequency domain by overlap-save with FFTs of size `2P`. A tap at index23/// `>= P` only ever needs input that is at least `P` samples old, so the frequency-domain part24/// can be computed one block ahead: no latency is added.25struct Convolver {26    p: usize,27    fft: Fft,28    head: Vec<f32>,29    /// Input history for the direct part, written twice so a contiguous window is always available.30    hist: Vec<f32>,31    hist_pos: usize,32    /// Spectra of the tail partitions: `parts * (P + 1)` bins, real and imaginary.33    h_re: Vec<f32>,34    h_im: Vec<f32>,35    parts: usize,36    /// Frequency-domain delay line of input spectra.37    x_re: Vec<f32>,38    x_im: Vec<f32>,39    x_head: usize,40    /// Previous and current input block.41    block: Vec<f32>,42    fill: usize,43    /// Output of the tail for the current block.44    tail: Vec<f32>,45    re: Vec<f32>,46    im: Vec<f32>,47    acc_re: Vec<f32>,48    acc_im: Vec<f32>,49}5051impl Convolver {52    fn new(p: usize) -> Convolver {53        let bins = p + 1;54        Convolver {55            p,56            fft: Fft::new(2 * p),57            head: vec![0.0; p],58            hist: vec![0.0; 2 * p],59            hist_pos: 0,60            h_re: vec![0.0; MAX_PARTS * bins],61            h_im: vec![0.0; MAX_PARTS * bins],62            parts: 0,63            x_re: vec![0.0; MAX_PARTS * bins],64            x_im: vec![0.0; MAX_PARTS * bins],65            x_head: 0,66            block: vec![0.0; 2 * p],67            fill: 0,68            tail: vec![0.0; p],69            re: vec![0.0; 2 * p],70            im: vec![0.0; 2 * p],71            acc_re: vec![0.0; bins],72            acc_im: vec![0.0; bins],73        }74    }7576    /// Installs an impulse response (truncated to `(MAX_PARTS + 1) * P` taps). Does not allocate.77    fn set_ir(&mut self, ir: &[f32]) {78        let p = self.p;79        let bins = p + 1;80        for (i, h) in self.head.iter_mut().enumerate() {81            *h = ir.get(i).copied().unwrap_or(0.0);82        }83        let rest = ir.len().saturating_sub(p);84        self.parts = rest.div_ceil(p).min(MAX_PARTS);85        for part in 0..self.parts {86            for i in 0..2 * p {87                self.re[i] = if i < p { ir.get(p + part * p + i).copied().unwrap_or(0.0) } else { 0.0 };88                self.im[i] = 0.0;89            }90            self.fft.forward(&mut self.re, &mut self.im);91            self.h_re[part * bins..(part + 1) * bins].copy_from_slice(&self.re[..bins]);92            self.h_im[part * bins..(part + 1) * bins].copy_from_slice(&self.im[..bins]);93        }94        self.reset();95    }9697    fn reset(&mut self) {98        self.hist.fill(0.0);99        self.x_re.fill(0.0);100        self.x_im.fill(0.0);101        self.block.fill(0.0);102        self.tail.fill(0.0);103        self.fill = 0;104        self.hist_pos = 0;105        self.x_head = 0;106    }107108    #[inline]109    fn tick(&mut self, x: f32) -> f32 {110        let p = self.p;111        // Direct part: y = sum_{j < P} h[j] x[n - j].112        self.hist[self.hist_pos] = x;113        self.hist[self.hist_pos + p] = x;114        let window = &self.hist[self.hist_pos + 1..self.hist_pos + 1 + p]; // oldest .. newest115        let mut acc = 0.0f32;116        for j in 0..p {117            acc += self.head[j] * window[p - 1 - j];118        }119        self.hist_pos = (self.hist_pos + 1) % p;120        let y = acc + self.tail[self.fill];121        self.block[p + self.fill] = x;122        self.fill += 1;123        if self.fill == p {124            self.end_of_block();125        }126        y127    }128129    /// The current input block is complete: compute the tail contribution to the next block.130    fn end_of_block(&mut self) {131        let p = self.p;132        let bins = p + 1;133        self.fill = 0;134        if self.parts == 0 {135            self.tail.fill(0.0);136            self.block.copy_within(p.., 0);137            return;138        }139        // Spectrum of [previous block, current block].140        self.re.copy_from_slice(&self.block);141        self.im.fill(0.0);142        self.fft.forward(&mut self.re, &mut self.im);143        self.x_head = (self.x_head + self.parts - 1) % self.parts;144        let h = self.x_head;145        self.x_re[h * bins..(h + 1) * bins].copy_from_slice(&self.re[..bins]);146        self.x_im[h * bins..(h + 1) * bins].copy_from_slice(&self.im[..bins]);147        // Y = sum_i X_{k - i} H_i  (partition i holds taps [P + iP, P + (i + 1)P)).148        self.acc_re.fill(0.0);149        self.acc_im.fill(0.0);150        for i in 0..self.parts {151            let xs = ((h + i) % self.parts) * bins;152            let hs = i * bins;153            let (xr, xi) = (&self.x_re[xs..xs + bins], &self.x_im[xs..xs + bins]);154            let (hr, hi) = (&self.h_re[hs..hs + bins], &self.h_im[hs..hs + bins]);155            for b in 0..bins {156                self.acc_re[b] += xr[b] * hr[b] - xi[b] * hi[b];157                self.acc_im[b] += xr[b] * hi[b] + xi[b] * hr[b];158            }159        }160        // Hermitian extension, inverse transform; the second half is free of time aliasing.161        self.re[..bins].copy_from_slice(&self.acc_re);162        self.im[..bins].copy_from_slice(&self.acc_im);163        for b in 1..p {164            self.re[2 * p - b] = self.acc_re[b];165            self.im[2 * p - b] = -self.acc_im[b];166        }167        self.fft.inverse(&mut self.re, &mut self.im);168        self.tail.copy_from_slice(&self.re[p..]);169        self.block.copy_within(p.., 0);170    }171}172173/// Parameters of a synthetic space: (RT60 s, pre-delay s, early reflection span s, density of174/// early reflections, high-frequency decay ratio, low-frequency decay ratio).175const SPACES: [(&str, f32, f32, f32, usize, f32, f32); 5] = [176    ("room", 0.5, 0.002, 0.02, 10, 0.55, 1.1),177    ("chamber", 1.0, 0.006, 0.035, 12, 0.6, 1.15),178    ("hall", 2.2, 0.018, 0.07, 14, 0.45, 1.25),179    ("plate", 1.8, 0.0, 0.0, 0, 0.8, 0.9),180    ("cathedral", 4.5, 0.035, 0.11, 16, 0.35, 1.35),181];182183/// Generates a synthetic impulse response: sparse early reflections followed by exponentially184/// decaying Gaussian-like noise in three bands with different decay times (lows ring longer,185/// highs die faster), normalised to unit energy. Deterministic for a given seed.186/// These are synthetic approximations of the named kinds of space, not measurements.187pub fn synth_ir(space: usize, decay_scale: f32, brightness: f32, sample_rate: f32, seed: u64, max_len: usize) -> Vec<f32> {188    let (_, rt, pre, span, n_early, hf, lf) = SPACES[space.min(SPACES.len() - 1)];189    let rt = rt * decay_scale.clamp(0.1, 4.0);190    let len = ((rt * 1.2 + pre + span) * sample_rate) as usize;191    let len = len.clamp(64, max_len);192    let mut ir = vec![0.0f32; len];193    let mut rng = Rng::new(seed);194    // Early reflections: decreasing amplitude, random sign, within `span` after the pre-delay.195    for k in 0..n_early {196        let t = pre + span * ((k as f32 + rng.unipolar()) / n_early as f32).powf(1.3);197        let i = (t * sample_rate) as usize;198        if i < len {199            ir[i] += (if rng.unipolar() < 0.5 { -1.0 } else { 1.0 }) * 0.8 * (1.0 - 0.6 * k as f32 / n_early as f32);200        }201    }202    // Late field: three bands of noise with their own decay.203    let start = ((pre + span * 0.5) * sample_rate) as usize;204    let build = (0.004 * sample_rate).max(1.0);205    let hf = (hf * (0.5 + brightness.clamp(0.0, 1.0))).clamp(0.1, 1.2);206    let a_low = (-std::f32::consts::TAU * 400.0 / sample_rate).exp();207    let a_high = (-std::f32::consts::TAU * 4000.0 / sample_rate).exp();208    let (mut lp1, mut lp2) = (0.0f32, 0.0f32);209    let k = -6.9078 / sample_rate; // ln(0.001) per second210    for i in start..len {211        // Sum of three uniforms: close enough to Gaussian for a diffuse field.212        let n = (rng.bipolar() + rng.bipolar() + rng.bipolar()) * 0.577;213        lp1 = n + (lp1 - n) * a_low;214        lp2 = n + (lp2 - n) * a_high;215        let (low, mid, high) = (lp1, lp2 - lp1, n - lp2);216        let t = (i - start) as f32;217        let fade = (t / build).min(1.0);218        ir[i] += fade * 0.25 * (low * 2.0 * (k * t / (rt * lf)).exp() + mid * (k * t / rt).exp() + high * (k * t / (rt * hf)).exp());219    }220    // Fade the last 5 % so truncation does not click, then normalise to unit energy.221    let tail = (len / 20).max(1);222    for i in 0..tail {223        ir[len - 1 - i] *= i as f32 / tail as f32;224    }225    let energy: f32 = ir.iter().map(|v| v * v).sum();226    if energy > 0.0 {227        let g = 1.0 / energy.sqrt();228        for v in &mut ir {229            *v *= g;230        }231    }232    ir233}234235/// Convolution reverb with built-in synthetic spaces.236///237/// The impulse response is limited to 751 partitions (4.0 s at any supported sample rate, since238/// the partition size scales with the rate); longer ones are faded out at that length.239///240/// `space`, `decay` and `brightness` shape the impulse response, which is generated when the241/// effect is prepared: they are structural parameters, read at compile time; changing them on a242/// sounding effect has no effect until the program is recompiled (hot swap). `low_cut` and243/// `high_cut` filter the reverberated signal and can be automated.244pub struct Convolution {245    sr: f32,246    space: usize,247    decay: f32,248    brightness: f32,249    conv: Option<[Convolver; 2]>,250    filters: [[Biquad; 2]; 2],251    cuts: [f32; 2],252    cuts_dirty: bool,253    ir_dirty: bool,254    live: bool,255    ir_len: usize,256}257258impl Convolution {259    pub fn new() -> Convolution {260        Convolution {261            sr: 48_000.0,262            space: 2,263            decay: 1.0,264            brightness: 0.5,265            conv: None,266            filters: [[Biquad::default(); 2]; 2],267            cuts: [80.0, 16_000.0],268            cuts_dirty: true,269            ir_dirty: true,270            live: false,271            ir_len: 0,272        }273    }274    pub fn desc() -> EffectDesc {275        desc(276            "convolution",277            "Convolution Reverb",278            "space",279            "Zero-latency partitioned convolution with synthetic impulse responses (decaying filtered noise with early reflections) generated deterministically at prepare time. No recorded space is bundled.",280            vec![281                choice("space", &SPACES.map(|s| s.0), "hall", "Kind of synthetic space. Structural: read when the program is compiled."),282                fixed("decay", Unit::Scalar, 0.25, 2.0, 1.0, "Multiplier of the space's reverberation time. Structural."),283                fixed("brightness", Unit::Ratio, 0.0, 1.0, 0.5, "How long high frequencies ring relative to mids. Structural."),284                num("low_cut", Unit::Hertz, 20.0, 1000.0, 80.0, "High-pass on the reverberated signal."),285                num("high_cut", Unit::Hertz, 1000.0, 20_000.0, 16_000.0, "Low-pass on the reverberated signal."),286            ],287            vec![preset("dark_hall", "Long and soft.", &[("decay", 1.3), ("brightness", 0.2), ("high_cut", 8000.0)]), preset("bright_room", "Short and lively.", &[("decay", 0.8), ("brightness", 0.9)])],288            LatencySpec::default(),289            0.25,290        )291    }292    /// Partition size for a sample rate: 256 up to 48 kHz, doubling with the rate.293    fn partition(sample_rate: f32) -> usize {294        (256.0 * (sample_rate / 48_000.0).max(1.0)).ceil() as usize295    }296    /// Length in samples of the impulse response in use (after truncation).297    pub fn ir_len(&self) -> usize {298        self.ir_len299    }300    fn rebuild(&mut self) {301        let Some(conv) = self.conv.as_mut() else { return };302        let max_len = (MAX_PARTS + 1) * conv[0].p;303        for (c, cv) in conv.iter_mut().enumerate() {304            // Different seeds per channel: a decorrelated, wide tail.305            let ir = synth_ir(self.space, self.decay, self.brightness, self.sr, 0x5EED_0000 + self.space as u64 * 16 + c as u64, max_len);306            self.ir_len = ir.len();307            cv.set_ir(&ir);308        }309        self.ir_dirty = false;310    }311}312313impl Default for Convolution {314    fn default() -> Self {315        Self::new()316    }317}318319impl Effect for Convolution {320    fn prepare(&mut self, sample_rate: f32, _: usize) {321        self.sr = sample_rate;322        let p = Self::partition(sample_rate).next_power_of_two();323        self.conv = Some([Convolver::new(p), Convolver::new(p)]);324        self.live = false;325        self.ir_dirty = true;326        self.cuts_dirty = true;327    }328    fn reset(&mut self) {329        if self.ir_dirty && !self.live {330            // Only before the first process call (configuration time): generating an impulse331            // response is far too slow for the audio thread.332            self.rebuild();333        }334        if let Some(conv) = self.conv.as_mut() {335            conv[0].reset();336            conv[1].reset();337        }338        for f in self.filters.iter_mut().flatten() {339            f.reset();340        }341    }342    fn set_param(&mut self, index: usize, value: f32) {343        match index {344            1 if !self.live => {345                self.decay = value;346                self.ir_dirty = true;347            }348            2 if !self.live => {349                self.brightness = value;350                self.ir_dirty = true;351            }352            3 | 4 => {353                self.cuts[index - 3] = value;354                self.cuts_dirty = true;355            }356            _ => {}357        }358    }359    fn set_choice(&mut self, index: usize, choice: usize) {360        if index == 0 && !self.live {361            self.space = choice.min(SPACES.len() - 1);362            self.ir_dirty = true;363        }364    }365    fn process(&mut self, left: &mut [f32], right: &mut [f32]) {366        self.live = true;367        if self.cuts_dirty {368            let hp = BiquadCoefs::design(BiquadKind::Highpass, self.cuts[0], std::f32::consts::FRAC_1_SQRT_2, 0.0, self.sr);369            let lp = BiquadCoefs::design(BiquadKind::Lowpass, self.cuts[1], std::f32::consts::FRAC_1_SQRT_2, 0.0, self.sr);370            for c in 0..2 {371                self.filters[0][c].set_smoothed(hp, 256);372                self.filters[1][c].set_smoothed(lp, 256);373            }374            self.cuts_dirty = false;375        }376        let Some(conv) = self.conv.as_mut() else { return };377        for i in 0..left.len() {378            left[i] = conv[0].tick(left[i]);379            right[i] = conv[1].tick(right[i]);380        }381        for f in &mut self.filters {382            f[0].process(left);383            f[1].process(right);384        }385    }386    fn tail_seconds(&self) -> f32 {387        self.ir_len as f32 / self.sr388    }389}390391#[cfg(test)]392mod tests {393    use super::*;394395    /// The partitioned convolver must equal a direct convolution (tolerance 2e-4 absolute for396    /// unit-scale signals: single-precision FFT round-off), with zero latency, whatever the397    /// impulse response length relative to the partition size.398    #[test]399    fn partitioned_convolution_equals_direct_convolution() {400        let mut rng = Rng::new(9);401        for ir_len in [1usize, 5, 16, 17, 40, 100, 333] {402            let ir: Vec<f32> = (0..ir_len).map(|_| rng.bipolar()).collect();403            let x: Vec<f32> = (0..400).map(|_| rng.bipolar()).collect();404            let mut c = Convolver::new(16);405            c.set_ir(&ir);406            for n in 0..x.len() {407                let y = c.tick(x[n]);408                let want: f32 = (0..ir_len.min(n + 1)).map(|j| ir[j] * x[n - j]).sum();409                assert!((y - want).abs() < 2e-4 * (ir_len as f32).sqrt().max(1.0), "ir {ir_len}, sample {n}: {y} vs {want}");410            }411            c.reset();412            assert_eq!(c.tick(0.0), 0.0);413        }414    }415416    #[test]417    fn synthetic_impulse_responses_are_deterministic_normalised_and_decay() {418        for space in 0..SPACES.len() {419            let ir = synth_ir(space, 1.0, 0.5, 48_000.0, 1, 1 << 20);420            assert_eq!(ir, synth_ir(space, 1.0, 0.5, 48_000.0, 1, 1 << 20));421            assert_ne!(ir, synth_ir(space, 1.0, 0.5, 48_000.0, 2, 1 << 20));422            let energy: f32 = ir.iter().map(|v| v * v).sum();423            assert!((energy - 1.0).abs() < 1e-3);424            assert!(ir.iter().all(|v| v.is_finite()));425            // Schroeder backward integration: the -5 to -35 dB slope gives RT60 within 30 % of the nominal value.426            let mut edc: Vec<f64> = ir427                .iter()428                .rev()429                .scan(0.0f64, |a, v| {430                    *a += (*v as f64).powi(2);431                    Some(*a)432                })433                .collect();434            edc.reverse();435            let db = |i: usize| 10.0 * (edc[i] / edc[0]).log10();436            let t5 = (0..edc.len()).find(|i| db(*i) < -5.0).unwrap();437            let t35 = (0..edc.len()).find(|i| db(*i) < -35.0).unwrap();438            let rt = (t35 - t5) as f32 / 48_000.0 * 2.0;439            let nominal = SPACES[space].1;440            assert!((rt / nominal - 1.0).abs() < 0.3, "{}: measured RT60 {rt} s, nominal {nominal} s", SPACES[space].0);441        }442        assert_eq!(synth_ir(4, 2.0, 0.5, 48_000.0, 1, 1000).len(), 1000);443    }444}445
Files main
Menu

Theme