Skip to main content

qualia_audio/midi/sync/
mmc.rs

1//! MIDI Machine Control (MMC) — build and parse transport commands.
2//!
3//! MMC commands ride inside a Universal Real-Time SysEx:
4//! `F0 7F <device> 06 <command…> F7`, where `06` is the MMC sub-ID. This module
5//! handles the common transport verbs — Stop, Play, Deferred Play, Fast Forward,
6//! Rewind, Pause — plus **Locate (target)**, which carries a standard-time field
7//! `44 06 01 hr mn sc fr sf` (the `hr` byte packs a 2-bit frame-rate code in bits
8//! 5–6, per SMPTE). Messages are built into a caller-supplied buffer and parsed
9//! from a byte slice, allocation-free.
10
11use crate::types::AudioError;
12
13use super::mtc::{FrameRate, Timecode};
14
15const SYSEX_START: u8 = 0xF0;
16const SYSEX_END: u8 = 0xF7;
17const UNIVERSAL_REALTIME: u8 = 0x7F;
18const MMC_SUB_ID: u8 = 0x06;
19
20const CMD_STOP: u8 = 0x01;
21const CMD_PLAY: u8 = 0x02;
22const CMD_DEFERRED_PLAY: u8 = 0x03;
23const CMD_FAST_FORWARD: u8 = 0x04;
24const CMD_REWIND: u8 = 0x05;
25const CMD_PAUSE: u8 = 0x09;
26const CMD_LOCATE: u8 = 0x44;
27
28/// A parsed / to-be-built MMC transport command.
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub enum MmcCommand {
31    /// Stop transport.
32    Stop,
33    /// Start playback.
34    Play,
35    /// Deferred play (play at the next locate/edit point).
36    DeferredPlay,
37    /// Fast forward.
38    FastForward,
39    /// Rewind.
40    Rewind,
41    /// Pause.
42    Pause,
43    /// Locate to a target timecode.
44    Locate(Timecode),
45}
46
47/// Build an MMC message for `device` and `command` into `out`, returning the
48/// number of bytes written. `device` is a 7-bit device id (`0x7F` = all).
49///
50/// Errors with [`AudioError::OutputBufferTooSmall`] if `out` is too short, or
51/// [`AudioError::InvalidParameter`] if `device` has its high bit set.
52pub fn build(device: u8, command: MmcCommand, out: &mut [u8]) -> Result<usize, AudioError> {
53    if device & 0x80 != 0 {
54        return Err(AudioError::InvalidParameter);
55    }
56    match command {
57        MmcCommand::Locate(tc) => {
58            const LEN: usize = 12; // F0 7F dev 06 44 06 01 hr mn sc fr F7
59            if out.len() < LEN {
60                return Err(AudioError::OutputBufferTooSmall);
61            }
62            out[0] = SYSEX_START;
63            out[1] = UNIVERSAL_REALTIME;
64            out[2] = device;
65            out[3] = MMC_SUB_ID;
66            out[4] = CMD_LOCATE;
67            out[5] = 0x06; // length of the information field
68            out[6] = 0x01; // "TARGET" sub-command
69            out[7] = (tc.hours & 0x1F) | (tc.rate.code() << 5); // 0rrhhhhh
70            out[8] = tc.minutes & 0x3F;
71            out[9] = tc.seconds & 0x3F;
72            out[10] = tc.frames & 0x1F;
73            out[11] = SYSEX_END;
74            Ok(LEN)
75        }
76        simple => {
77            const LEN: usize = 6; // F0 7F dev 06 cmd F7
78            if out.len() < LEN {
79                return Err(AudioError::OutputBufferTooSmall);
80            }
81            out[0] = SYSEX_START;
82            out[1] = UNIVERSAL_REALTIME;
83            out[2] = device;
84            out[3] = MMC_SUB_ID;
85            out[4] = simple_command_byte(simple);
86            out[5] = SYSEX_END;
87            Ok(LEN)
88        }
89    }
90}
91
92#[inline]
93fn simple_command_byte(cmd: MmcCommand) -> u8 {
94    match cmd {
95        MmcCommand::Stop => CMD_STOP,
96        MmcCommand::Play => CMD_PLAY,
97        MmcCommand::DeferredPlay => CMD_DEFERRED_PLAY,
98        MmcCommand::FastForward => CMD_FAST_FORWARD,
99        MmcCommand::Rewind => CMD_REWIND,
100        MmcCommand::Pause => CMD_PAUSE,
101        MmcCommand::Locate(_) => CMD_LOCATE, // handled separately in build()
102    }
103}
104
105/// Parse an MMC SysEx message, returning `(device, command)`.
106///
107/// Validates the SysEx envelope and MMC sub-ID. Errors with
108/// [`AudioError::InvalidParameter`] on any malformed / unrecognized message.
109pub fn parse(msg: &[u8]) -> Result<(u8, MmcCommand), AudioError> {
110    if msg.len() < 6
111        || msg[0] != SYSEX_START
112        || msg[1] != UNIVERSAL_REALTIME
113        || msg[3] != MMC_SUB_ID
114        || msg[msg.len() - 1] != SYSEX_END
115    {
116        return Err(AudioError::InvalidParameter);
117    }
118    let device = msg[2];
119    let command = match msg[4] {
120        CMD_STOP => MmcCommand::Stop,
121        CMD_PLAY => MmcCommand::Play,
122        CMD_DEFERRED_PLAY => MmcCommand::DeferredPlay,
123        CMD_FAST_FORWARD => MmcCommand::FastForward,
124        CMD_REWIND => MmcCommand::Rewind,
125        CMD_PAUSE => MmcCommand::Pause,
126        CMD_LOCATE => {
127            // F0 7F dev 06 44 06 01 hr mn sc fr F7  (len 12)
128            if msg.len() != 12 || msg[5] != 0x06 || msg[6] != 0x01 {
129                return Err(AudioError::InvalidParameter);
130            }
131            let rate = FrameRate::from_code(msg[7] >> 5);
132            let hours = msg[7] & 0x1F;
133            let minutes = msg[8] & 0x3F;
134            let seconds = msg[9] & 0x3F;
135            let frames = msg[10] & 0x1F;
136            MmcCommand::Locate(Timecode::new(hours, minutes, seconds, frames, rate)?)
137        }
138        _ => return Err(AudioError::InvalidParameter),
139    };
140    Ok((device, command))
141}
142
143#[cfg(test)]
144mod tests {
145    use super::*;
146
147    #[test]
148    fn simple_commands_round_trip() {
149        let cmds = [
150            MmcCommand::Stop,
151            MmcCommand::Play,
152            MmcCommand::DeferredPlay,
153            MmcCommand::FastForward,
154            MmcCommand::Rewind,
155            MmcCommand::Pause,
156        ];
157        let mut buf = [0u8; 16];
158        for &cmd in &cmds {
159            let n = build(0x7F, cmd, &mut buf).unwrap();
160            assert_eq!(parse(&buf[..n]).unwrap(), (0x7F, cmd));
161        }
162    }
163
164    #[test]
165    fn play_bytes_are_canonical() {
166        let mut buf = [0u8; 6];
167        let n = build(0x7F, MmcCommand::Play, &mut buf).unwrap();
168        assert_eq!(&buf[..n], &[0xF0, 0x7F, 0x7F, 0x06, 0x02, 0xF7]);
169    }
170
171    #[test]
172    fn locate_round_trip() {
173        let tc = Timecode::new(1, 23, 45, 12, FrameRate::Fps25).unwrap();
174        let mut buf = [0u8; 16];
175        let n = build(0x03, MmcCommand::Locate(tc), &mut buf).unwrap();
176        assert_eq!(parse(&buf[..n]).unwrap(), (0x03, MmcCommand::Locate(tc)));
177    }
178
179    #[test]
180    fn rejects_truncated_and_bad_envelope() {
181        assert!(parse(&[0xF0, 0x7F, 0x00]).is_err());
182        let mut buf = [0u8; 6];
183        build(0x7F, MmcCommand::Stop, &mut buf).unwrap();
184        buf[0] = 0x00; // corrupt SysEx start
185        assert!(parse(&buf).is_err());
186    }
187
188    #[test]
189    fn buffer_too_small() {
190        let mut small = [0u8; 3];
191        assert_eq!(
192            build(0x7F, MmcCommand::Stop, &mut small),
193            Err(AudioError::OutputBufferTooSmall)
194        );
195    }
196}