Skip to main content

smpte_timecode/mtc/
encoder.rs

1use super::{
2    ALL_DEVICES, Direction, MtcError, QUARTER_FRAME, SUB_ID_FULL_FRAME, SUB_ID_TIME_CODE,
3    SYSEX_END, SYSEX_START, UNIVERSAL_REAL_TIME, rate_code,
4};
5use crate::{Ratio, Timecode};
6
7/// Each quarter-frame cycle spans two frames.
8const CYCLE_FRAMES: i64 = 2;
9
10/// Produces the quarter-frame messages of a running MIDI Time Code stream.
11///
12/// The encoder is an endless iterator of two-byte messages. Forward streams send pieces 0 to 7 and
13/// reverse streams 7 to 0. Each cycle of eight pieces carries one position, and the next cycle
14/// carries the position two frames further in the direction of travel, wrapping at midnight.
15///
16/// The encoder only builds bytes. Send one message every
17/// [`quarter_frame_interval`](MtcEncoder::quarter_frame_interval) on whatever clock and port
18/// the application uses, and send [`MtcEncoder::full_frame`] after a locate.
19///
20/// ```
21/// use smpte_timecode::{Direction, FrameRate, MtcEncoder, Timecode};
22///
23/// let start = Timecode::parse("01:02:03:04", FrameRate::FPS_25)?;
24/// let messages: Vec<[u8; 2]> = MtcEncoder::new(start, Direction::Forward)?.take(8).collect();
25/// assert_eq!(messages[0], [0xF1, 0x04]); // piece 0: frames, low nibble
26/// assert_eq!(messages[7], [0xF1, 0x72]); // piece 7: rate code 1 (25 fps), hours high bit
27/// # Ok::<(), Box<dyn std::error::Error>>(())
28/// ```
29#[derive(Clone, Debug)]
30pub struct MtcEncoder {
31    timecode: Timecode,
32    direction: Direction,
33    code: u8,
34    piece: u8,
35}
36
37impl MtcEncoder {
38    /// An encoder whose first cycle carries `start`.
39    ///
40    /// # Errors
41    ///
42    /// [`MtcError::NoRateCode`] when the rate of `start` has 48 or more frames per second.
43    pub const fn new(start: Timecode, direction: Direction) -> Result<Self, MtcError> {
44        let code = match rate_code(start.rate()) {
45            Ok(code) => code,
46            Err(error) => return Err(error),
47        };
48        let piece = match direction {
49            Direction::Forward => 0,
50            Direction::Reverse => 7,
51        };
52        Ok(Self {
53            timecode: start,
54            direction,
55            code,
56            piece,
57        })
58    }
59
60    /// The position the cycle in progress carries. A new cycle starts with the next message
61    /// after the last piece of the previous one.
62    pub const fn timecode(&self) -> Timecode {
63        self.timecode
64    }
65
66    /// The direction of the stream.
67    pub const fn direction(&self) -> Direction {
68        self.direction
69    }
70
71    /// The exact time between quarter frames in seconds: a quarter of a frame.
72    pub const fn quarter_frame_interval(&self) -> Ratio {
73        let fps = self.timecode.rate().frames_per_second();
74        Ratio::reduced(fps.denom(), fps.numer() * 4)
75    }
76
77    /// The full-frame SysEx message for `timecode`, addressed to all devices.
78    ///
79    /// # Errors
80    ///
81    /// [`MtcError::NoRateCode`] when the rate of `timecode` has 48 or more frames per second.
82    pub const fn full_frame(timecode: Timecode) -> Result<[u8; 10], MtcError> {
83        let code = match rate_code(timecode.rate()) {
84            Ok(code) => code,
85            Err(error) => return Err(error),
86        };
87        let fields = timecode.fields();
88        Ok([
89            SYSEX_START,
90            UNIVERSAL_REAL_TIME,
91            ALL_DEVICES,
92            SUB_ID_TIME_CODE,
93            SUB_ID_FULL_FRAME,
94            (code << 5) | fields.hours,
95            fields.minutes,
96            fields.seconds,
97            fields.frames,
98            SYSEX_END,
99        ])
100    }
101}
102
103impl Iterator for MtcEncoder {
104    type Item = [u8; 2];
105
106    fn next(&mut self) -> Option<Self::Item> {
107        let fields = self.timecode.fields();
108        let value = match self.piece {
109            0 => fields.frames & 0x0F,
110            1 => fields.frames >> 4,
111            2 => fields.seconds & 0x0F,
112            3 => fields.seconds >> 4,
113            4 => fields.minutes & 0x0F,
114            5 => fields.minutes >> 4,
115            6 => fields.hours & 0x0F,
116            _ => (fields.hours >> 4) | (self.code << 1),
117        };
118        let message = [QUARTER_FRAME, (self.piece << 4) | value];
119        match (self.direction, self.piece) {
120            (Direction::Forward, 7) => {
121                self.piece = 0;
122                self.timecode = self.timecode.wrapping_add_frames(CYCLE_FRAMES);
123            }
124            (Direction::Forward, _) => self.piece += 1,
125            (Direction::Reverse, 0) => {
126                self.piece = 7;
127                self.timecode = self.timecode.wrapping_add_frames(-CYCLE_FRAMES);
128            }
129            (Direction::Reverse, _) => self.piece -= 1,
130        }
131        Some(message)
132    }
133
134    fn size_hint(&self) -> (usize, Option<usize>) {
135        (usize::MAX, None)
136    }
137}