moont 1.0.0

Roland CM-32L synthesizer emulator
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
// Copyright (C) 2021-2026 Geoff Hill <geoff@geoffhill.org>
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 2.1 of the License, or (at
// your option) any later version. Read COPYING.LESSER.txt for details.

//! Minimal Standard MIDI File (SMF) parser.
//!
//! Parses format 0 and format 1 .mid files into a flat list of
//! timestamped MIDI events suitable for playback through the CM-32L.

use alloc::vec::Vec;
use core::{error, fmt};

const DEFAULT_TEMPO: u64 = 500_000; // 120 BPM in microseconds per quarter note

/// A timestamped MIDI event with time in samples at 32 kHz.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Event {
    /// A packed MIDI channel message.
    Msg {
        /// Event time in rendered sample frames at 32 kHz.
        time: u32,
        /// Packed MIDI message in the same `u32` format used by [`crate::Synth`].
        msg: u32,
    },
    /// A System Exclusive message.
    Sysex {
        /// Event time in rendered sample frames at 32 kHz.
        time: u32,
        /// Complete SysEx payload, including the leading `0xF0`.
        data: Vec<u8>,
    },
}

impl Event {
    /// Returns the event timestamp in rendered sample frames at 32 kHz.
    pub fn time(&self) -> u32 {
        match self {
            Event::Msg { time, .. } => *time,
            Event::Sysex { time, .. } => *time,
        }
    }
}

/// Errors returned when parsing a Standard MIDI File.
#[non_exhaustive]
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum ParseError {
    /// The `MThd` header chunk is missing or malformed.
    BadHeader,
    /// The file uses an SMF format other than 0 or 1.
    UnsupportedFormat(u16),
    /// The file uses SMPTE time division instead of ticks-per-quarter-note.
    UnsupportedDivision,
    /// A track chunk is missing, malformed, or contains an invalid event stream.
    BadTrack,
    /// The input ended before a complete SMF structure or event could be read.
    UnexpectedEof,
}

impl error::Error for ParseError {}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ParseError::BadHeader => f.write_str("invalid SMF header"),
            ParseError::UnsupportedFormat(n) => {
                write!(f, "unsupported SMF format {n}")
            }
            ParseError::UnsupportedDivision => {
                f.write_str("SMPTE time division not supported")
            }
            ParseError::BadTrack => f.write_str("invalid track chunk"),
            ParseError::UnexpectedEof => f.write_str("unexpected end of data"),
        }
    }
}

struct Reader<'a> {
    data: &'a [u8],
    pos: usize,
}

impl<'a> Reader<'a> {
    fn new(data: &'a [u8]) -> Self {
        Reader { data, pos: 0 }
    }

    fn remaining(&self) -> usize {
        self.data.len() - self.pos
    }

    fn read_u8(&mut self) -> Result<u8, ParseError> {
        if self.pos >= self.data.len() {
            return Err(ParseError::UnexpectedEof);
        }
        let b = self.data[self.pos];
        self.pos += 1;
        Ok(b)
    }

    fn read_u16(&mut self) -> Result<u16, ParseError> {
        if self.remaining() < 2 {
            return Err(ParseError::UnexpectedEof);
        }
        let hi = self.data[self.pos] as u16;
        let lo = self.data[self.pos + 1] as u16;
        self.pos += 2;
        Ok((hi << 8) | lo)
    }

    fn read_u32(&mut self) -> Result<u32, ParseError> {
        if self.remaining() < 4 {
            return Err(ParseError::UnexpectedEof);
        }
        let a = self.data[self.pos] as u32;
        let b = self.data[self.pos + 1] as u32;
        let c = self.data[self.pos + 2] as u32;
        let d = self.data[self.pos + 3] as u32;
        self.pos += 4;
        Ok((a << 24) | (b << 16) | (c << 8) | d)
    }

    fn read_bytes(&mut self, n: usize) -> Result<&'a [u8], ParseError> {
        if self.remaining() < n {
            return Err(ParseError::UnexpectedEof);
        }
        let slice = &self.data[self.pos..self.pos + n];
        self.pos += n;
        Ok(slice)
    }

    fn read_vlq(&mut self) -> Result<u32, ParseError> {
        let mut val: u32 = 0;
        for _ in 0..4 {
            let b = self.read_u8()?;
            val = (val << 7) | (b & 0x7F) as u32;
            if b & 0x80 == 0 {
                return Ok(val);
            }
        }
        Err(ParseError::UnexpectedEof)
    }
}

