qualia_audio/midi/synth/
voice_allocator.rs1use super::adsr::AdsrEnvelope;
10use super::oscillator_voice::Waveform;
11use super::voice::Voice;
12
13pub const MAX_VOICES: usize = 32;
15
16#[derive(Clone, Copy, Debug)]
18pub struct VoiceAllocator<const N: usize> {
19 voices: [Voice; N],
20 next_age: u64,
22}
23
24impl<const N: usize> VoiceAllocator<N> {
25 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 pub fn freq_12tet(note: u8) -> f32 {
36 440.0 * 2.0_f32.powf((note as f32 - 69.0) / 12.0)
37 }
38
39 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 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 pub fn note_on_12tet(&mut self, note: u8, velocity: u8) {
62 self.note_on(note, velocity, Self::freq_12tet(note));
63 }
64
65 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 pub fn active_count(&self) -> usize {
76 self.voices.iter().filter(|v| v.is_active()).count()
77 }
78
79 #[inline]
81 pub const fn capacity(&self) -> usize {
82 N
83 }
84
85 #[inline]
87 pub fn voices(&self) -> &[Voice] {
88 &self.voices
89 }
90
91 #[inline]
93 pub fn voices_mut(&mut self) -> &mut [Voice] {
94 &mut self.voices
95 }
96
97 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 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 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 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 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}