Skip to main content

qualia_audio/midi/synth/
oscillator_voice.rs

1//! Single oscillator voice — waveform × ADSR × velocity gain, zero-alloc.
2//!
3//! One naive (non-band-limited) oscillator running at a set frequency, gated by an
4//! [`AdsrEnvelope`] and scaled by a per-note velocity gain. `render_sample()` produces
5//! one output sample and advances all internal state. No heap, no locks, no FS.
6
7use super::adsr::AdsrEnvelope;
8
9/// Selectable oscillator waveform.
10#[repr(u8)]
11#[derive(Clone, Copy, PartialEq, Eq, Debug)]
12pub enum Waveform {
13    Sine = 0,
14    Saw = 1,
15    Square = 2,
16    Triangle = 3,
17}
18
19/// A single monophonic voice: oscillator + envelope + velocity gain.
20///
21/// Frequency is supplied directly to `note_on` (Hz), so a tuning table can drive it;
22/// callers wanting equal temperament compute the frequency upstream.
23#[derive(Clone, Copy, Debug)]
24pub struct OscillatorVoice {
25    sample_rate: f32,
26    waveform: Waveform,
27    /// Normalized phase in `[0.0, 1.0)`.
28    phase: f32,
29    /// Phase increment per sample = freq / sample_rate.
30    phase_inc: f32,
31    /// Velocity-derived gain in `0.0..=1.0`.
32    velocity_gain: f32,
33    env: AdsrEnvelope,
34}
35
36impl OscillatorVoice {
37    /// Build an idle voice with the given waveform and envelope shape.
38    pub fn new(sample_rate: f32, waveform: Waveform, env: AdsrEnvelope) -> Self {
39        let sr = if sample_rate.is_finite() && sample_rate > 0.0 {
40            sample_rate
41        } else {
42            1.0
43        };
44        Self {
45            sample_rate: sr,
46            waveform,
47            phase: 0.0,
48            phase_inc: 0.0,
49            velocity_gain: 0.0,
50            env,
51        }
52    }
53
54    /// Start a note at an explicit frequency (Hz) and MIDI velocity (`0..=127`).
55    pub fn note_on(&mut self, freq_hz: f32, velocity: u8) {
56        let f = if freq_hz.is_finite() && freq_hz > 0.0 {
57            freq_hz
58        } else {
59            0.0
60        };
61        self.phase = 0.0;
62        self.phase_inc = f / self.sample_rate;
63        self.velocity_gain = (velocity as f32 / 127.0).clamp(0.0, 1.0);
64        self.env.note_on();
65    }
66
67    /// Release the note (enters the envelope's release stage).
68    pub fn note_off(&mut self) {
69        self.env.note_off();
70    }
71
72    /// `true` while the voice still contributes signal (attack..release).
73    #[inline]
74    pub fn is_active(&self) -> bool {
75        self.env.is_active()
76    }
77
78    /// Velocity gain currently applied (`0..=1`).
79    #[inline]
80    pub fn velocity_gain(&self) -> f32 {
81        self.velocity_gain
82    }
83
84    /// Render one sample and advance phase + envelope.
85    pub fn render_sample(&mut self) -> f32 {
86        let p = self.phase;
87        let osc = match self.waveform {
88            Waveform::Sine => (core::f32::consts::TAU * p).sin(),
89            Waveform::Saw => 2.0 * p - 1.0,
90            Waveform::Square => {
91                if p < 0.5 {
92                    1.0
93                } else {
94                    -1.0
95                }
96            }
97            // Peak +1 at p=0.5, -1 at the edges.
98            Waveform::Triangle => 1.0 - 4.0 * (p - 0.5).abs(),
99        };
100        self.phase += self.phase_inc;
101        if self.phase >= 1.0 {
102            self.phase -= 1.0;
103            // Guard against freq >= sample_rate (step > 1.0).
104            if self.phase >= 1.0 {
105                self.phase = self.phase.fract();
106            }
107        }
108        let gain = self.env.process_sample();
109        osc * gain * self.velocity_gain
110    }
111}
112
113#[cfg(test)]
114mod tests {
115    use super::*;
116
117    const SR: f32 = 48_000.0;
118
119    fn fast_env() -> AdsrEnvelope {
120        // Near-instant attack, full sustain so gain settles at ~1.0 quickly.
121        AdsrEnvelope::new(SR, 0.001, 0.0, 1.0, 0.010)
122    }
123
124    #[test]
125    fn sine_dominant_frequency_is_440hz() {
126        let mut v = OscillatorVoice::new(SR, Waveform::Sine, fast_env());
127        v.note_on(440.0, 127);
128        // Render 1.0 s → 440 cycles → 880 zero crossings.
129        let n = SR as usize;
130        let mut buf = vec![0.0f32; n];
131        for s in buf.iter_mut() {
132            *s = v.render_sample();
133        }
134        // Count sign changes (ignoring exact zeros).
135        let mut crossings = 0usize;
136        let mut prev_sign = 0i8;
137        for &x in &buf {
138            let sign = if x > 0.0 {
139                1
140            } else if x < 0.0 {
141                -1
142            } else {
143                0
144            };
145            if sign != 0 {
146                if prev_sign != 0 && sign != prev_sign {
147                    crossings += 1;
148                }
149                prev_sign = sign;
150            }
151        }
152        // 440 Hz over 1 s → ~880 zero crossings.
153        assert!(
154            (crossings as i64 - 880).abs() <= 4,
155            "expected ~880 zero crossings for 440 Hz, got {crossings}"
156        );
157        // Amplitude bounded by velocity gain (1.0 here).
158        let max_abs = buf.iter().fold(0.0f32, |m, &x| m.max(x.abs()));
159        assert!(
160            max_abs <= 1.0 + 1e-4,
161            "amplitude exceeds velocity bound: {max_abs}"
162        );
163    }
164
165    #[test]
166    fn amplitude_scales_with_velocity() {
167        let mut v = OscillatorVoice::new(SR, Waveform::Saw, fast_env());
168        v.note_on(220.0, 64);
169        let mut max_abs = 0.0f32;
170        for _ in 0..SR as usize {
171            max_abs = max_abs.max(v.render_sample().abs());
172        }
173        let bound = 64.0 / 127.0;
174        assert!(
175            max_abs <= bound + 1e-3,
176            "saw amplitude {max_abs} exceeds velocity bound {bound}"
177        );
178        assert!(
179            max_abs > bound - 0.05,
180            "saw should approach velocity bound, got {max_abs}"
181        );
182    }
183
184    #[test]
185    fn inactive_before_note_on() {
186        let v = OscillatorVoice::new(SR, Waveform::Square, fast_env());
187        assert!(!v.is_active());
188    }
189}