Skip to main content

qualia_audio/midi/smf/
read.rs

1//! Standard MIDI File parser: MThd + MTrk chunks → [`SmfFile`].
2//!
3//! Defines the structured in-memory model ([`SmfFile`], [`Track`], [`Event`],
4//! [`TrackEvent`], [`Division`]) that the whole `smf` module shares, and
5//! [`read_smf`], which parses a complete SMF byte buffer. Running status inside
6//! tracks is expanded (each stored channel event carries its explicit status).
7//! Cold path — `Vec` throughout is deliberate.
8//!
9//! Lane AU-MIDI-FILE.
10
11use super::meta_event::{parse_meta, MetaEvent};
12use super::vlq::read_vlq;
13use crate::types::AudioError;
14
15/// SMF time division (the MThd `division` field).
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum Division {
18    /// Metrical time: ticks (pulses) per quarter note. High bit is 0.
19    Ppq(u16),
20    /// SMPTE time-code based division. High bit is 1.
21    Smpte {
22        /// Frames per second (25, 24, 29 for 29.97-drop, or 30).
23        fps: u8,
24        /// Ticks (subdivisions) per frame.
25        ticks_per_frame: u8,
26    },
27}
28
29impl Division {
30    /// Decode the raw 16-bit MThd division field.
31    pub fn from_raw(raw: u16) -> Self {
32        if raw & 0x8000 != 0 {
33            // High byte is a signed negative frame count (two's complement).
34            let neg = ((raw >> 8) & 0xFF) as u8;
35            let fps = (256u16 - u16::from(neg)) as u8;
36            Division::Smpte {
37                fps,
38                ticks_per_frame: (raw & 0xFF) as u8,
39            }
40        } else {
41            Division::Ppq(raw & 0x7FFF)
42        }
43    }
44
45    /// Encode back to the raw 16-bit MThd field.
46    pub fn to_raw(self) -> u16 {
47        match self {
48            Division::Ppq(ppq) => ppq & 0x7FFF,
49            Division::Smpte {
50                fps,
51                ticks_per_frame,
52            } => {
53                let neg = (256u16 - u16::from(fps)) & 0xFF;
54                (neg << 8) | u16::from(ticks_per_frame)
55            }
56        }
57    }
58}
59
60/// A single track event: MIDI channel message, meta-event, or system-exclusive.
61#[derive(Debug, Clone, PartialEq, Eq)]
62pub enum TrackEvent {
63    /// Channel voice/mode message. `status` includes the channel nibble; `data`
64    /// holds the 1 or 2 data bytes that follow.
65    Midi { status: u8, data: Vec<u8> },
66    /// Meta-event (`0xFF ...`).
67    Meta(MetaEvent),
68    /// System-exclusive. `start` is `0xF0` (normal) or `0xF7` (escape/continued);
69    /// `data` is the payload bytes that were length-prefixed in the file
70    /// (including any terminating `0xF7` for a complete `0xF0` message).
71    SysEx { start: u8, data: Vec<u8> },
72}
73
74/// A delta-timed track event.
75#[derive(Debug, Clone, PartialEq, Eq)]
76pub struct Event {
77    /// Ticks since the previous event in the track.
78    pub delta_ticks: u32,
79    /// The event itself.
80    pub event: TrackEvent,
81}
82
83/// One MTrk track: an ordered list of delta-timed events.
84#[derive(Debug, Clone, PartialEq, Eq, Default)]
85pub struct Track {
86    pub events: Vec<Event>,
87}
88
89/// A parsed Standard MIDI File.
90#[derive(Debug, Clone, PartialEq, Eq)]
91pub struct SmfFile {
92    /// 0 (single multi-channel track), 1 (multiple simultaneous tracks), or 2
93    /// (multiple independent sequences).
94    pub format: u16,
95    /// Time division from the header.
96    pub division: Division,
97    /// The tracks, in file order.
98    pub tracks: Vec<Track>,
99}
100
101/// Number of data bytes following a channel-message status byte.
102///
103/// Returns `None` if `status` is not a channel voice/mode status (`0x80..=0xEF`).
104pub(super) fn channel_data_len(status: u8) -> Option<usize> {
105    match status & 0xF0 {
106        0x80 | 0x90 | 0xA0 | 0xB0 | 0xE0 => Some(2),
107        0xC0 | 0xD0 => Some(1),
108        _ => None,
109    }
110}
111
112/// Read a big-endian u32 at `pos`, advancing nothing.
113fn read_u32_be(bytes: &[u8], pos: usize) -> Result<u32, AudioError> {
114    let s = bytes.get(pos..pos + 4).ok_or(AudioError::MalformedAudio)?;
115    Ok(
116        (u32::from(s[0]) << 24)
117            | (u32::from(s[1]) << 16)
118            | (u32::from(s[2]) << 8)
119            | u32::from(s[3]),
120    )
121}
122
123/// Read a big-endian u16 at `pos`.
124fn read_u16_be(bytes: &[u8], pos: usize) -> Result<u16, AudioError> {
125    let s = bytes.get(pos..pos + 2).ok_or(AudioError::MalformedAudio)?;
126    Ok((u16::from(s[0]) << 8) | u16::from(s[1]))
127}
128
129/// Parse a complete Standard MIDI File byte buffer.
130///
131/// Validates the `MThd` header (must declare format 0/1/2 and a 6-byte body),
132/// then parses exactly `ntracks` `MTrk` chunks. Non-`MTrk` chunks encountered
133/// where a track is expected are rejected. Returns [`AudioError::MalformedAudio`]
134/// for structural problems and [`AudioError::UnsupportedFormat`] for an unknown
135/// SMF format number.
136pub fn read_smf(bytes: &[u8]) -> Result<SmfFile, AudioError> {
137    // --- Header chunk (MThd) ---
138    if bytes.len() < 14 || &bytes[0..4] != b"MThd" {
139        return Err(AudioError::MalformedAudio);
140    }
141    let header_len = read_u32_be(bytes, 4)?;
142    if header_len != 6 {
143        return Err(AudioError::MalformedAudio);
144    }
145    let format = read_u16_be(bytes, 8)?;
146    if format > 2 {
147        return Err(AudioError::UnsupportedFormat);
148    }
149    let ntracks = read_u16_be(bytes, 10)? as usize;
150    let division = Division::from_raw(read_u16_be(bytes, 12)?);
151
152    // Header body may in principle be longer than 6, but we validated == 6.
153    let mut pos = 8 + header_len as usize;
154
155    // --- Track chunks (MTrk) ---
156    let mut tracks = Vec::with_capacity(ntracks);
157    for _ in 0..ntracks {
158        // Chunk header: 4-byte id + 4-byte length.
159        let id = bytes.get(pos..pos + 4).ok_or(AudioError::MalformedAudio)?;
160        let chunk_len = read_u32_be(bytes, pos + 4)? as usize;
161        let body_start = pos + 8;
162        let body_end = body_start
163            .checked_add(chunk_len)
164            .ok_or(AudioError::MalformedAudio)?;
165        let body = bytes
166            .get(body_start..body_end)
167            .ok_or(AudioError::MalformedAudio)?;
168
169        if id == b"MTrk" {
170            tracks.push(parse_track(body)?);
171        } else {
172            // Alien chunk where a track was declared: reject rather than guess.
173            return Err(AudioError::MalformedAudio);
174        }
175        pos = body_end;
176    }
177
178    Ok(SmfFile {
179        format,
180        division,
181        tracks,
182    })
183}
184
185/// Parse a single MTrk body (the bytes between the chunk length and its end)
186/// into a [`Track`], expanding running status.
187fn parse_track(body: &[u8]) -> Result<Track, AudioError> {
188    let mut events = Vec::new();
189    let mut pos = 0usize;
190    let mut running_status: Option<u8> = None;
191
192    while pos < body.len() {
193        // Delta time.
194        let (delta_ticks, used) = read_vlq(&body[pos..])?;
195        pos += used;
196
197        let first = *body.get(pos).ok_or(AudioError::MalformedAudio)?;
198
199        let event = if first == 0xFF {
200            // Meta-event: 0xFF <type> <vlq len> <data>. Clears running status.
201            running_status = None;
202            pos += 1;
203            let meta_type = *body.get(pos).ok_or(AudioError::MalformedAudio)?;
204            pos += 1;
205            let (len, used) = read_vlq(&body[pos..])?;
206            pos += used;
207            let len = len as usize;
208            let data = body.get(pos..pos + len).ok_or(AudioError::MalformedAudio)?;
209            pos += len;
210            TrackEvent::Meta(parse_meta(meta_type, data)?)
211        } else if first == 0xF0 || first == 0xF7 {
212            // SysEx (0xF0) or escape/continuation (0xF7): <status> <vlq len> <data>.
213            running_status = None;
214            let start = first;
215            pos += 1;
216            let (len, used) = read_vlq(&body[pos..])?;
217            pos += used;
218            let len = len as usize;
219            let data = body.get(pos..pos + len).ok_or(AudioError::MalformedAudio)?;
220            pos += len;
221            TrackEvent::SysEx {
222                start,
223                data: data.to_vec(),
224            }
225        } else if first & 0x80 != 0 {
226            // Explicit channel status byte.
227            let status = first;
228            pos += 1;
229            let dlen = channel_data_len(status).ok_or(AudioError::MalformedAudio)?;
230            let data = body
231                .get(pos..pos + dlen)
232                .ok_or(AudioError::MalformedAudio)?;
233            pos += dlen;
234            running_status = Some(status);
235            TrackEvent::Midi {
236                status,
237                data: data.to_vec(),
238            }
239        } else {
240            // Data byte with no status → running status: reuse last channel status.
241            let status = running_status.ok_or(AudioError::MalformedAudio)?;
242            let dlen = channel_data_len(status).ok_or(AudioError::MalformedAudio)?;
243            let data = body
244                .get(pos..pos + dlen)
245                .ok_or(AudioError::MalformedAudio)?;
246            pos += dlen;
247            TrackEvent::Midi {
248                status,
249                data: data.to_vec(),
250            }
251        };
252
253        events.push(Event { delta_ticks, event });
254    }
255
256    Ok(Track { events })
257}
258
259#[cfg(test)]
260mod tests {
261    use super::*;
262
263    #[test]
264    fn division_raw_round_trip() {
265        assert_eq!(Division::from_raw(480), Division::Ppq(480));
266        assert_eq!(Division::Ppq(480).to_raw(), 480);
267        // 25 fps, 40 ticks/frame → high byte 0xE7 (256-25), low 0x28.
268        let smpte = Division::from_raw(0xE728);
269        assert_eq!(
270            smpte,
271            Division::Smpte {
272                fps: 25,
273                ticks_per_frame: 0x28
274            }
275        );
276        assert_eq!(smpte.to_raw(), 0xE728);
277    }
278
279    #[test]
280    fn channel_data_lengths() {
281        assert_eq!(channel_data_len(0x90), Some(2)); // note on
282        assert_eq!(channel_data_len(0xC0), Some(1)); // program change
283        assert_eq!(channel_data_len(0xE3), Some(2)); // pitch bend, ch 3
284        assert_eq!(channel_data_len(0xF0), None); // system
285    }
286
287    #[test]
288    fn rejects_bad_magic() {
289        assert_eq!(read_smf(b"NOPExxxxxxxxxx"), Err(AudioError::MalformedAudio));
290    }
291
292    #[test]
293    fn rejects_unknown_format() {
294        // Valid MThd framing but format = 3.
295        let mut b = Vec::new();
296        b.extend_from_slice(b"MThd");
297        b.extend_from_slice(&6u32.to_be_bytes());
298        b.extend_from_slice(&3u16.to_be_bytes());
299        b.extend_from_slice(&0u16.to_be_bytes());
300        b.extend_from_slice(&96u16.to_be_bytes());
301        assert_eq!(read_smf(&b), Err(AudioError::UnsupportedFormat));
302    }
303
304    #[test]
305    fn running_status_expands() {
306        // MThd format 0, 1 track, division 96.
307        let mut b = Vec::new();
308        b.extend_from_slice(b"MThd");
309        b.extend_from_slice(&6u32.to_be_bytes());
310        b.extend_from_slice(&0u16.to_be_bytes());
311        b.extend_from_slice(&1u16.to_be_bytes());
312        b.extend_from_slice(&96u16.to_be_bytes());
313        // Track: note-on (explicit 0x90 3C 40), then running-status note-on (00 3E 40),
314        // then end-of-track.
315        let track_body: &[u8] = &[
316            0x00, 0x90, 0x3C, 0x40, // delta 0, note on C, vel 64
317            0x00, 0x3E, 0x40, // delta 0, running status note on D, vel 64
318            0x00, 0xFF, 0x2F, 0x00, // end of track
319        ];
320        b.extend_from_slice(b"MTrk");
321        b.extend_from_slice(&(track_body.len() as u32).to_be_bytes());
322        b.extend_from_slice(track_body);
323
324        let smf = read_smf(&b).unwrap();
325        assert_eq!(smf.tracks.len(), 1);
326        let evs = &smf.tracks[0].events;
327        assert_eq!(evs.len(), 3);
328        assert_eq!(
329            evs[0].event,
330            TrackEvent::Midi {
331                status: 0x90,
332                data: vec![0x3C, 0x40]
333            }
334        );
335        // Running status expanded to explicit 0x90.
336        assert_eq!(
337            evs[1].event,
338            TrackEvent::Midi {
339                status: 0x90,
340                data: vec![0x3E, 0x40]
341            }
342        );
343        assert_eq!(evs[2].event, TrackEvent::Meta(MetaEvent::EndOfTrack));
344    }
345}