Skip to main content

qualia_core_db/audio/dsp/
oscillator.rs

1//! Oscillator — basic waveform synthesis.
2//!
3//! Generates sine, square, sawtooth, and triangle waveforms at a given
4//! frequency and sample rate. Phase-continuous for real-time modulation.
5
6/// Oscillator waveform type.
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub enum Waveform {
9    /// Pure sinusoid.
10    Sine,
11    /// 50% duty-cycle square wave.
12    Square,
13    /// Rising sawtooth (-1 → +1 per cycle).
14    Sawtooth,
15    /// Triangle wave.
16    Triangle,
17}
18
19/// An oscillator with phase accumulation.
20#[derive(Debug, Clone)]
21pub struct Oscillator {
22    /// Waveform shape produced by `tick`.
23    pub waveform: Waveform,
24    /// Frequency in Hz.
25    pub frequency: f64,
26    /// Sample rate the phase increment is computed against.
27    pub sample_rate: f64,
28    /// Output amplitude multiplier (typically 0–1).
29    pub gain: f64,
30    phase: f64,
31}
32
33impl Oscillator {
34    /// Create an oscillator at unity gain, phase 0.
35    pub fn new(waveform: Waveform, frequency: f64, sample_rate: f64) -> Self {
36        Self {
37            waveform,
38            frequency,
39            sample_rate,
40            gain: 1.0,
41            phase: 0.0,
42        }
43    }
44
45    /// Advance one sample and return the output value in [-1.0, 1.0] * gain.
46    pub fn tick(&mut self) -> f64 {
47        let phase_increment = self.frequency / self.sample_rate;
48        let value = match self.waveform {
49            Waveform::Sine => (self.phase * 2.0 * std::f64::consts::PI).sin(),
50            Waveform::Square => {
51                if self.phase < 0.5 {
52                    1.0
53                } else {
54                    -1.0
55                }
56            }
57            Waveform::Sawtooth => 2.0 * self.phase - 1.0,
58            Waveform::Triangle => {
59                if self.phase < 0.5 {
60                    4.0 * self.phase - 1.0
61                } else {
62                    3.0 - 4.0 * self.phase
63                }
64            }
65        };
66        self.phase += phase_increment;
67        if self.phase >= 1.0 {
68            self.phase -= 1.0;
69        }
70        value * self.gain
71    }
72
73    /// Generate `n` samples into `out`.
74    pub fn render(&mut self, out: &mut [f64]) {
75        for s in out.iter_mut() {
76            *s = self.tick();
77        }
78    }
79
80    /// Reset phase to zero.
81    pub fn reset(&mut self) {
82        self.phase = 0.0;
83    }
84
85    /// Set frequency (Hz).
86    pub fn set_frequency(&mut self, freq: f64) {
87        self.frequency = freq;
88    }
89
90    /// Set gain (0.0 to 1.0 typically).
91    pub fn set_gain(&mut self, gain: f64) {
92        self.gain = gain;
93    }
94}
95
96#[cfg(test)]
97mod tests {
98    use super::*;
99
100    #[test]
101    fn sine_oscillator_range() {
102        let mut osc = Oscillator::new(Waveform::Sine, 440.0, 44100.0);
103        for _ in 0..1000 {
104            let v = osc.tick();
105            assert!(v.abs() <= 1.0 + 1e-10);
106        }
107    }
108
109    #[test]
110    fn square_oscillator_values() {
111        let mut osc = Oscillator::new(Waveform::Square, 1.0, 8.0);
112        let mut samples = vec![0.0; 8];
113        osc.render(&mut samples);
114        // First half should be +1, second half -1.
115        assert!(samples[0] > 0.0);
116        assert!(samples[4] < 0.0);
117    }
118
119    #[test]
120    fn sawtooth_oscillator_range() {
121        let mut osc = Oscillator::new(Waveform::Sawtooth, 100.0, 44100.0);
122        for _ in 0..1000 {
123            let v = osc.tick();
124            assert!(v.abs() <= 1.0 + 1e-10);
125        }
126    }
127
128    #[test]
129    fn triangle_oscillator_range() {
130        let mut osc = Oscillator::new(Waveform::Triangle, 100.0, 44100.0);
131        for _ in 0..1000 {
132            let v = osc.tick();
133            assert!(v.abs() <= 1.0 + 1e-10);
134        }
135    }
136
137    #[test]
138    fn oscillator_reset() {
139        let mut osc = Oscillator::new(Waveform::Sine, 440.0, 44100.0);
140        for _ in 0..100 {
141            osc.tick();
142        }
143        osc.reset();
144        // After reset, first sample of sine should be ~0.
145        let v = osc.tick();
146        assert!(v.abs() < 1e-10);
147    }
148
149    #[test]
150    fn oscillator_gain() {
151        let mut osc = Oscillator::new(Waveform::Sine, 440.0, 44100.0);
152        osc.set_gain(0.5);
153        let _ = osc.tick();
154        // At phase 0, sine is 0, so check a later sample.
155        let v2 = osc.tick();
156        assert!(v2.abs() <= 0.5 + 1e-10);
157    }
158
159    #[test]
160    fn oscillator_frequency_change() {
161        let mut osc = Oscillator::new(Waveform::Sine, 100.0, 44100.0);
162        osc.set_frequency(200.0);
163        assert_eq!(osc.frequency, 200.0);
164    }
165}