/// Ticked event from a single track, before timing conversion.
struct RawEvent {
    tick: u64,
    kind: RawEventKind,
}

enum RawEventKind {
    Msg(u32),
    Sysex(Vec<u8>),
    Tempo(u64),
}

fn msg_len(status: u8) -> usize {
    match status & 0xF0 {
        0x80 | 0x90 | 0xA0 | 0xB0 | 0xE0 => 2,
        0xC0 | 0xD0 => 1,
        _ => 0,
    }
}

fn parse_track(data: &[u8]) -> Result<Vec<RawEvent>, ParseError> {
    let mut r = Reader::new(data);
    let mut events = Vec::new();
    let mut tick: u64 = 0;
    let mut running_status: u8 = 0;

    while r.remaining() > 0 {
        let delta = r.read_vlq()? as u64;
        tick += delta;

        let peek = r.read_u8()?;

        if peek == 0xFF {
            // Meta event.
            let meta_type = r.read_u8()?;
            let len = r.read_vlq()? as usize;
            let body = r.read_bytes(len)?;
            if meta_type == 0x51 && len == 3 {
                let tempo = (body[0] as u64) << 16
                    | (body[1] as u64) << 8
                    | body[2] as u64;
                events.push(RawEvent {
                    tick,
                    kind: RawEventKind::Tempo(tempo),
                });
            }
            // All other meta events ignored.
        } else if peek == 0xF0 || peek == 0xF7 {
            // SysEx event.
            let len = r.read_vlq()? as usize;
            let body = r.read_bytes(len)?;
            let mut sysex = Vec::with_capacity(1 + body.len());
            sysex.push(0xF0);
            sysex.extend_from_slice(body);
            events.push(RawEvent {
                tick,
                kind: RawEventKind::Sysex(sysex),
            });
        } else {
            // Channel message (possibly with running status).
            let status;
            let first_data;
            if peek & 0x80 != 0 {
                status = peek;
                running_status = status;
                first_data = r.read_u8()?;
            } else {
                status = running_status;
                first_data = peek;
            }

            let n = msg_len(status);
            if n == 0 {
                return Err(ParseError::BadTrack);
            }

            let mut msg = status as u32 | (first_data as u32) << 8;
            if n == 2 {
                let second = r.read_u8()?;
                msg |= (second as u32) << 16;
            }

            events.push(RawEvent {
                tick,
                kind: RawEventKind::Msg(msg),
            });
        }
    }

    Ok(events)
}

