Skip to main content

qualia_audio/midi/message/
running_status.rs

1//! Canonical MIDI 1.0 message model + a zero-alloc streaming parser with
2//! **running status**.
3//!
4//! [`MidiMessage`] is the `Copy` enum every other lane reconciles to. It covers
5//! the channel-voice messages, system-common, and system-real-time messages.
6//! SysEx payloads are variable-length and are *not* carried in this `Copy` enum;
7//! the streaming parser consumes SysEx bytes (emitting nothing) so a stream that
8//! interleaves SysEx still yields the surrounding channel messages correctly.
9//! Use [`crate::midi::message::sysex`] to frame/unframe SysEx over buffers.
10//!
11//! [`MessageParser`] is a byte-at-a-time state machine. It carries running
12//! status (a data byte with no preceding status re-uses the last channel-voice
13//! status), decodes system-real-time bytes that are interleaved mid-message
14//! without disturbing running status, and never allocates.
15
16use crate::types::AudioError;
17
18use super::channel_pressure::ChannelPressure;
19use super::control_change::ControlChange;
20use super::note::{NoteOff, NoteOn};
21use super::pitch_bend::PitchBend;
22use super::poly_pressure::PolyPressure;
23use super::program_change::ProgramChange;
24
25/// The canonical MIDI 1.0 message model (excluding SysEx payload bytes).
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum MidiMessage {
28    // ---- Channel voice ----
29    /// Note Off (`0x8n`).
30    NoteOff(NoteOff),
31    /// Note On (`0x9n`). Velocity 0 is an implied Note Off.
32    NoteOn(NoteOn),
33    /// Polyphonic Key Pressure (`0xAn`).
34    PolyPressure(PolyPressure),
35    /// Control Change (`0xBn`) — includes channel-mode controllers 120..=127.
36    ControlChange(ControlChange),
37    /// Program Change (`0xCn`).
38    ProgramChange(ProgramChange),
39    /// Channel Pressure (`0xDn`).
40    ChannelPressure(ChannelPressure),
41    /// Pitch Bend (`0xEn`), 14-bit.
42    PitchBend(PitchBend),
43
44    // ---- System common ----
45    /// MTC Quarter Frame (`0xF1`); payload is the 7-bit data byte.
46    QuarterFrame(u8),
47    /// Song Position Pointer (`0xF2`), 14-bit.
48    SongPositionPointer(u16),
49    /// Song Select (`0xF3`); payload is the song number.
50    SongSelect(u8),
51    /// Tune Request (`0xF6`).
52    TuneRequest,
53
54    // ---- System real-time ----
55    /// Timing Clock (`0xF8`).
56    TimingClock,
57    /// Start (`0xFA`).
58    Start,
59    /// Continue (`0xFB`).
60    Continue,
61    /// Stop (`0xFC`).
62    Stop,
63    /// Active Sensing (`0xFE`).
64    ActiveSensing,
65    /// System Reset (`0xFF`).
66    SystemReset,
67}
68
69/// A zero-alloc, byte-at-a-time MIDI 1.0 stream parser with running status.
70#[derive(Debug, Clone, Copy)]
71pub struct MessageParser {
72    /// Current running status byte (0 = none held), for channel-voice + `0xF1..0xF3`.
73    status: u8,
74    /// Data bytes collected so far for the in-progress message.
75    data: [u8; 2],
76    /// Count of data bytes collected.
77    data_len: u8,
78    /// Data bytes expected for the current status.
79    expected: u8,
80    /// Whether we are inside a SysEx (`F0`..`F7`) region.
81    in_sysex: bool,
82}
83
84impl Default for MessageParser {
85    fn default() -> Self {
86        Self::new()
87    }
88}
89
90/// Data-byte count for a channel-voice / system-common status byte, or `None`
91/// if `status` is not one that collects data bytes here.
92fn expected_data_bytes(status: u8) -> Option<u8> {
93    match status & 0xF0 {
94        0x80 | 0x90 | 0xA0 | 0xB0 | 0xE0 => Some(2),
95        0xC0 | 0xD0 => Some(1),
96        0xF0 => match status {
97            0xF1 => Some(1), // MTC quarter frame
98            0xF2 => Some(2), // song position pointer
99            0xF3 => Some(1), // song select
100            _ => None,       // F0/F4/F5/F6/F7 handled directly, not via data collection
101        },
102        _ => None,
103    }
104}
105
106/// Decode a single-byte system real-time status (`0xF8..=0xFF`).
107fn decode_real_time(status: u8) -> Option<MidiMessage> {
108    match status {
109        0xF8 => Some(MidiMessage::TimingClock),
110        0xFA => Some(MidiMessage::Start),
111        0xFB => Some(MidiMessage::Continue),
112        0xFC => Some(MidiMessage::Stop),
113        0xFE => Some(MidiMessage::ActiveSensing),
114        0xFF => Some(MidiMessage::SystemReset),
115        _ => None, // 0xF9, 0xFD are undefined real-time
116    }
117}
118
119impl MessageParser {
120    /// A fresh parser with no running status held.
121    pub const fn new() -> Self {
122        Self {
123            status: 0,
124            data: [0; 2],
125            data_len: 0,
126            expected: 0,
127            in_sysex: false,
128        }
129    }
130
131    /// Build the message for the current (complete) status + data bytes.
132    fn build(&self) -> Option<MidiMessage> {
133        let ch = self.status & 0x0F;
134        let d0 = self.data[0];
135        let d1 = self.data[1];
136        match self.status & 0xF0 {
137            0x80 => Some(MidiMessage::NoteOff(NoteOff {
138                channel: ch,
139                note: d0,
140                velocity: d1,
141            })),
142            0x90 => Some(MidiMessage::NoteOn(NoteOn {
143                channel: ch,
144                note: d0,
145                velocity: d1,
146            })),
147            0xA0 => Some(MidiMessage::PolyPressure(PolyPressure {
148                channel: ch,
149                note: d0,
150                pressure: d1,
151            })),
152            0xB0 => Some(MidiMessage::ControlChange(ControlChange {
153                channel: ch,
154                controller: d0,
155                value: d1,
156            })),
157            0xC0 => Some(MidiMessage::ProgramChange(ProgramChange {
158                channel: ch,
159                program: d0,
160            })),
161            0xD0 => Some(MidiMessage::ChannelPressure(ChannelPressure {
162                channel: ch,
163                pressure: d0,
164            })),
165            0xE0 => Some(MidiMessage::PitchBend(PitchBend {
166                channel: ch,
167                value: ((d1 as u16) << 7) | (d0 as u16),
168            })),
169            0xF0 => match self.status {
170                0xF1 => Some(MidiMessage::QuarterFrame(d0)),
171                0xF2 => Some(MidiMessage::SongPositionPointer(
172                    ((d1 as u16) << 7) | (d0 as u16),
173                )),
174                0xF3 => Some(MidiMessage::SongSelect(d0)),
175                _ => None,
176            },
177            _ => None,
178        }
179    }
180
181    /// Feed one byte. Returns `Some(message)` when a complete message has been
182    /// decoded, otherwise `None`. Never allocates.
183    pub fn push(&mut self, byte: u8) -> Option<MidiMessage> {
184        if byte >= 0x80 {
185            // ---- Status byte ----
186            if byte >= 0xF8 {
187                // System real-time: does NOT affect running status or an
188                // in-progress message; decode and emit immediately.
189                return decode_real_time(byte);
190            }
191            match byte {
192                0xF0 => {
193                    // SysEx start. Clears running status (system message).
194                    self.in_sysex = true;
195                    self.status = 0;
196                    self.data_len = 0;
197                    None
198                }
199                0xF7 => {
200                    // End of SysEx. Running status remains cleared.
201                    self.in_sysex = false;
202                    self.data_len = 0;
203                    None
204                }
205                0xF6 => {
206                    // Tune Request: no data bytes, clears running status.
207                    self.status = 0;
208                    self.data_len = 0;
209                    self.in_sysex = false;
210                    Some(MidiMessage::TuneRequest)
211                }
212                _ => {
213                    // Channel-voice status, or F1/F2/F3 system-common.
214                    self.in_sysex = false;
215                    match expected_data_bytes(byte) {
216                        Some(exp) => {
217                            self.status = byte;
218                            self.expected = exp;
219                            self.data_len = 0;
220                            None
221                        }
222                        // Undefined (F4/F5) or otherwise: clear and ignore.
223                        None => {
224                            self.status = 0;
225                            self.data_len = 0;
226                            None
227                        }
228                    }
229                }
230            }
231        } else {
232            // ---- Data byte (< 0x80) ----
233            if self.in_sysex {
234                // Consumed as SysEx payload; not surfaced here.
235                return None;
236            }
237            if self.status == 0 {
238                // Stray data byte with no running status: ignore.
239                return None;
240            }
241            self.data[self.data_len as usize] = byte;
242            self.data_len += 1;
243            if self.data_len >= self.expected {
244                let msg = self.build();
245                // Retain `status` for running status; reset data collection.
246                self.data_len = 0;
247                return msg;
248            }
249            None
250        }
251    }
252
253    /// Reset the parser to its initial state (drop any running status / SysEx).
254    pub fn reset(&mut self) {
255        *self = Self::new();
256    }
257}
258
259/// Parse a full byte slice, invoking `on_msg` for each complete message.
260/// Zero-alloc: state lives in a stack [`MessageParser`]; no buffers are grown.
261pub fn parse_stream<F: FnMut(MidiMessage)>(bytes: &[u8], mut on_msg: F) {
262    let mut parser = MessageParser::new();
263    for &b in bytes {
264        if let Some(m) = parser.push(b) {
265            on_msg(m);
266        }
267    }
268}
269
270/// Convenience: parse into a caller-provided output buffer, returning the count
271/// written. Errors [`AudioError::OutputBufferTooSmall`] if more messages are
272/// produced than fit. Zero-alloc.
273pub fn parse_into(bytes: &[u8], out: &mut [MidiMessage]) -> Result<usize, AudioError> {
274    let mut n = 0usize;
275    let mut overflow = false;
276    parse_stream(bytes, |m| {
277        if n < out.len() {
278            out[n] = m;
279            n += 1;
280        } else {
281            overflow = true;
282        }
283    });
284    if overflow {
285        return Err(AudioError::OutputBufferTooSmall);
286    }
287    Ok(n)
288}
289
290#[cfg(test)]
291mod tests {
292    use super::*;
293
294    #[test]
295    fn golden_single_note_on() {
296        let mut msgs = [MidiMessage::TuneRequest; 4];
297        let n = parse_into(&[0x90, 0x3C, 0x64], &mut msgs).unwrap();
298        assert_eq!(n, 1);
299        match msgs[0] {
300            MidiMessage::NoteOn(no) => {
301                assert_eq!(no.channel, 0);
302                assert_eq!(no.note, 60);
303                assert_eq!(no.velocity, 100);
304            }
305            other => panic!("expected NoteOn, got {other:?}"),
306        }
307    }
308
309    #[test]
310    fn golden_running_status_two_note_ons() {
311        // 0x90 0x3C 0x64 0x3E 0x64 -> TWO note-ons; second reuses status 0x90.
312        let mut msgs = [MidiMessage::TuneRequest; 4];
313        let n = parse_into(&[0x90, 0x3C, 0x64, 0x3E, 0x64], &mut msgs).unwrap();
314        assert_eq!(n, 2);
315        let notes: [u8; 2] = match (msgs[0], msgs[1]) {
316            (MidiMessage::NoteOn(a), MidiMessage::NoteOn(b)) => {
317                assert_eq!(a.channel, 0);
318                assert_eq!(a.velocity, 100);
319                assert_eq!(b.channel, 0);
320                assert_eq!(b.velocity, 100);
321                [a.note, b.note]
322            }
323            other => panic!("expected two NoteOns, got {other:?}"),
324        };
325        assert_eq!(notes, [60, 62]);
326    }
327
328    #[test]
329    fn golden_pitch_bend_center_via_stream() {
330        let mut msgs = [MidiMessage::TuneRequest; 2];
331        let n = parse_into(&[0xE0, 0x00, 0x40], &mut msgs).unwrap();
332        assert_eq!(n, 1);
333        match msgs[0] {
334            MidiMessage::PitchBend(pb) => assert_eq!(pb.value, 8192),
335            other => panic!("expected PitchBend, got {other:?}"),
336        }
337    }
338
339    #[test]
340    fn realtime_interleaved_midmessage() {
341        // Timing clock (0xF8) arrives between the data bytes of a note-on; it
342        // must be emitted without disturbing the note-on being assembled.
343        let mut got = [MidiMessage::TuneRequest; 4];
344        let mut i = 0;
345        parse_stream(&[0x90, 0x3C, 0xF8, 0x64], |m| {
346            got[i] = m;
347            i += 1;
348        });
349        assert_eq!(i, 2);
350        assert_eq!(got[0], MidiMessage::TimingClock);
351        match got[1] {
352            MidiMessage::NoteOn(no) => {
353                assert_eq!(no.note, 60);
354                assert_eq!(no.velocity, 100);
355            }
356            other => panic!("expected NoteOn, got {other:?}"),
357        }
358    }
359
360    #[test]
361    fn sysex_is_skipped_but_surrounding_survives() {
362        // NoteOn, then a SysEx blob, then a program change (new status).
363        let stream = [0x90, 0x3C, 0x64, 0xF0, 0x43, 0x12, 0xF7, 0xC0, 0x28];
364        let mut msgs = [MidiMessage::TuneRequest; 4];
365        let n = parse_into(&stream, &mut msgs).unwrap();
366        assert_eq!(n, 2);
367        assert!(matches!(msgs[0], MidiMessage::NoteOn(_)));
368        match msgs[1] {
369            MidiMessage::ProgramChange(pc) => assert_eq!(pc.program, 40),
370            other => panic!("expected ProgramChange, got {other:?}"),
371        }
372    }
373
374    #[test]
375    fn running_status_program_change_and_song_position() {
376        // Program change with running status (two programs), then song position.
377        let mut msgs = [MidiMessage::TuneRequest; 4];
378        let n = parse_into(&[0xC0, 0x01, 0x02, 0xF2, 0x00, 0x40], &mut msgs).unwrap();
379        assert_eq!(n, 3);
380        assert_eq!(
381            msgs[0],
382            MidiMessage::ProgramChange(ProgramChange {
383                channel: 0,
384                program: 1
385            })
386        );
387        assert_eq!(
388            msgs[1],
389            MidiMessage::ProgramChange(ProgramChange {
390                channel: 0,
391                program: 2
392            })
393        );
394        assert_eq!(msgs[2], MidiMessage::SongPositionPointer(8192));
395    }
396
397    #[test]
398    fn overflow_reported() {
399        let mut msgs = [MidiMessage::TuneRequest; 1];
400        assert_eq!(
401            parse_into(&[0x90, 0x3C, 0x64, 0x3E, 0x64], &mut msgs),
402            Err(AudioError::OutputBufferTooSmall)
403        );
404    }
405}