Skip to main content

qualia_audio/midi/synth/
voice_allocator.rs

1//! Fixed-capacity polyphonic voice pool — zero-alloc, no locks, no FS.
2//!
3//! [`VoiceAllocator`] owns a `[Voice; N]` array on the stack/inline. `note_on` assigns
4//! a free (inactive) voice, or **steals the oldest** voice when the pool is full. Voice
5//! age is a monotonic counter, so the lowest age is the oldest allocation. Frequency is
6//! passed in directly (a tuning table can drive it); `note_on_12tet` provides the default
7//! 12-TET mapping.
8
9use super::adsr::AdsrEnvelope;
10use super::oscillator_voice::Waveform;
11use super::voice::Voice;
12
13/// Default maximum simultaneous voices for a full-size pool.
14pub const MAX_VOICES: usize = 32;
15
16/// Fixed pool of `N` voices. All state is inline; no allocation on any path.
17#[derive(Clone, Copy, Debug)]
18pub struct VoiceAllocator<const N: usize> {
19    voices: [Voice; N],
20    /// Monotonic allocation counter (assigned as each voice's `age`).
21    next_age: u64,
22}
23
24impl<const N: usize> VoiceAllocator<N> {
25    /// Build a pool of `N` idle voices sharing a waveform + envelope template.
26    pub fn new(sample_rate: f32, waveform: Waveform, env: AdsrEnvelope) -> Self {
27        let template = Voice::new(sample_rate, waveform, env);
28        Self {
29            voices: [template; N],
30            next_age: 0,
31        }
32    }
33
34    /// Equal-temperament frequency (Hz) for a MIDI note (A4 = 69 = 440 Hz).
35    pub fn freq_12tet(note: u8) -> f32 {
36        440.0 * 2.0_f32.powf((note as f32 - 69.0) / 12.0)
37    }
38
39    /// Start a note at an explicit frequency (Hz). Assigns a free voice, or steals the
40    /// oldest voice when the pool is full. The active voice count never exceeds `N`.
41    pub fn note_on(&mut self, note: u8, velocity: u8, freq_hz: f32) {
42        if N == 0 {
43            return;
44        }
45        let age = self.next_age;
46        self.next_age = self.next_age.wrapping_add(1);
47
48        // Prefer a free (inactive) voice.
49        let mut target: Option<usize> = None;
50        for (i, v) in self.voices.iter().enumerate() {
51            if !v.is_active() {
52                target = Some(i);
53                break;
54            }
55        }
56        let idx = target.unwrap_or_else(|| self.oldest_index());
57        self.voices[idx].note_on(note, velocity, freq_hz, age);
58    }
59
60    /// Start a note using the default 12-TET frequency for `note`.
61    pub fn note_on_12tet(&mut self, note: u8, velocity: u8) {
62        self.note_on(note, velocity, Self::freq_12tet(note));
63    }
64
65    /// Release all held voices matching `note`.
66    pub fn note_off(&mut self, note: u8) {
67        for v in self.voices.iter_mut() {
68            if v.is_held() && v.note() == note {
69                v.note_off();
70            }
71        }
72    }
73
74    /// Number of voices currently producing signal.
75    pub fn active_count(&self) -> usize {
76        self.voices.iter().filter(|v| v.is_active()).count()
77    }
78
79    /// Pool capacity (`N`).
80    #[inline]
81    pub const fn capacity(&self) -> usize {
82        N
83    }
84
85    /// Immutable view of the voice array (for rendering / inspection).
86    #[inline]
87    pub fn voices(&self) -> &[Voice] {
88        &self.voices
89    }
90
91    /// Mutable view of the voice array (used by the render path).
92    #[inline]
93    pub fn voices_mut(&mut self) -> &mut [Voice] {
94        &mut self.voices
95    }
96
97    /// Index of the oldest voice (smallest age). `N >= 1` guaranteed by callers.
98    fn oldest_index(&self) -> usize {
99        let mut best = 0usize;
100        let mut best_age = u64::MAX;
101        for (i, v) in self.voices.iter().enumerate() {
102            if v.age() < best_age {
103                best_age = v.age();
104                best = i;
105            }
106        }
107        best
108    }
109}
110
111#[cfg(test)]
112mod tests {
113    use super::*;
114
115    const SR: f32 = 48_000.0;
116
117    fn env() -> AdsrEnvelope {
118        AdsrEnvelope::new(SR, 0.001, 0.0, 1.0, 0.100)
119    }
120
121    #[test]
122    fn twelve_tet_reference_pitches() {
123        assert!((VoiceAllocator::<4>::freq_12tet(69) - 440.0).abs() < 1e-3);
124        assert!((VoiceAllocator::<4>::freq_12tet(57) - 220.0).abs() < 1e-2);
125        assert!((VoiceAllocator::<4>::freq_12tet(60) - 261.6256).abs() < 1e-2);
126    }
127
128    #[test]
129    fn full_pool_then_one_more_steals_oldest() {
130        let mut alloc: VoiceAllocator<4> = VoiceAllocator::new(SR, Waveform::Sine, env());
131        // Fill all four voices with distinct notes; note 60 is oldest (age 0).
132        for &n in &[60u8, 62, 64, 65] {
133            alloc.note_on(n, 100, VoiceAllocator::<4>::freq_12tet(n));
134        }
135        assert_eq!(alloc.active_count(), 4);
136
137        // One more note must steal the oldest (60), not exceed capacity.
138        alloc.note_on(67, 100, VoiceAllocator::<4>::freq_12tet(67));
139        assert!(alloc.active_count() <= 4, "count must stay <= N");
140        assert_eq!(alloc.active_count(), 4);
141
142        let notes: [u8; 4] = {
143            let mut arr = [0u8; 4];
144            for (i, v) in alloc.voices().iter().enumerate() {
145                arr[i] = v.note();
146            }
147            arr
148        };
149        assert!(
150            !notes.contains(&60),
151            "oldest note 60 should have been stolen: {notes:?}"
152        );
153        assert!(
154            notes.contains(&67),
155            "new note 67 should be present: {notes:?}"
156        );
157        // The three younger notes survive.
158        for n in [62u8, 64, 65] {
159            assert!(
160                notes.contains(&n),
161                "younger note {n} should survive: {notes:?}"
162            );
163        }
164    }
165
166    #[test]
167    fn note_off_releases_matching_voice() {
168        let mut alloc: VoiceAllocator<4> = VoiceAllocator::new(SR, Waveform::Sine, env());
169        alloc.note_on(60, 100, 261.63);
170        assert!(alloc.voices()[0].is_held());
171        alloc.note_off(60);
172        assert!(!alloc.voices()[0].is_held());
173        // Still active during release.
174        assert!(alloc.voices()[0].is_active());
175    }
176
177    #[test]
178    fn zero_capacity_is_safe() {
179        let mut alloc: VoiceAllocator<0> = VoiceAllocator::new(SR, Waveform::Sine, env());
180        alloc.note_on(60, 100, 261.63);
181        assert_eq!(alloc.active_count(), 0);
182    }
183}