SPB Git

Repository Public

time.rs 15.9 KB 449 lines rust

1//! ORIX Sonata2//! File: crates/sonata-dsp/src/effects/time.rs3//! Description: Delay-line effects: stereo / ping-pong delay with filtered feedback, chorus,4//! flanger and phaser.5//!6//! Author: Simon-Pierre Boucher7//! Contact: contact@spboucher.ai89use super::{choice, desc, num, preset};10use crate::core::{flush, DelayLine, OnePoleSmoother};11use crate::effect::Effect;12use crate::env::{Lfo, LfoShape};13use crate::filter::OnePole;14use sonata_ir::{EffectDesc, LatencySpec, Unit};1516const MAX_DELAY_SEC: f32 = 4.0;1718/// Stereo delay. The wet output is the delayed signal only; echoes are fed back through a19/// low-cut and a high-cut so repeats thin out and darken. In `ping_pong` mode the input is20/// summed to mono into the left line and the repeats alternate sides.21/// The first echo arrives exactly `time` after the input (whole samples; fractional times are22/// linearly interpolated). Changing `time` glides the read position (tape-style pitch bend).23pub struct Delay {24    sr: f32,25    lines: [DelayLine; 2],26    time: OnePoleSmoother,27    time_sec: f32,28    feedback: f32,29    ping_pong: bool,30    low_cut: f32,31    high_cut: f32,32    hp: [OnePole; 2],33    lp: [OnePole; 2],34}3536impl Delay {37    pub fn new() -> Delay {38        Delay {39            sr: 48_000.0,40            lines: [DelayLine::new(8), DelayLine::new(8)],41            time: OnePoleSmoother::new(12_000.0, 0.05, 48_000.0),42            time_sec: 0.25,43            feedback: 0.35,44            ping_pong: false,45            low_cut: 20.0,46            high_cut: 12_000.0,47            hp: [OnePole::new(20.0, 48_000.0); 2],48            lp: [OnePole::new(12_000.0, 48_000.0); 2],49        }50    }51    pub fn desc() -> EffectDesc {52        desc(53            "delay",54            "Delay",55            "time",56            "Stereo or ping-pong delay with filtered feedback. A musical duration given as `time` is converted at the tempo in effect at position 0.",57            vec![58                num("time", Unit::Seconds, 0.001, MAX_DELAY_SEC as f64, 0.25, "Delay time of each repeat."),59                num("feedback", Unit::Ratio, 0.0, 0.95, 0.35, "Fraction of the delayed signal fed back."),60                choice("mode", &["stereo", "ping_pong"], "stereo", "Independent channels, or repeats alternating left and right."),61                num("low_cut", Unit::Hertz, 20.0, 2000.0, 20.0, "High-pass in the feedback path."),62                num("high_cut", Unit::Hertz, 500.0, 20_000.0, 12_000.0, "Low-pass in the feedback path."),63            ],64            vec![65                preset("slap", "Single short echo.", &[("time", 0.09), ("feedback", 0.0)]),66                preset("echo", "Classic repeats.", &[("time", 0.33), ("feedback", 0.45), ("high_cut", 6000.0)]),67                preset("dub", "Long dark feedback.", &[("time", 0.5), ("feedback", 0.7), ("high_cut", 2500.0), ("low_cut", 200.0)]),68            ],69            LatencySpec::default(),70            0.3,71        )72    }73}7475impl Default for Delay {76    fn default() -> Self {77        Self::new()78    }79}8081impl Effect for Delay {82    fn prepare(&mut self, sample_rate: f32, _: usize) {83        self.sr = sample_rate;84        let max = (MAX_DELAY_SEC * sample_rate) as usize + 8;85        self.lines = [DelayLine::new(max), DelayLine::new(max)];86        self.time = OnePoleSmoother::new(self.time_sec * sample_rate, 0.05, sample_rate);87        self.hp = [OnePole::new(self.low_cut, sample_rate); 2];88        self.lp = [OnePole::new(self.high_cut, sample_rate); 2];89    }90    fn reset(&mut self) {91        self.lines[0].clear();92        self.lines[1].clear();93        self.time.snap(self.time_sec * self.sr);94        for f in self.hp.iter_mut().chain(self.lp.iter_mut()) {95            f.reset();96        }97    }98    fn set_param(&mut self, index: usize, value: f32) {99        match index {100            0 => {101                self.time_sec = value.clamp(0.001, MAX_DELAY_SEC);102                self.time.set_target(self.time_sec * self.sr);103            }104            1 => self.feedback = value.clamp(0.0, 0.95),105            3 => {106                self.low_cut = value;107                for f in &mut self.hp {108                    f.set(value, self.sr);109                }110            }111            4 => {112                self.high_cut = value;113                for f in &mut self.lp {114                    f.set(value, self.sr);115                }116            }117            _ => {}118        }119    }120    fn set_choice(&mut self, index: usize, choice: usize) {121        if index == 2 {122            self.ping_pong = choice == 1;123        }124    }125    fn process(&mut self, left: &mut [f32], right: &mut [f32]) {126        let max = (self.lines[0].capacity() - 2) as f32;127        for i in 0..left.len() {128            let d = self.time.tick().clamp(1.0, max);129            let (yl, yr) = (self.lines[0].read(d), self.lines[1].read(d));130            let fl = self.lp[0].lowpass(self.hp[0].highpass(yl)) * self.feedback;131            let fr = self.lp[1].lowpass(self.hp[1].highpass(yr)) * self.feedback;132            if self.ping_pong {133                self.lines[0].write(flush(0.5 * (left[i] + right[i]) + fr));134                self.lines[1].write(flush(yl));135            } else {136                self.lines[0].write(flush(left[i] + fl));137                self.lines[1].write(flush(right[i] + fr));138            }139            left[i] = yl;140            right[i] = yr;141        }142    }143    fn tail_seconds(&self) -> f32 {144        // Time for the feedback to fall 60 dB.145        if self.feedback < 1e-3 {146            self.time_sec147        } else {148            (self.time_sec * (-3.0 / self.feedback.log10())).min(60.0)149        }150    }151}152153/// Two-voice chorus per channel: modulated delay lines whose LFOs are spread in phase.154pub struct Chorus {155    sr: f32,156    lines: [DelayLine; 2],157    lfos: [[Lfo; 2]; 2],158    p: [f32; 4],159    fb: [f32; 2],160}161162impl Chorus {163    pub fn new() -> Chorus {164        let l = Lfo::new(48_000.0, 1);165        Chorus { sr: 48_000.0, lines: [DelayLine::new(8), DelayLine::new(8)], lfos: [[l; 2]; 2], p: [0.8, 0.003, 0.012, 0.0], fb: [0.0; 2] }166    }167    pub fn desc() -> EffectDesc {168        desc(169            "chorus",170            "Chorus",171            "modulation",172            "Two detuned voices per channel from slowly modulated delays; left and right move in quadrature for width.",173            vec![174                num("rate", Unit::Hertz, 0.01, 10.0, 0.8, "Modulation rate."),175                num("depth", Unit::Seconds, 0.0, 0.01, 0.003, "Peak deviation of the delay time."),176                num("delay", Unit::Seconds, 0.001, 0.05, 0.012, "Centre delay time."),177                num("feedback", Unit::Ratio, 0.0, 0.7, 0.0, "Fraction of the wet signal fed back."),178            ],179            vec![180                preset("lush", "Wide and slow.", &[("rate", 0.4), ("depth", 0.005), ("delay", 0.018)]),181                preset("shimmer", "Fast and shallow.", &[("rate", 2.5), ("depth", 0.001), ("delay", 0.008)]),182            ],183            LatencySpec::default(),184            0.5,185        )186    }187    fn configure(&mut self) {188        for (c, ch) in self.lfos.iter_mut().enumerate() {189            for (v, l) in ch.iter_mut().enumerate() {190                l.shape = LfoShape::Sine;191                l.set_rate(self.p[0] * if v == 0 { 1.0 } else { 1.31 });192            }193            let _ = c;194        }195    }196}197198impl Default for Chorus {199    fn default() -> Self {200        Self::new()201    }202}203204impl Effect for Chorus {205    fn prepare(&mut self, sample_rate: f32, _: usize) {206        self.sr = sample_rate;207        let max = (0.07 * sample_rate) as usize + 8;208        self.lines = [DelayLine::new(max), DelayLine::new(max)];209        self.lfos = [[Lfo::new(sample_rate, 1), Lfo::new(sample_rate, 2)], [Lfo::new(sample_rate, 3), Lfo::new(sample_rate, 4)]];210        self.reset();211    }212    fn reset(&mut self) {213        self.lines[0].clear();214        self.lines[1].clear();215        self.fb = [0.0; 2];216        for (c, ch) in self.lfos.iter_mut().enumerate() {217            for (v, l) in ch.iter_mut().enumerate() {218                l.set_phase(c as f32 * 0.25 + v as f32 * 0.5);219            }220        }221        self.configure();222    }223    fn set_param(&mut self, index: usize, value: f32) {224        if let Some(p) = self.p.get_mut(index) {225            *p = value;226        }227        if index == 0 {228            self.configure();229        }230    }231    fn process(&mut self, left: &mut [f32], right: &mut [f32]) {232        let (depth, centre, fb) = (self.p[1] * self.sr, self.p[2] * self.sr, self.p[3]);233        let depth = depth.min(centre - 2.0).max(0.0);234        for i in 0..left.len() {235            let input = [left[i], right[i]];236            let mut out = [0.0f32; 2];237            for c in 0..2 {238                let mut wet = 0.0;239                for v in 0..2 {240                    let d = centre + depth * self.lfos[c][v].tick();241                    wet += self.lines[c].read_cubic(d.max(2.0));242                }243                wet *= 0.5;244                self.lines[c].write(flush(input[c] + self.fb[c] * fb));245                self.fb[c] = wet;246                out[c] = wet;247            }248            left[i] = out[0];249            right[i] = out[1];250        }251    }252}253254/// Flanger: a very short modulated delay with feedback; mixing it with the dry signal (mix 0.5)255/// produces the moving comb filter.256pub struct Flanger {257    sr: f32,258    lines: [DelayLine; 2],259    lfos: [Lfo; 2],260    p: [f32; 5],261    fb: [f32; 2],262}263264impl Flanger {265    pub fn new() -> Flanger {266        Flanger {267            sr: 48_000.0,268            lines: [DelayLine::new(8), DelayLine::new(8)],269            lfos: [Lfo::new(48_000.0, 1); 2],270            p: [0.25, 0.002, 0.001, 0.5, 90.0],271            fb: [0.0; 2],272        }273    }274    pub fn desc() -> EffectDesc {275        desc(276            "flanger",277            "Flanger",278            "modulation",279            "Swept comb filter from a short modulated delay with feedback (negative feedback inverts the comb).",280            vec![281                num("rate", Unit::Hertz, 0.01, 10.0, 0.25, "Sweep rate."),282                num("depth", Unit::Seconds, 0.0, 0.01, 0.002, "Sweep range of the delay time."),283                num("delay", Unit::Seconds, 0.0001, 0.01, 0.001, "Shortest delay time."),284                num("feedback", Unit::Scalar, -0.95, 0.95, 0.5, "Signed feedback amount."),285                num("stereo_phase", Unit::Degrees, 0.0, 180.0, 90.0, "Phase offset of the right channel's sweep."),286            ],287            vec![288                preset("jet", "Deep resonant sweep.", &[("rate", 0.1), ("depth", 0.004), ("feedback", 0.8)]),289                preset("through_zero_like", "Shallow, inverted.", &[("depth", 0.001), ("feedback", -0.6)]),290            ],291            LatencySpec::default(),292            0.5,293        )294    }295}296297impl Default for Flanger {298    fn default() -> Self {299        Self::new()300    }301}302303impl Effect for Flanger {304    fn prepare(&mut self, sample_rate: f32, _: usize) {305        self.sr = sample_rate;306        let max = (0.025 * sample_rate) as usize + 8;307        self.lines = [DelayLine::new(max), DelayLine::new(max)];308        self.lfos = [Lfo::new(sample_rate, 1), Lfo::new(sample_rate, 2)];309        self.reset();310    }311    fn reset(&mut self) {312        self.lines[0].clear();313        self.lines[1].clear();314        self.fb = [0.0; 2];315        for (c, l) in self.lfos.iter_mut().enumerate() {316            l.shape = LfoShape::Triangle;317            l.set_rate(self.p[0]);318            l.set_phase(c as f32 * self.p[4] / 360.0);319        }320    }321    fn set_param(&mut self, index: usize, value: f32) {322        if let Some(p) = self.p.get_mut(index) {323            *p = value;324        }325        if index == 0 {326            for l in &mut self.lfos {327                l.set_rate(value);328            }329        }330    }331    fn process(&mut self, left: &mut [f32], right: &mut [f32]) {332        let (depth, base, fb) = (self.p[1] * self.sr, self.p[2] * self.sr, self.p[3].clamp(-0.95, 0.95));333        for i in 0..left.len() {334            let input = [left[i], right[i]];335            let mut out = [0.0f32; 2];336            for c in 0..2 {337                let d = (base + depth * (0.5 + 0.5 * self.lfos[c].tick())).max(2.0);338                let wet = self.lines[c].read_cubic(d);339                self.lines[c].write(flush(input[c] + self.fb[c] * fb));340                self.fb[c] = wet;341                out[c] = wet;342            }343            left[i] = out[0];344            right[i] = out[1];345        }346    }347}348349const MAX_STAGES: usize = 12;350351/// Phaser: a chain of first-order all-pass filters whose corner sweeps around `centre`;352/// mixed with the dry signal it produces moving notches (half as many as stages).353pub struct Phaser {354    sr: f32,355    lfos: [Lfo; 2],356    p: [f32; 6],357    z: [[f32; MAX_STAGES]; 2],358    fb: [f32; 2],359}360361impl Phaser {362    pub fn new() -> Phaser {363        Phaser { sr: 48_000.0, lfos: [Lfo::new(48_000.0, 1); 2], p: [0.4, 0.7, 800.0, 0.4, 6.0, 90.0], z: [[0.0; MAX_STAGES]; 2], fb: [0.0; 2] }364    }365    pub fn desc() -> EffectDesc {366        desc(367            "phaser",368            "Phaser",369            "modulation",370            "Swept all-pass chain with feedback. At depth 1 the corner moves two octaves either side of the centre.",371            vec![372                num("rate", Unit::Hertz, 0.01, 10.0, 0.4, "Sweep rate."),373                num("depth", Unit::Ratio, 0.0, 1.0, 0.7, "Sweep range (1 = +/- two octaves)."),374                num("centre", Unit::Hertz, 100.0, 5000.0, 800.0, "Centre frequency of the sweep."),375                num("feedback", Unit::Scalar, -0.9, 0.9, 0.4, "Signed feedback around the chain."),376                num("stages", Unit::Count, 2.0, MAX_STAGES as f64, 6.0, "Number of all-pass stages (even values; two stages per notch)."),377                num("stereo_phase", Unit::Degrees, 0.0, 180.0, 90.0, "Phase offset of the right channel's sweep."),378            ],379            vec![380                preset("slow_swirl", "Gentle movement.", &[("rate", 0.15), ("depth", 0.8), ("stages", 4.0)]),381                preset("vibe", "Faster and resonant.", &[("rate", 1.6), ("feedback", 0.7), ("stages", 8.0)]),382            ],383            LatencySpec::default(),384            0.5,385        )386    }387}388389impl Default for Phaser {390    fn default() -> Self {391        Self::new()392    }393}394395impl Effect for Phaser {396    fn prepare(&mut self, sample_rate: f32, _: usize) {397        self.sr = sample_rate;398        self.lfos = [Lfo::new(sample_rate, 1), Lfo::new(sample_rate, 2)];399        self.reset();400    }401    fn reset(&mut self) {402        self.z = [[0.0; MAX_STAGES]; 2];403        self.fb = [0.0; 2];404        for (c, l) in self.lfos.iter_mut().enumerate() {405            l.shape = LfoShape::Sine;406            l.set_rate(self.p[0]);407            l.set_phase(c as f32 * self.p[5] / 360.0);408        }409    }410    fn set_param(&mut self, index: usize, value: f32) {411        if let Some(p) = self.p.get_mut(index) {412            *p = value;413        }414        if index == 0 {415            for l in &mut self.lfos {416                l.set_rate(value);417            }418        }419    }420    fn process(&mut self, left: &mut [f32], right: &mut [f32]) {421        let stages = ((self.p[4] as usize).clamp(2, MAX_STAGES) / 2) * 2;422        let (depth, centre, fb) = (self.p[1], self.p[2], self.p[3].clamp(-0.9, 0.9));423        let mut a = [0.0f32; 2];424        for i in 0..left.len() {425            let input = [left[i], right[i]];426            let mut out = [0.0f32; 2];427            for c in 0..2 {428                let lfo = self.lfos[c].tick();429                // All-pass coefficient refreshed every 4 samples.430                if i.is_multiple_of(4) || i == 0 {431                    let f = (centre * (2.0 * depth * lfo).exp2()).clamp(20.0, 0.45 * self.sr);432                    let t = (std::f32::consts::PI * f / self.sr).tan();433                    a[c] = (t - 1.0) / (t + 1.0);434                }435                let mut x = input[c] + self.fb[c] * fb;436                for z in self.z[c].iter_mut().take(stages) {437                    let y = a[c] * x + *z;438                    *z = flush(x - a[c] * y);439                    x = y;440                }441                self.fb[c] = x;442                out[c] = x;443            }444            left[i] = out[0];445            right[i] = out[1];446        }447    }448}449
Files main
Menu

Theme