qualia_core_db/audio/dsp/
lfo.rs1use super::oscillator::{Oscillator, Waveform};
7
8#[derive(Debug, Clone)]
10pub struct Lfo {
11 osc: Oscillator,
12 pub depth: f64, }
14
15impl Lfo {
16 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 pub fn tick(&mut self) -> f64 {
27 self.osc.tick() * self.depth
28 }
29
30 pub fn render(&mut self, out: &mut [f64]) {
32 for s in out.iter_mut() {
33 *s = self.tick();
34 }
35 }
36
37 pub fn set_frequency(&mut self, freq: f64) {
39 self.osc.set_frequency(freq);
40 }
41
42 pub fn set_depth(&mut self, depth: f64) {
44 self.depth = depth.clamp(0.0, 1.0);
45 }
46
47 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}