Skip to main content

qualia_audio/midi/sequencer/
track.rs

1//! A fixed-capacity track of timed MIDI events plus a zero-alloc "due window"
2//! iterator.
3//!
4//! [`TimedEvent`] is a small `Copy` POD — `(tick, status, data1, data2)` — the
5//! generic event currency this lane uses so it never depends on another lane's
6//! uncommitted types. A [`Track`] stores up to `N` of them on the stack, kept
7//! sorted by tick, and [`Track::due_window`] yields exactly the events whose
8//! tick falls in a half-open `[start, end)` window, in order. The iterator
9//! borrows the track and allocates nothing, so it is safe to call every audio
10//! block on the real-time thread.
11
12use crate::types::AudioError;
13
14/// A single timed MIDI event: a status byte + up to two data bytes, at an
15/// absolute tick position. All-integer and `Copy`, so it is torn-read-safe to
16/// move through the [`super::event_ring::EventRing`].
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub struct TimedEvent {
19    /// Absolute position on the sequencer timeline, in PPQ ticks.
20    pub tick: u64,
21    /// MIDI status byte (e.g. `0x90` note-on, channel in low nibble).
22    pub status: u8,
23    /// First data byte (e.g. note number).
24    pub data1: u8,
25    /// Second data byte (e.g. velocity).
26    pub data2: u8,
27}
28
29impl TimedEvent {
30    /// The all-zero event, usable as a fixed-array filler.
31    pub const ZERO: TimedEvent = TimedEvent {
32        tick: 0,
33        status: 0,
34        data1: 0,
35        data2: 0,
36    };
37
38    /// Construct a timed event.
39    #[inline]
40    pub const fn new(tick: u64, status: u8, data1: u8, data2: u8) -> Self {
41        Self {
42            tick,
43            status,
44            data1,
45            data2,
46        }
47    }
48}
49
50/// A fixed-capacity, tick-sorted track of `N` events.
51#[derive(Debug, Clone)]
52pub struct Track<const N: usize> {
53    events: [TimedEvent; N],
54    len: usize,
55}
56
57impl<const N: usize> Default for Track<N> {
58    fn default() -> Self {
59        Self::new()
60    }
61}
62
63impl<const N: usize> Track<N> {
64    /// An empty track.
65    pub const fn new() -> Self {
66        Self {
67            events: [TimedEvent::ZERO; N],
68            len: 0,
69        }
70    }
71
72    /// Number of events currently stored.
73    #[inline]
74    pub fn len(&self) -> usize {
75        self.len
76    }
77
78    /// Whether the track holds no events.
79    #[inline]
80    pub fn is_empty(&self) -> bool {
81        self.len == 0
82    }
83
84    /// Insert an event, keeping the track sorted by tick (stable for equal
85    /// ticks). This is a cold, loading-time operation — not for the audio
86    /// thread. Returns [`AudioError::OutputBufferTooSmall`] if the track is full.
87    pub fn insert(&mut self, event: TimedEvent) -> Result<(), AudioError> {
88        if self.len >= N {
89            return Err(AudioError::OutputBufferTooSmall);
90        }
91        // Find the insertion point (first index with a strictly greater tick),
92        // then shift the tail up by one. Stable: equal ticks keep insert order.
93        let mut i = self.len;
94        while i > 0 && self.events[i - 1].tick > event.tick {
95            self.events[i] = self.events[i - 1];
96            i -= 1;
97        }
98        self.events[i] = event;
99        self.len += 1;
100        Ok(())
101    }
102
103    /// Remove every event from the track.
104    pub fn clear(&mut self) {
105        self.len = 0;
106    }
107
108    /// All stored events, in tick order.
109    #[inline]
110    pub fn events(&self) -> &[TimedEvent] {
111        &self.events[..self.len]
112    }
113
114    /// Yield the events due in the half-open window `[start, end)`, in tick
115    /// order. Borrows the track; allocates nothing.
116    #[inline]
117    pub fn due_window(&self, start: u64, end: u64) -> DueWindow<'_> {
118        // Binary-search the first index with tick >= start; the tick-sorted
119        // slice lets the iterator stop as soon as it passes `end`.
120        let slice = &self.events[..self.len];
121        let mut lo = 0usize;
122        let mut hi = self.len;
123        while lo < hi {
124            let mid = lo + (hi - lo) / 2;
125            if slice[mid].tick < start {
126                lo = mid + 1;
127            } else {
128                hi = mid;
129            }
130        }
131        DueWindow {
132            slice,
133            idx: lo,
134            end,
135        }
136    }
137}
138
139/// Zero-alloc iterator over the events of a [`Track`] due in `[start, end)`.
140pub struct DueWindow<'a> {
141    slice: &'a [TimedEvent],
142    idx: usize,
143    end: u64,
144}
145
146impl<'a> Iterator for DueWindow<'a> {
147    type Item = &'a TimedEvent;
148
149    #[inline]
150    fn next(&mut self) -> Option<Self::Item> {
151        if self.idx >= self.slice.len() {
152            return None;
153        }
154        let ev = &self.slice[self.idx];
155        if ev.tick >= self.end {
156            return None;
157        }
158        self.idx += 1;
159        Some(ev)
160    }
161}
162
163#[cfg(test)]
164mod tests {
165    use super::*;
166
167    #[test]
168    fn insert_keeps_sorted() {
169        let mut t: Track<8> = Track::new();
170        t.insert(TimedEvent::new(300, 0x90, 60, 100)).unwrap();
171        t.insert(TimedEvent::new(100, 0x90, 62, 100)).unwrap();
172        t.insert(TimedEvent::new(200, 0x90, 64, 100)).unwrap();
173        let ticks: [u64; 3] = [t.events()[0].tick, t.events()[1].tick, t.events()[2].tick];
174        assert_eq!(ticks, [100, 200, 300]);
175    }
176
177    #[test]
178    fn due_window_in_order_none_outside() {
179        let mut t: Track<16> = Track::new();
180        for &tick in &[0u64, 50, 100, 150, 200, 250, 300] {
181            t.insert(TimedEvent::new(tick, 0x90, 60, 64)).unwrap();
182        }
183        // Window [100, 250): expect ticks 100, 150, 200 in order (250 excluded).
184        let got: heapless_vec::V =
185            t.due_window(100, 250)
186                .fold(heapless_vec::V::new(), |mut v, e| {
187                    v.push(e.tick);
188                    v
189                });
190        assert_eq!(got.as_slice(), &[100, 150, 200]);
191    }
192
193    #[test]
194    fn full_track_rejects_insert() {
195        let mut t: Track<2> = Track::new();
196        t.insert(TimedEvent::ZERO).unwrap();
197        t.insert(TimedEvent::ZERO).unwrap();
198        assert_eq!(
199            t.insert(TimedEvent::ZERO),
200            Err(AudioError::OutputBufferTooSmall)
201        );
202    }
203
204    /// Tiny fixed-capacity collector so the test asserts order without `Vec`.
205    mod heapless_vec {
206        pub struct V {
207            buf: [u64; 16],
208            len: usize,
209        }
210        impl V {
211            /// Creates a new instance.
212            pub fn new() -> Self {
213                Self {
214                    buf: [0; 16],
215                    len: 0,
216                }
217            }
218            /// Pushes an item.
219            pub fn push(&mut self, v: u64) {
220                self.buf[self.len] = v;
221                self.len += 1;
222            }
223            /// `slice` form.
224            pub fn as_slice(&self) -> &[u64] {
225                &self.buf[..self.len]
226            }
227        }
228    }
229}