Skip to main content

qualia_audio/midi/sync/
mtc.rs

1//! MIDI Time Code (MTC) — quarter-frame encode/decode of an `hh:mm:ss:ff`
2//! timecode.
3//!
4//! A full SMPTE timecode is streamed as eight *quarter-frame* messages, each a
5//! `0xF1` status byte followed by one data byte of the form `0iiidddd`: the
6//! upper three bits `iii` select which of the eight nibbles (piece 0..=7) is
7//! carried in the lower four bits `dddd`. Reassembling all eight pieces yields
8//! the frame; the top piece also carries the high hour bit and a 2-bit frame-rate
9//! code. This module encodes a [`Timecode`] to the eight data bytes and decodes
10//! them back, allocation-free.
11
12use crate::types::AudioError;
13
14/// SMPTE frame rate, encoded in the 2-bit rate field of MTC piece 7.
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum FrameRate {
17    /// 24 fps (film).
18    Fps24,
19    /// 25 fps (EBU / PAL).
20    Fps25,
21    /// 29.97 fps drop-frame (NTSC).
22    Fps2997Drop,
23    /// 30 fps (non-drop).
24    Fps30,
25}
26
27impl FrameRate {
28    /// The 2-bit code as it appears in MTC / SMPTE hour bytes.
29    #[inline]
30    pub const fn code(self) -> u8 {
31        match self {
32            FrameRate::Fps24 => 0,
33            FrameRate::Fps25 => 1,
34            FrameRate::Fps2997Drop => 2,
35            FrameRate::Fps30 => 3,
36        }
37    }
38
39    /// Decode a 2-bit rate code.
40    #[inline]
41    pub const fn from_code(code: u8) -> FrameRate {
42        match code & 0b11 {
43            0 => FrameRate::Fps24,
44            1 => FrameRate::Fps25,
45            2 => FrameRate::Fps2997Drop,
46            _ => FrameRate::Fps30,
47        }
48    }
49
50    /// The nominal upper frame count for range validation (max frame index + 1).
51    #[inline]
52    pub const fn frames_per_second(self) -> u8 {
53        match self {
54            FrameRate::Fps24 => 24,
55            FrameRate::Fps25 => 25,
56            FrameRate::Fps2997Drop | FrameRate::Fps30 => 30,
57        }
58    }
59}
60
61/// An SMPTE / MTC timecode: `hours:minutes:seconds:frames` at a [`FrameRate`].
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63pub struct Timecode {
64    /// Hours, 0..=23.
65    pub hours: u8,
66    /// Minutes, 0..=59.
67    pub minutes: u8,
68    /// Seconds, 0..=59.
69    pub seconds: u8,
70    /// Frames, 0..=(fps-1).
71    pub frames: u8,
72    /// Frame rate.
73    pub rate: FrameRate,
74}
75
76impl Timecode {
77    /// Construct and validate field ranges against the frame rate.
78    pub fn new(
79        hours: u8,
80        minutes: u8,
81        seconds: u8,
82        frames: u8,
83        rate: FrameRate,
84    ) -> Result<Self, AudioError> {
85        if hours > 23 || minutes > 59 || seconds > 59 || frames >= rate.frames_per_second() {
86            return Err(AudioError::InvalidParameter);
87        }
88        Ok(Self {
89            hours,
90            minutes,
91            seconds,
92            frames,
93            rate,
94        })
95    }
96}
97
98/// Encode a timecode into the eight MTC quarter-frame *data bytes* (the byte
99/// that follows each `0xF1` status). Element `i` has the form `(i << 4) | nibble`.
100pub fn encode_quarter_frames(tc: Timecode) -> [u8; 8] {
101    let nibbles = [
102        tc.frames & 0x0F,                                 // 0: frame LSN
103        (tc.frames >> 4) & 0x0F,                          // 1: frame MSN
104        tc.seconds & 0x0F,                                // 2: seconds LSN
105        (tc.seconds >> 4) & 0x0F,                         // 3: seconds MSN
106        tc.minutes & 0x0F,                                // 4: minutes LSN
107        (tc.minutes >> 4) & 0x0F,                         // 5: minutes MSN
108        tc.hours & 0x0F,                                  // 6: hours LSN
109        ((tc.hours >> 4) & 0x01) | (tc.rate.code() << 1), // 7: hours MSN + rate
110    ];
111    let mut out = [0u8; 8];
112    let mut i = 0;
113    while i < 8 {
114        out[i] = ((i as u8) << 4) | (nibbles[i] & 0x0F);
115        i += 1;
116    }
117    out
118}
119
120/// Decode eight MTC quarter-frame data bytes back into a [`Timecode`].
121///
122/// Each byte must carry its own piece index in the upper nibble (0..=7) and the
123/// eight indices must all be present exactly once. Errors on a malformed set or
124/// out-of-range reconstructed fields.
125pub fn decode_quarter_frames(data: &[u8; 8]) -> Result<Timecode, AudioError> {
126    let mut nibbles = [0u8; 8];
127    let mut seen = [false; 8];
128    for &b in data.iter() {
129        let idx = (b >> 4) as usize;
130        if idx >= 8 || seen[idx] {
131            return Err(AudioError::InvalidParameter);
132        }
133        seen[idx] = true;
134        nibbles[idx] = b & 0x0F;
135    }
136    if seen.iter().any(|&s| !s) {
137        return Err(AudioError::InvalidParameter);
138    }
139    let frames = nibbles[0] | (nibbles[1] << 4);
140    let seconds = nibbles[2] | (nibbles[3] << 4);
141    let minutes = nibbles[4] | (nibbles[5] << 4);
142    let rate = FrameRate::from_code(nibbles[7] >> 1);
143    let hours = nibbles[6] | ((nibbles[7] & 0x01) << 4);
144    Timecode::new(hours, minutes, seconds, frames, rate)
145}
146
147#[cfg(test)]
148mod tests {
149    use super::*;
150
151    #[test]
152    fn golden_round_trip() {
153        let tc = Timecode::new(17, 42, 53, 12, FrameRate::Fps25).unwrap();
154        let bytes = encode_quarter_frames(tc);
155        let back = decode_quarter_frames(&bytes).unwrap();
156        assert_eq!(tc, back);
157    }
158
159    #[test]
160    fn round_trip_hour_high_bit() {
161        // hours 23 needs the high bit in piece 7.
162        let tc = Timecode::new(23, 59, 59, 29, FrameRate::Fps30).unwrap();
163        let bytes = encode_quarter_frames(tc);
164        assert_eq!(decode_quarter_frames(&bytes).unwrap(), tc);
165    }
166
167    #[test]
168    fn rate_preserved() {
169        for rate in [
170            FrameRate::Fps24,
171            FrameRate::Fps25,
172            FrameRate::Fps2997Drop,
173            FrameRate::Fps30,
174        ] {
175            let tc = Timecode::new(1, 2, 3, 4, rate).unwrap();
176            assert_eq!(
177                decode_quarter_frames(&encode_quarter_frames(tc))
178                    .unwrap()
179                    .rate,
180                rate
181            );
182        }
183    }
184
185    #[test]
186    fn rejects_duplicate_piece() {
187        let mut bytes = encode_quarter_frames(Timecode::new(1, 2, 3, 4, FrameRate::Fps24).unwrap());
188        bytes[1] = bytes[0]; // duplicate piece 0
189        assert_eq!(
190            decode_quarter_frames(&bytes),
191            Err(AudioError::InvalidParameter)
192        );
193    }
194
195    #[test]
196    fn rejects_out_of_range_field() {
197        assert!(Timecode::new(24, 0, 0, 0, FrameRate::Fps24).is_err());
198        assert!(Timecode::new(0, 0, 0, 24, FrameRate::Fps24).is_err());
199    }
200}