Skip to main content

qualia_core_db/audio/dsp/
lfo.rs

1//! LFO — low-frequency oscillator for modulation.
2//!
3//! Wraps an oscillator at sub-audio frequencies (typically 0.1–20 Hz) and
4//! provides a smoothed modulation output.
5
6use super::oscillator::{Oscillator, Waveform};
7
8/// LFO configuration.
9#[derive(Debug, Clone)]
10pub struct Lfo {
11    osc: Oscillator,
12    pub depth: f64, // Modulation depth [0, 1]
13}
14
15impl Lfo {
16    /// Create an LFO; `depth` clamped to `[0, 1]`, `frequency` in Hz
17    /// (typically sub-audio, 0.1–20 Hz).
18    pub fn new(waveform: Waveform, frequency: f64, sample_rate: f64, depth: f64) -> Self {
19        Self {
20            osc: Oscillator::new(waveform, frequency, sample_rate),
21            depth: depth.clamp(0.0, 1.0),
22        }
23    }
24
25    /// Tick the LFO and return a modulation value in [-depth, +depth].
26    pub fn tick(&mut self) -> f64 {
27        self.osc.tick() * self.depth
28    }
29
30    /// Render `n` samples.
31    pub fn render(&mut self, out: &mut [f64]) {
32        for s in out.iter_mut() {
33            *s = self.tick();
34        }
35    }
36
37    /// Set the modulation frequency in Hz.
38    pub fn set_frequency(&mut self, freq: f64) {
39        self.osc.set_frequency(freq);
40    }
41
42    /// Set the modulation depth, clamped to `[0, 1]`.
43    pub fn set_depth(&mut self, depth: f64) {
44        self.depth = depth.clamp(0.0, 1.0);
45    }
46
47    /// Reset the oscillator phase to zero.
48    pub fn reset(&mut self) {
49        self.osc.reset();
50    }
51}
52
53#[cfg(test)]
54mod tests {
55    use super::*;
56
57    #[test]
58    fn lfo_output_range() {
59        let mut lfo = Lfo::new(Waveform::Sine, 1.0, 44100.0, 0.5);
60        for _ in 0..1000 {
61            let v = lfo.tick();
62            assert!(v.abs() <= 0.5 + 1e-10);
63        }
64    }
65
66    #[test]
67    fn lfo_depth_clamped() {
68        let lfo = Lfo::new(Waveform::Sine, 1.0, 44100.0, 2.0);
69        assert_eq!(lfo.depth, 1.0);
70    }
71
72    #[test]
73    fn lfo_frequency_change() {
74        let mut lfo = Lfo::new(Waveform::Sine, 1.0, 44100.0, 0.5);
75        lfo.set_frequency(5.0);
76        assert_eq!(lfo.osc.frequency, 5.0);
77    }
78}