/// Parses a Standard MIDI File and returns timestamped events.
///
/// Supports format 0 (single track) and format 1 (multi-track).
/// Times are converted to samples at 32 kHz using tempo information
/// from the file (defaulting to 120 BPM if no tempo event is present).
pub fn parse(data: &[u8]) -> Result<Vec<Event>, ParseError> {
    let mut r = Reader::new(data);

    // Header chunk: "MThd" + 6-byte payload.
    let magic = r.read_u32()?;
    if magic != 0x4D546864 {
        return Err(ParseError::BadHeader);
    }
    let header_len = r.read_u32()?;
    if header_len < 6 {
        return Err(ParseError::BadHeader);
    }
    let format = r.read_u16()?;
    let ntracks = r.read_u16()?;
    let division = r.read_u16()?;

    if format > 1 {
        return Err(ParseError::UnsupportedFormat(format));
    }
    if division & 0x8000 != 0 {
        return Err(ParseError::UnsupportedDivision);
    }
    let tpqn = division as u64;

    // Skip any extra header bytes.
    if header_len > 6 {
        r.read_bytes((header_len - 6) as usize)?;
    }

    // Parse all tracks.
    let mut all_events: Vec<RawEvent> = Vec::new();

    for _ in 0..ntracks {
        let chunk_magic = r.read_u32()?;
        let chunk_len = r.read_u32()? as usize;
        if chunk_magic != 0x4D54726B {
            // Not "MTrk" -- skip unknown chunk.
            r.read_bytes(chunk_len)?;
            continue;
        }
        let track_data = r.read_bytes(chunk_len)?;
        let mut track_events = parse_track(track_data)?;
        all_events.append(&mut track_events);
    }

    // Sort by tick (stable sort preserves order within same tick).
    all_events.sort_by_key(|e| e.tick);

    // Convert ticks to samples using tempo map.
    let mut tempo = DEFAULT_TEMPO;
    let mut last_tick: u64 = 0;
    let mut last_sample: u64 = 0;
    let mut events = Vec::new();

    for raw in &all_events {
        let dt = raw.tick - last_tick;
        let samples = dt * tempo * 32 / (tpqn * 1000);
        last_sample += samples as u64;
        last_tick = raw.tick;

        let time = last_sample.min(u32::MAX as u64) as u32;
        match &raw.kind {
            RawEventKind::Tempo(t) => {
                tempo = *t;
            }
            RawEventKind::Msg(msg) => {
                events.push(Event::Msg { time, msg: *msg });
            }
            RawEventKind::Sysex(data) => {
                events.push(Event::Sysex {
                    time,
                    data: data.clone(),
                });
            }
        }
    }

    Ok(events)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn make_header(format: u16, ntracks: u16, division: u16) -> Vec<u8> {
        let mut h = Vec::new();
        h.extend_from_slice(b"MThd");
        h.extend_from_slice(&6u32.to_be_bytes());
        h.extend_from_slice(&format.to_be_bytes());
        h.extend_from_slice(&ntracks.to_be_bytes());
        h.extend_from_slice(&division.to_be_bytes());
        h
    }

    fn make_track(events: &[u8]) -> Vec<u8> {
        let mut t = Vec::new();
        t.extend_from_slice(b"MTrk");
        t.extend_from_slice(&(events.len() as u32).to_be_bytes());
        t.extend_from_slice(events);
        t
    }

    #[test]
    fn test_single_note() {
        let mut data = make_header(0, 1, 480);
        // delta=0, note-on ch0 C4 vel=100.
        // delta=480, note-off ch0 C4 vel=0.
        let track = [
            0x00, 0x90, 0x3C, 0x64, // delta=0, note on
            0x83, 0x60, 0x80, 0x3C, 0x00, // delta=480, note off
        ];
        data.extend_from_slice(&make_track(&track));

        let events = parse(&data).unwrap();
        assert_eq!(events.len(), 2);

        assert!(
            matches!(&events[0], Event::Msg { time: 0, msg } if *msg == 0x643C90)
        );

        // 480 ticks at 480 tpqn = 1 quarter note.
        // Default tempo 500000us/qn -> 1 qn = 0.5s = 16000 samples.
        assert!(matches!(&events[1], Event::Msg { time: 16000, .. }));
    }

    #[test]
    fn test_running_status() {
        let mut data = make_header(0, 1, 96);
        let track = [
            0x00, 0x90, 0x3C, 0x64, // note on C4
            0x60, 0x3E, 0x64, // delta=96, running status, note on D4
        ];
        data.extend_from_slice(&make_track(&track));

        let events = parse(&data).unwrap();
        assert_eq!(events.len(), 2);
        assert!(
            matches!(&events[1], Event::Msg { msg, .. } if *msg == 0x643E90)
        );
    }

    #[test]
    fn test_tempo_change() {
        let mut data = make_header(0, 1, 480);
        // Tempo = 1000000us/qn (60 BPM), then a note at tick 480.
        let track = [
            0x00, 0xFF, 0x51, 0x03, 0x0F, 0x42, 0x40, // tempo 1000000
            0x83, 0x60, 0x90, 0x3C, 0x64, // delta=480, note on
        ];
        data.extend_from_slice(&make_track(&track));

        let events = parse(&data).unwrap();
        assert_eq!(events.len(), 1);

        // 480 ticks at 1000000us/qn, 480 tpqn = 1 qn = 1s = 32000 samples.
        assert!(matches!(&events[0], Event::Msg { time: 32000, .. }));
    }

    #[test]
    fn test_sysex() {
        let mut data = make_header(0, 1, 480);
        // SysEx: F0 41 10 16 12 ... F7.
        let track = [0x00, 0xF0, 0x05, 0x41, 0x10, 0x16, 0x12, 0xF7];
        data.extend_from_slice(&make_track(&track));

        let events = parse(&data).unwrap();
        assert_eq!(events.len(), 1);
        match &events[0] {
            Event::Sysex { data, .. } => {
                assert_eq!(data[0], 0xF0);
                assert_eq!(data[1], 0x41);
            }
            _ => panic!("expected sysex"),
        }
    }

    #[test]
    fn test_format2_rejected() {
        let data = make_header(2, 1, 480);
        assert!(parse(&data).is_err());
    }
}