Skip to main content

qualia_audio/midi/mpe/
note_allocation.rs

1//! MPE note allocation — assign incoming notes to member channels, rotating.
2//!
3//! In MPE each sounding note gets its own member channel so its per-note
4//! expression is independent. [`MpeNoteAllocator`] hands each new note the next
5//! free member channel using a **rotating** cursor (round-robin), which spreads
6//! successive notes across channels — the standard way to avoid immediately
7//! reusing a just-released channel and to keep pitch-bend glide artifacts apart.
8//! Occupancy is a fixed `[Option<u8>; 16]` table indexed by channel, so
9//! allocation and release are allocation-free and safe on the real-time thread.
10
11use crate::types::AudioError;
12
13use super::zone::MpeZone;
14
15/// Rotating (round-robin) allocator of member channels to active notes.
16#[derive(Debug, Clone)]
17pub struct MpeNoteAllocator {
18    zone: MpeZone,
19    /// Per-channel active note number (`None` = free). Indexed by channel 0..16.
20    active: [Option<u8>; 16],
21    /// Rotating cursor: the next member channel to try.
22    cursor: u8,
23}
24
25impl MpeNoteAllocator {
26    /// Create an allocator over `zone` with all member channels free.
27    pub fn new(zone: MpeZone) -> Self {
28        Self {
29            zone,
30            active: [None; 16],
31            cursor: zone.member_low,
32        }
33    }
34
35    /// Allocate a member channel for `note`, rotating from the current cursor.
36    ///
37    /// Returns the assigned channel index. Errors with
38    /// [`AudioError::BackendUnavailable`] if every member channel is occupied.
39    pub fn allocate(&mut self, note: u8) -> Result<u8, AudioError> {
40        let count = self.zone.member_count();
41        let low = self.zone.member_low;
42        // Try each member channel once, starting at the cursor.
43        for step in 0..count {
44            let ch = low + ((self.cursor - low + step) % count);
45            if self.active[ch as usize].is_none() {
46                self.active[ch as usize] = Some(note);
47                // Advance the cursor past the channel we just used.
48                self.cursor = low + ((ch - low + 1) % count);
49                return Ok(ch);
50            }
51        }
52        Err(AudioError::BackendUnavailable)
53    }
54
55    /// Release the channel currently holding `note`. Returns the freed channel,
56    /// or `None` if the note was not active.
57    pub fn release(&mut self, note: u8) -> Option<u8> {
58        let low = self.zone.member_low as usize;
59        let high = self.zone.member_high as usize;
60        for ch in low..=high {
61            if self.active[ch] == Some(note) {
62                self.active[ch] = None;
63                return Some(ch as u8);
64            }
65        }
66        None
67    }
68
69    /// The note currently sounding on `channel`, if any.
70    #[inline]
71    pub fn note_on_channel(&self, channel: u8) -> Option<u8> {
72        self.active.get(channel as usize).copied().flatten()
73    }
74
75    /// Number of member channels currently occupied.
76    pub fn active_count(&self) -> usize {
77        let low = self.zone.member_low as usize;
78        let high = self.zone.member_high as usize;
79        self.active[low..=high]
80            .iter()
81            .filter(|c| c.is_some())
82            .count()
83    }
84}
85
86#[cfg(test)]
87mod tests {
88    use super::*;
89
90    #[test]
91    fn golden_three_notes_three_distinct_channels() {
92        let mut alloc = MpeNoteAllocator::new(MpeZone::lower(7).unwrap());
93        let c0 = alloc.allocate(60).unwrap();
94        let c1 = alloc.allocate(64).unwrap();
95        let c2 = alloc.allocate(67).unwrap();
96        assert_ne!(c0, c1);
97        assert_ne!(c1, c2);
98        assert_ne!(c0, c2);
99        // All must be valid member channels.
100        for &c in &[c0, c1, c2] {
101            assert!((1..=7).contains(&c));
102        }
103    }
104
105    #[test]
106    fn rotates_and_reuses_after_release() {
107        let mut alloc = MpeNoteAllocator::new(MpeZone::lower(3).unwrap()); // channels 1,2,3
108        let a = alloc.allocate(60).unwrap();
109        let b = alloc.allocate(61).unwrap();
110        let c = alloc.allocate(62).unwrap();
111        assert_eq!([a, b, c], [1, 2, 3]);
112        assert!(alloc.allocate(63).is_err()); // full
113        assert_eq!(alloc.release(61), Some(2));
114        assert_eq!(alloc.allocate(63).unwrap(), 2); // reuses freed channel
115    }
116
117    #[test]
118    fn tracks_active_notes() {
119        let mut alloc = MpeNoteAllocator::new(MpeZone::lower(5).unwrap());
120        let ch = alloc.allocate(72).unwrap();
121        assert_eq!(alloc.note_on_channel(ch), Some(72));
122        assert_eq!(alloc.active_count(), 1);
123        alloc.release(72);
124        assert_eq!(alloc.active_count(), 0);
125        assert_eq!(alloc.note_on_channel(ch), None);
126    }
127}