Skip to main content

qualia_core_db/audio/dsp/
effects.rs

1//! Audio effects — delay, reverb, compressor, EQ.
2//!
3//! Simple but real implementations of common DAW effects.
4
5/// Simple delay line with feedback.
6#[derive(Debug, Clone)]
7pub struct Delay {
8    buffer: Vec<f64>,
9    write_pos: usize,
10    pub feedback: f64, // [0, 1)
11    pub mix: f64,      // wet/dry mix [0, 1]
12}
13
14impl Delay {
15    /// Create a delay line of `max_samples`; `feedback` is clamped to
16    /// `[0, 0.999]` and `mix` to `[0, 1]`.
17    pub fn new(max_samples: usize, feedback: f64, mix: f64) -> Self {
18        Self {
19            buffer: vec![0.0; max_samples.max(1)],
20            write_pos: 0,
21            feedback: feedback.clamp(0.0, 0.999),
22            mix: mix.clamp(0.0, 1.0),
23        }
24    }
25
26    /// Set delay time in samples.
27    pub fn set_delay_samples(&mut self, samples: usize) {
28        // The buffer size is fixed at construction; we just adjust the
29        // read offset by ensuring the buffer is large enough.
30        if samples > self.buffer.len() {
31            self.buffer.resize(samples, 0.0);
32        }
33    }
34
35    /// Advance one sample: reads the delayed value, writes `input + delayed
36    /// × feedback`, and returns `input + delayed × mix`.
37    pub fn tick(&mut self, input: f64) -> f64 {
38        let delayed = self.buffer[self.write_pos];
39        let output = input + delayed * self.mix;
40        self.buffer[self.write_pos] = input + delayed * self.feedback;
41        self.write_pos = (self.write_pos + 1) % self.buffer.len();
42        output
43    }
44
45    /// Apply the delay to `input`, writing up to `output.len()` samples.
46    pub fn process(&mut self, input: &[f64], output: &mut [f64]) {
47        for (i, &s) in input.iter().enumerate() {
48            if i < output.len() {
49                output[i] = self.tick(s);
50            }
51        }
52    }
53
54    /// Clear the delay line and rewind the write cursor.
55    pub fn reset(&mut self) {
56        self.buffer.fill(0.0);
57        self.write_pos = 0;
58    }
59}
60
61/// Simple reverb using a feedback delay network.
62#[derive(Debug, Clone)]
63pub struct Reverb {
64    pub room_size: f64, // [0, 1]
65    pub damping: f64,   // [0, 1]
66    pub mix: f64,       // wet/dry [0, 1]
67    delays: Vec<Delay>,
68}
69
70impl Reverb {
71    /// Build the 4-delay feedback network (prime-ms lengths for a dense
72    /// tail); `room_size`, `damping`, and `mix` are clamped to `[0, 1]`.
73    pub fn new(sample_rate: f64, room_size: f64, damping: f64, mix: f64) -> Self {
74        // Four parallel delay lines with prime-number lengths for a dense tail.
75        let prime_ms = [29.0, 37.0, 41.0, 43.0];
76        let delays: Vec<Delay> = prime_ms
77            .iter()
78            .map(|&ms| {
79                let samples = (ms * sample_rate / 1000.0) as usize;
80                Delay::new(samples, 0.6 + room_size * 0.3, 0.25)
81            })
82            .collect();
83        Self {
84            room_size: room_size.clamp(0.0, 1.0),
85            damping: damping.clamp(0.0, 1.0),
86            mix: mix.clamp(0.0, 1.0),
87            delays,
88        }
89    }
90
91    /// Advance one sample through the delay network and apply the damping
92    /// low-pass; returns the wet/dry blend.
93    pub fn tick(&mut self, input: f64) -> f64 {
94        let mut wet = 0.0;
95        for d in &mut self.delays {
96            wet += d.tick(input);
97        }
98        wet /= self.delays.len() as f64;
99        // Apply damping (simple low-pass via averaging).
100        let damped = wet * (1.0 - self.damping * 0.5);
101        input * (1.0 - self.mix) + damped * self.mix
102    }
103
104    /// Apply the reverb to `input`, writing up to `output.len()` samples.
105    pub fn process(&mut self, input: &[f64], output: &mut [f64]) {
106        for (i, &s) in input.iter().enumerate() {
107            if i < output.len() {
108                output[i] = self.tick(s);
109            }
110        }
111    }
112
113    /// Clear all internal delay lines.
114    pub fn reset(&mut self) {
115        for d in &mut self.delays {
116            d.reset();
117        }
118    }
119}
120
121/// Simple compressor with threshold, ratio, attack, release.
122#[derive(Debug, Clone)]
123pub struct Compressor {
124    pub threshold: f64, // dB
125    pub ratio: f64,     // >= 1.0
126    pub attack: f64,    // seconds
127    pub release: f64,   // seconds
128    pub sample_rate: f64,
129    envelope: f64,
130    attack_coef: f64,
131    release_coef: f64,
132}
133
134impl Compressor {
135    /// `threshold` in dB, `ratio` clamped to ≥ 1, `attack`/`release` in
136    /// seconds; attack/release smoothing coefficients are derived from
137    /// `sample_rate`.
138    pub fn new(threshold: f64, ratio: f64, attack: f64, release: f64, sample_rate: f64) -> Self {
139        let attack_coef = (-1.0 / (attack * sample_rate)).exp();
140        let release_coef = (-1.0 / (release * sample_rate)).exp();
141        Self {
142            threshold,
143            ratio: ratio.max(1.0),
144            attack,
145            release,
146            sample_rate,
147            envelope: 0.0,
148            attack_coef,
149            release_coef,
150        }
151    }
152
153    /// Advance one sample: measures level in dB, applies attack/release
154    /// envelope smoothing to the gain-reduction target, and returns the
155    /// compressed sample.
156    pub fn tick(&mut self, input: f64) -> f64 {
157        // Convert to dB.
158        let abs_input = input.abs();
159        let input_db = if abs_input > 1e-10 {
160            20.0 * abs_input.log10()
161        } else {
162            -200.0
163        };
164
165        // Gain reduction.
166        let over_threshold = input_db - self.threshold;
167        let target_gain = if over_threshold > 0.0 {
168            -over_threshold * (1.0 - 1.0 / self.ratio)
169        } else {
170            0.0
171        };
172
173        // Smooth envelope.
174        let coef = if target_gain < self.envelope {
175            self.attack_coef
176        } else {
177            self.release_coef
178        };
179        self.envelope = coef * self.envelope + (1.0 - coef) * target_gain;
180
181        // Apply gain reduction.
182        let gain_linear = 10.0_f64.powf(self.envelope / 20.0);
183        input * gain_linear
184    }
185
186    /// Apply the compressor to `input`, writing up to `output.len()` samples.
187    pub fn process(&mut self, input: &[f64], output: &mut [f64]) {
188        for (i, &s) in input.iter().enumerate() {
189            if i < output.len() {
190                output[i] = self.tick(s);
191            }
192        }
193    }
194
195    /// Reset the gain-reduction envelope to zero.
196    pub fn reset(&mut self) {
197        self.envelope = 0.0;
198    }
199}
200
201use super::filter::{BiquadFilter, FilterType};
202
203/// Simple 3-band EQ (low, mid, high) using biquad filters.
204#[derive(Debug)]
205pub struct Equalizer {
206    low: BiquadFilter,
207    mid: BiquadFilter,
208    high: BiquadFilter,
209    pub low_gain: f64,  // dB
210    pub mid_gain: f64,  // dB
211    pub high_gain: f64, // dB
212}
213
214impl Equalizer {
215    /// Build the three biquads at 200 Hz (low-pass), 1 kHz (band-pass), and
216    /// 3 kHz (high-pass); all band gains start at 0 dB.
217    pub fn new(sample_rate: f64) -> Self {
218        Self {
219            low: BiquadFilter::new(FilterType::LowPass, 200.0, 0.707, sample_rate),
220            mid: BiquadFilter::new(FilterType::BandPass, 1000.0, 0.707, sample_rate),
221            high: BiquadFilter::new(FilterType::HighPass, 3000.0, 0.707, sample_rate),
222            low_gain: 0.0,
223            mid_gain: 0.0,
224            high_gain: 0.0,
225        }
226    }
227
228    /// Set per-band gains in dB (applied multiplicatively to each band's
229    /// output).
230    pub fn set_band_gains(&mut self, low_db: f64, mid_db: f64, high_db: f64) {
231        self.low_gain = low_db;
232        self.mid_gain = mid_db;
233        self.high_gain = high_db;
234    }
235
236    /// Advance one sample through all three bands and sum the
237    /// gain-weighted outputs.
238    pub fn tick(&mut self, input: f64) -> f64 {
239        let low = self.low.tick(input) * 10.0_f64.powf(self.low_gain / 20.0);
240        let mid = self.mid.tick(input) * 10.0_f64.powf(self.mid_gain / 20.0);
241        let high = self.high.tick(input) * 10.0_f64.powf(self.high_gain / 20.0);
242        low + mid + high
243    }
244
245    /// Apply the EQ to `input`, writing up to `output.len()` samples.
246    pub fn process(&mut self, input: &[f64], output: &mut [f64]) {
247        for (i, &s) in input.iter().enumerate() {
248            if i < output.len() {
249                output[i] = self.tick(s);
250            }
251        }
252    }
253}
254
255#[cfg(test)]
256mod tests {
257    use super::*;
258
259    #[test]
260    fn delay_basic() {
261        let mut delay = Delay::new(100, 0.3, 0.5);
262        let input = vec![1.0, 0.0, 0.0, 0.0];
263        let mut output = vec![0.0; 4];
264        delay.process(&input, &mut output);
265        // First sample should be mostly input (dry).
266        assert!(output[0] > 0.9);
267    }
268
269    #[test]
270    fn delay_feedback_decays() {
271        let mut delay = Delay::new(10, 0.5, 0.5);
272        delay.tick(1.0);
273        for _ in 0..9 {
274            delay.tick(0.0);
275        }
276        // After one delay period, the echo should be present but smaller than original.
277        let echo = delay.tick(0.0);
278        assert!(echo > 0.0, "echo should be non-zero: {echo}");
279        assert!(echo < 1.0, "echo should be smaller than original: {echo}");
280    }
281
282    #[test]
283    fn reverb_adds_tail() {
284        let mut reverb = Reverb::new(44100.0, 0.5, 0.3, 0.5);
285        let mut input = vec![0.0; 3000];
286        input[0] = 1.0;
287        let mut output = vec![0.0; 3000];
288        reverb.process(&input, &mut output);
289        // The reverb should produce non-zero output in the tail (after the impulse).
290        // Delay lines are ~29-43ms = ~1277-1894 samples at 44.1kHz.
291        let has_tail = output[100..].iter().any(|x| x.abs() > 1e-10);
292        assert!(has_tail, "reverb should produce a tail after impulse");
293    }
294
295    #[test]
296    fn compressor_reduces_loud() {
297        let mut comp = Compressor::new(-10.0, 4.0, 0.001, 0.1, 44100.0);
298        let loud = 0.9; // ~ -0.9 dB, well above -10 threshold
299        let compressed = comp.tick(loud);
300        assert!(compressed < loud, "compressor should reduce loud signal");
301    }
302
303    #[test]
304    fn compressor_passes_quiet() {
305        let mut comp = Compressor::new(-10.0, 4.0, 0.001, 0.1, 44100.0);
306        let quiet = 0.01; // ~ -40 dB, below threshold
307        let compressed = comp.tick(quiet);
308        assert!(
309            (compressed - quiet).abs() < 0.01,
310            "compressor should pass quiet signal"
311        );
312    }
313
314    #[test]
315    fn eq_passes_signal() {
316        let mut eq = Equalizer::new(44100.0);
317        eq.set_band_gains(0.0, 0.0, 0.0);
318        let input = vec![0.5; 100];
319        let mut output = vec![0.0; 100];
320        eq.process(&input, &mut output);
321        // With 0 dB gains, output should be non-zero.
322        assert!(output[50].abs() > 0.0);
323    }
324
325    #[test]
326    fn delay_reset() {
327        let mut delay = Delay::new(100, 0.5, 0.5);
328        for _ in 0..50 {
329            delay.tick(0.5);
330        }
331        delay.reset();
332        let v = delay.tick(0.0);
333        assert!(v.abs() < 1e-10);
334    }
335
336    #[test]
337    fn compressor_reset() {
338        let mut comp = Compressor::new(-10.0, 4.0, 0.001, 0.1, 44100.0);
339        for _ in 0..100 {
340            comp.tick(0.9);
341        }
342        comp.reset();
343        assert_eq!(comp.envelope, 0.0);
344    }
345}