Repository Public
1//! ORIX Sonata2//! File: crates/sonata-dsp/src/effects/eq.rs3//! Description: Parametric equaliser (low cut, low shelf, three peaks, high shelf, high cut)4//! and a resonant multimode filter.5//!6//! Author: Simon-Pierre Boucher7//! Contact: contact@spboucher.ai89use super::{choice, desc, num, preset};10use crate::core::OnePoleSmoother;11use crate::effect::Effect;12use crate::filter::{Biquad, BiquadCoefs, BiquadKind, Svf};13use sonata_ir::{EffectDesc, LatencySpec, Unit};1415const EQ_BANDS: usize = 7;16/// Samples over which a coefficient change is glided.17const EQ_GLIDE: u32 = 256;1819/// Seven-band parametric equaliser built from RBJ biquads. A band at 0 dB (or a cut filter at20/// the end of its range) is exactly transparent and costs nothing.21pub struct Eq {22 sr: f32,23 p: [f32; 15],24 bands: [[Biquad; 2]; EQ_BANDS],25 active: [bool; EQ_BANDS],26 dirty: bool,27 first: bool,28}2930impl Eq {31 pub fn new() -> Eq {32 Eq {33 sr: 48_000.0,34 p: [10.0, 100.0, 0.0, 300.0, 0.0, 1.0, 1000.0, 0.0, 1.0, 4000.0, 0.0, 1.0, 8000.0, 0.0, 22_000.0],35 bands: [[Biquad::default(); 2]; EQ_BANDS],36 active: [false; EQ_BANDS],37 dirty: true,38 first: true,39 }40 }41 pub fn desc() -> EffectDesc {42 let mut params = vec![43 num("low_cut", Unit::Hertz, 10.0, 2000.0, 10.0, "High-pass corner (12 dB/octave). Off at 10 Hz."),44 num("low_freq", Unit::Hertz, 20.0, 1000.0, 100.0, "Low shelf corner frequency."),45 num("low_gain", Unit::Decibel, -24.0, 24.0, 0.0, "Low shelf gain."),46 ];47 for (i, f) in [(1, 300.0), (2, 1000.0), (3, 4000.0)] {48 params.push(num(&format!("mid{i}_freq"), Unit::Hertz, 20.0, 20_000.0, f, "Centre frequency of the peak band."));49 params.push(num(&format!("mid{i}_gain"), Unit::Decibel, -24.0, 24.0, 0.0, "Gain of the peak band."));50 params.push(num(&format!("mid{i}_q"), Unit::Scalar, 0.1, 18.0, 1.0, "Quality factor of the peak band (centre frequency over bandwidth)."));51 }52 params.push(num("high_freq", Unit::Hertz, 1000.0, 20_000.0, 8000.0, "High shelf corner frequency."));53 params.push(num("high_gain", Unit::Decibel, -24.0, 24.0, 0.0, "High shelf gain."));54 params.push(num("high_cut", Unit::Hertz, 200.0, 22_000.0, 22_000.0, "Low-pass corner (12 dB/octave). Off at 22 kHz."));55 desc(56 "eq",57 "Parametric EQ",58 "tone",59 "Low cut, low shelf, three parametric peaks, high shelf and high cut. Minimum-phase biquads; flat bands are bit-transparent.",60 params,61 vec![62 preset("air", "Open the top.", &[("high_freq", 10_000.0), ("high_gain", 4.0)]),63 preset("warm", "Fuller lows, softer highs.", &[("low_gain", 3.0), ("high_gain", -2.5), ("high_freq", 6000.0)]),64 preset("clean_lows", "Remove rumble and mud.", &[("low_cut", 60.0), ("mid1_freq", 250.0), ("mid1_gain", -3.0), ("mid1_q", 1.2)]),65 preset("presence", "Bring a part forward.", &[("mid2_freq", 3000.0), ("mid2_gain", 3.5), ("mid2_q", 0.9)]),66 preset("telephone", "Band-limited.", &[("low_cut", 300.0), ("high_cut", 3400.0), ("mid2_freq", 1500.0), ("mid2_gain", 4.0)]),67 ],68 LatencySpec::default(),69 1.0,70 )71 }7273 /// Coefficients of band `b` and whether it does anything.74 fn design(&self, b: usize) -> (BiquadCoefs, bool) {75 let p = &self.p;76 let sr = self.sr;77 let d = BiquadCoefs::design;78 match b {79 0 => (d(BiquadKind::Highpass, p[0], std::f32::consts::FRAC_1_SQRT_2, 0.0, sr), p[0] > 10.01),80 1 => (d(BiquadKind::LowShelf, p[1], std::f32::consts::FRAC_1_SQRT_2, p[2], sr), p[2].abs() > 1e-4),81 2..=4 => {82 let k = 3 + (b - 2) * 3;83 (d(BiquadKind::Peak, p[k], p[k + 2], p[k + 1], sr), p[k + 1].abs() > 1e-4)84 }85 5 => (d(BiquadKind::HighShelf, p[12], std::f32::consts::FRAC_1_SQRT_2, p[13], sr), p[13].abs() > 1e-4),86 _ => (d(BiquadKind::Lowpass, p[14], std::f32::consts::FRAC_1_SQRT_2, 0.0, sr), p[14] < 21_999.0 && p[14] < 0.49 * sr),87 }88 }8990 /// Magnitude of the whole equaliser at `freq`, linear (for Filter Lab curves and tests).91 pub fn magnitude(&self, freq: f32) -> f32 {92 (0..EQ_BANDS).map(|b| self.design(b)).filter(|(_, on)| *on).map(|(c, _)| c.magnitude(freq, self.sr)).product()93 }94}9596impl Default for Eq {97 fn default() -> Self {98 Self::new()99 }100}101102impl Effect for Eq {103 fn prepare(&mut self, sample_rate: f32, _: usize) {104 self.sr = sample_rate;105 self.dirty = true;106 self.first = true;107 self.reset();108 }109 fn reset(&mut self) {110 for b in &mut self.bands {111 b[0].reset();112 b[1].reset();113 }114 self.first = true;115 self.dirty = true;116 }117 fn set_param(&mut self, index: usize, value: f32) {118 if let Some(p) = self.p.get_mut(index) {119 if *p != value {120 *p = value;121 self.dirty = true;122 }123 }124 }125 fn process(&mut self, left: &mut [f32], right: &mut [f32]) {126 if self.dirty {127 for b in 0..EQ_BANDS {128 let (c, on) = self.design(b);129 let c = if on { c } else { BiquadCoefs::IDENTITY };130 // A band stays in the path while it glides back to identity.131 let glide = if self.first || !(self.active[b] || on) { 0 } else { EQ_GLIDE };132 self.bands[b][0].set_smoothed(c, glide);133 self.bands[b][1].set_smoothed(c, glide);134 self.active[b] = on || (self.active[b] && glide > 0);135 }136 self.dirty = false;137 self.first = false;138 }139 for b in 0..EQ_BANDS {140 if self.active[b] {141 self.bands[b][0].process(left);142 self.bands[b][1].process(right);143 }144 }145 }146}147148/// Resonant multimode filter: zero-delay-feedback state-variable stages, 12 or 24 dB/octave,149/// cutoff smoothed (5 ms) so sweeps and automation do not zip.150pub struct Filter {151 sr: f32,152 cutoff: OnePoleSmoother,153 q: f32,154 mode: usize,155 poles4: bool,156 svf: [[Svf; 2]; 2],157}158159impl Filter {160 pub fn new() -> Filter {161 Filter {162 sr: 48_000.0,163 cutoff: OnePoleSmoother::new(1000.0, 0.005, 48_000.0),164 q: std::f32::consts::FRAC_1_SQRT_2,165 mode: 0,166 poles4: false,167 svf: [[Svf::new(48_000.0); 2]; 2],168 }169 }170 pub fn desc() -> EffectDesc {171 desc(172 "filter",173 "Filter",174 "tone",175 "Resonant state-variable filter. Stable under fast modulation of the cutoff.",176 vec![177 choice("mode", &["lowpass", "highpass", "bandpass", "notch"], "lowpass", "Response type."),178 num("cutoff", Unit::Hertz, 20.0, 20_000.0, 1000.0, "Corner or centre frequency."),179 num("resonance", Unit::Scalar, 0.3, 20.0, std::f64::consts::FRAC_1_SQRT_2, "Quality factor; 0.707 is maximally flat."),180 choice("slope", &["12db", "24db"], "12db", "Steepness per octave (one or two cascaded stages)."),181 ],182 vec![183 preset("dark", "Roll off the top.", &[("cutoff", 2500.0)]),184 preset("resonant_sweep", "Emphasised corner.", &[("cutoff", 800.0), ("resonance", 4.0)]),185 ],186 LatencySpec::default(),187 1.0,188 )189 }190}191192impl Default for Filter {193 fn default() -> Self {194 Self::new()195 }196}197198impl Effect for Filter {199 fn prepare(&mut self, sample_rate: f32, _: usize) {200 self.sr = sample_rate;201 let target = self.cutoff.target();202 self.cutoff = OnePoleSmoother::new(target, 0.005, sample_rate);203 self.svf = [[Svf::new(sample_rate); 2]; 2];204 }205 fn reset(&mut self) {206 for s in self.svf.iter_mut().flatten() {207 s.reset();208 }209 let t = self.cutoff.target();210 self.cutoff.snap(t);211 }212 fn set_param(&mut self, index: usize, value: f32) {213 match index {214 1 => self.cutoff.set_target(value),215 2 => self.q = value,216 _ => {}217 }218 }219 fn set_choice(&mut self, index: usize, choice: usize) {220 match index {221 0 => self.mode = choice,222 3 => self.poles4 = choice == 1,223 _ => {}224 }225 }226 fn process(&mut self, left: &mut [f32], right: &mut [f32]) {227 let k = 1.0 / self.q.max(0.3);228 let stages = if self.poles4 { 2 } else { 1 };229 for i in 0..left.len() {230 let f = self.cutoff.tick();231 // The tangent is recomputed every 8 samples (the smoother moves little in 0.17 ms).232 if i.is_multiple_of(8) {233 for s in self.svf.iter_mut().flatten() {234 s.set(f, self.q);235 }236 }237 let (mut l, mut r) = (left[i], right[i]);238 for st in 0..stages {239 let (a, b) = (self.svf[st][0].tick(l), self.svf[st][1].tick(r));240 (l, r) = match self.mode {241 0 => (a.low, b.low),242 1 => (a.high, b.high),243 2 => (a.band * k, b.band * k),244 _ => (a.low + a.high, b.low + b.high),245 };246 }247 left[i] = l;248 right[i] = r;249 }250 }251}252