Skip to main content

aura_core/
note_voices.rs

1//! CLAP voice table keyed by `note_id` — expressions in, `NOTE_END` out.
2//!
3//! Plugin owns oscillators / envelopes. This tracks which host notes are
4//! live and emits [`NoteEventKind::End`] when the plugin marks a voice silent
5//! (or when a new note steals the slot).
6
7use crate::note_events::{NoteBuffer, NoteEvent, NoteEventKind, NoteExpression};
8
9/// One occupied slot in [`NoteVoiceTable`].
10#[derive(Clone, Copy, Debug, PartialEq)]
11pub struct NoteVoice {
12    pub note_id: i32,
13    pub key: i16,
14    pub channel: i16,
15    pub port_index: i16,
16    pub velocity: f32,
17    /// CLAP volume expression (1.0 = 0 dB).
18    pub volume: f32,
19    pub pan: f32,
20    /// Tuning expression in semitones.
21    pub tuning: f32,
22    pub vibrato: f32,
23    pub expression: f32,
24    pub brightness: f32,
25    pub pressure: f32,
26    gated: bool,
27    occupied: bool,
28}
29
30impl NoteVoice {
31    const fn empty() -> Self {
32        Self {
33            note_id: -1,
34            key: 0,
35            channel: 0,
36            port_index: 0,
37            velocity: 0.0,
38            volume: 1.0,
39            pan: 0.0,
40            tuning: 0.0,
41            vibrato: 0.0,
42            expression: 0.0,
43            brightness: 0.0,
44            pressure: 1.0,
45            gated: false,
46            occupied: false,
47        }
48    }
49
50    #[must_use]
51    pub const fn is_occupied(self) -> bool {
52        self.occupied
53    }
54
55    #[must_use]
56    pub const fn is_gated(self) -> bool {
57        self.occupied && self.gated
58    }
59}
60
61/// Fixed-size voice pool. No heap in `apply` / `flush_ends` after [`Self::new`].
62pub struct NoteVoiceTable {
63    voices: Vec<NoteVoice>,
64    pending_ends: Vec<NoteEvent>,
65}
66
67impl NoteVoiceTable {
68    #[must_use]
69    pub fn new(max_voices: usize) -> Self {
70        let n = max_voices.clamp(1, 128);
71        Self {
72            voices: vec![NoteVoice::empty(); n],
73            pending_ends: Vec::with_capacity(n),
74        }
75    }
76
77    #[must_use]
78    pub fn max_voices(&self) -> usize {
79        self.voices.len()
80    }
81
82    #[must_use]
83    pub fn occupied_count(&self) -> usize {
84        self.voices.iter().filter(|v| v.occupied).count()
85    }
86
87    #[must_use]
88    pub fn voices(&self) -> &[NoteVoice] {
89        &self.voices
90    }
91
92    pub fn voice_mut(&mut self, index: usize) -> Option<&mut NoteVoice> {
93        self.voices.get_mut(index)
94    }
95
96    /// Route inbound CLAP notes. `On` allocates / retriggers; `Off` releases the
97    /// gate; `Choke` queues `NOTE_END` immediately; expressions update matches.
98    pub fn apply(&mut self, notes: &NoteBuffer) {
99        for ev in notes.iter() {
100            match ev.kind {
101                NoteEventKind::On { velocity } => {
102                    let _ = self.alloc(ev, velocity);
103                }
104                NoteEventKind::Off { .. } => {
105                    for v in &mut self.voices {
106                        if v.occupied && ev.matches_voice(v.note_id, v.key) {
107                            v.gated = false;
108                        }
109                    }
110                }
111                NoteEventKind::Choke => {
112                    for i in 0..self.voices.len() {
113                        let v = self.voices[i];
114                        if v.occupied && ev.matches_voice(v.note_id, v.key) {
115                            self.queue_end(i, ev.sample_offset);
116                            self.voices[i] = NoteVoice::empty();
117                        }
118                    }
119                }
120                NoteEventKind::End => {
121                    // Host-originated end: drop without echoing.
122                    for v in &mut self.voices {
123                        if v.occupied && ev.matches_voice(v.note_id, v.key) {
124                            *v = NoteVoice::empty();
125                        }
126                    }
127                }
128                NoteEventKind::Expression { id, value } => {
129                    #[allow(clippy::cast_possible_truncation)]
130                    let f = value as f32;
131                    for v in &mut self.voices {
132                        if v.occupied && ev.matches_voice(v.note_id, v.key) {
133                            match id {
134                                NoteExpression::Volume => v.volume = f,
135                                NoteExpression::Pan => v.pan = f,
136                                NoteExpression::Tuning => v.tuning = f,
137                                NoteExpression::Vibrato => v.vibrato = f,
138                                NoteExpression::Expression => v.expression = f,
139                                NoteExpression::Brightness => v.brightness = f,
140                                NoteExpression::Pressure => v.pressure = f,
141                                NoteExpression::Other(_) => {}
142                            }
143                        }
144                    }
145                }
146                NoteEventKind::ParamMod { .. } | NoteEventKind::ParamValue { .. } => {}
147            }
148        }
149    }
150
151    /// Envelope finished (or steal-equivalent). Next [`Self::flush_ends`] emits `NOTE_END`.
152    pub fn mark_silent(&mut self, index: usize, sample_offset: u32) {
153        if index >= self.voices.len() || !self.voices[index].occupied {
154            return;
155        }
156        self.queue_end(index, sample_offset);
157        self.voices[index] = NoteVoice::empty();
158    }
159
160    pub fn mark_silent_id(&mut self, note_id: i32, sample_offset: u32) {
161        for i in 0..self.voices.len() {
162            let v = self.voices[i];
163            if v.occupied && (note_id < 0 || v.note_id == note_id) {
164                self.mark_silent(i, sample_offset);
165            }
166        }
167    }
168
169    pub fn mark_all_silent(&mut self, sample_offset: u32) {
170        for i in 0..self.voices.len() {
171            if self.voices[i].occupied {
172                self.mark_silent(i, sample_offset);
173            }
174        }
175    }
176
177    /// Push queued `NOTE_END` events (steal + [`Self::mark_silent`]).
178    pub fn flush_ends(&mut self, out: &mut NoteBuffer) {
179        for ev in self.pending_ends.drain(..) {
180            out.push(ev);
181        }
182    }
183
184    fn alloc(&mut self, ev: NoteEvent, velocity: f64) -> Option<usize> {
185        if ev.note_id >= 0
186            && let Some(i) = self
187                .voices
188                .iter()
189                .position(|v| v.occupied && v.note_id == ev.note_id)
190        {
191            self.reset_voice(i, ev, velocity);
192            return Some(i);
193        }
194        if let Some(i) = self.voices.iter().position(|v| !v.occupied) {
195            self.reset_voice(i, ev, velocity);
196            return Some(i);
197        }
198        let steal = self
199            .voices
200            .iter()
201            .position(|v| v.occupied && !v.gated)
202            .or_else(|| self.voices.iter().position(|v| v.occupied))?;
203        self.queue_end(steal, ev.sample_offset);
204        self.reset_voice(steal, ev, velocity);
205        Some(steal)
206    }
207
208    fn reset_voice(&mut self, i: usize, ev: NoteEvent, velocity: f64) {
209        #[allow(clippy::cast_possible_truncation)]
210        let vel = velocity as f32;
211        let mut v = NoteVoice::empty();
212        v.occupied = true;
213        v.gated = true;
214        v.note_id = ev.note_id;
215        v.key = ev.key;
216        v.channel = ev.channel;
217        v.port_index = ev.port_index;
218        v.velocity = vel;
219        self.voices[i] = v;
220    }
221
222    fn queue_end(&mut self, i: usize, sample_offset: u32) {
223        let v = self.voices[i];
224        if !v.occupied {
225            return;
226        }
227        let mut end = NoteEvent::end(sample_offset, v.note_id, v.key);
228        end.port_index = v.port_index;
229        end.channel = v.channel;
230        self.pending_ends.push(end);
231    }
232}
233
234#[cfg(test)]
235mod tests {
236    use super::*;
237
238    #[test]
239    fn on_off_end_and_steal() {
240        let mut table = NoteVoiceTable::new(1);
241        let mut notes = NoteBuffer::new();
242        notes.push(NoteEvent::on(0, 3, 60, 0.8));
243        table.apply(&notes);
244        assert_eq!(table.occupied_count(), 1);
245        assert!((table.voices()[0].velocity - 0.8).abs() < 1e-6);
246        assert!(table.voices()[0].is_gated());
247
248        notes.clear();
249        notes.push(NoteEvent::off(4, 3, 60, 0.0));
250        table.apply(&notes);
251        assert!(table.voices()[0].is_occupied());
252        assert!(!table.voices()[0].is_gated());
253
254        let mut out = NoteBuffer::new();
255        table.mark_silent(0, 20);
256        table.flush_ends(&mut out);
257        assert_eq!(out.len(), 1);
258        assert!(matches!(out.as_slice()[0].kind, NoteEventKind::End));
259        assert_eq!(out.as_slice()[0].note_id, 3);
260        assert_eq!(table.occupied_count(), 0);
261
262        notes.clear();
263        notes.push(NoteEvent::on(0, 1, 64, 1.0));
264        table.apply(&notes);
265        notes.clear();
266        notes.push(NoteEvent::on(8, 2, 67, 1.0));
267        table.apply(&notes);
268        out.clear();
269        table.flush_ends(&mut out);
270        assert_eq!(out.len(), 1);
271        assert_eq!(out.as_slice()[0].note_id, 1);
272        assert_eq!(table.voices()[0].note_id, 2);
273    }
274
275    #[test]
276    fn expression_matches_note_id() {
277        let mut table = NoteVoiceTable::new(2);
278        let mut notes = NoteBuffer::new();
279        notes.push(NoteEvent::on(0, 1, 60, 1.0));
280        notes.push(NoteEvent::on(0, 2, 64, 1.0));
281        notes.push(NoteEvent {
282            sample_offset: 1,
283            note_id: 2,
284            port_index: 0,
285            channel: 0,
286            key: 64,
287            kind: NoteEventKind::Expression {
288                id: NoteExpression::Tuning,
289                value: 7.0,
290            },
291        });
292        table.apply(&notes);
293        assert!((table.voices()[0].tuning).abs() < 1e-6);
294        assert!((table.voices()[1].tuning - 7.0).abs() < 1e-6);
295    }
296}