Skip to main content

smpte_timecode/mtc/
decoder.rs

1use core::time::Duration;
2
3use super::{
4    Direction, Motion, MtcError, QUARTER_FRAME, SUB_ID_FULL_FRAME, SUB_ID_TIME_CODE, SYSEX_END,
5    SYSEX_START, UNIVERSAL_REAL_TIME, stream_rate,
6};
7use crate::{Fields, FrameRate, Timecode};
8
9/// Every quarter-frame piece, one bit each.
10const ALL_PIECES: u8 = 0xFF;
11/// Forward cycles complete two frames after the frame they encode (RFC 6295 B.4).
12const FORWARD_CYCLE_LATENCY: i64 = 2;
13
14/// A position decoded from MIDI Time Code.
15#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
16pub struct MtcEvent {
17    /// The position. Forward positions are already compensated for the cycle latency.
18    pub timecode: Timecode,
19    /// How the position was reached.
20    pub motion: Motion,
21    /// The time the completing message was fed, as passed to [`MtcDecoder::feed`].
22    pub at: Duration,
23}
24
25/// Whether a decoder is following a timecode source.
26#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
27pub enum LockState {
28    /// No position has been decoded since creation or the last [`MtcDecoder::reset`].
29    Unlocked,
30    /// The last position is recent. Holds the motion that produced it.
31    Locked(Motion),
32    /// The last position is older than the stale limit, as when the source stops sending.
33    Stale,
34}
35
36/// Turns MIDI Time Code messages into checked positions.
37///
38/// Feed every complete MIDI message with the time it arrived. Quarter frames form a position only
39/// when all eight pieces arrive consecutively in one direction, so a locate, a lost or repeated
40/// piece, a direction change or joining mid-cycle never yields a position that mixes two cycles.
41/// Full frames reset the cycle and yield a [`Motion::Located`] position.
42///
43/// Times are durations since any fixed instant the caller chooses, such as a MIDI backend's
44/// timestamp or a monotonic clock. Use one clock per decoder. The decoder never reads a clock,
45/// allocates or blocks, so it can run inside a MIDI callback.
46///
47/// ```
48/// use core::time::Duration;
49/// use smpte_timecode::{Direction, FrameRate, Motion, MtcDecoder, MtcEncoder, Timecode};
50///
51/// let start = Timecode::parse("01:00:00:00", FrameRate::FPS_25)?;
52/// let mut encoder = MtcEncoder::new(start, Direction::Forward)?;
53/// let mut decoder = MtcDecoder::new();
54/// let mut events = Vec::new();
55/// for (index, message) in encoder.by_ref().take(8).enumerate() {
56///     let at = Duration::from_millis(10 * index as u64);
57///     events.extend(decoder.feed(&message, at)?);
58/// }
59/// assert_eq!(events.len(), 1);
60/// assert_eq!(events[0].timecode.to_string(), "01:00:00:02");
61/// assert_eq!(events[0].motion, Motion::Forward);
62/// # Ok::<(), Box<dyn std::error::Error>>(())
63/// ```
64#[derive(Clone, Debug)]
65pub struct MtcDecoder {
66    quarter_frame_timeout: Duration,
67    stale_after: Duration,
68    rate_hint: Option<FrameRate>,
69    pieces: [u8; 8],
70    received: u8,
71    last_piece: Option<(u8, Duration)>,
72    direction: Option<Direction>,
73    last_event: Option<(Motion, Duration)>,
74}
75
76impl MtcDecoder {
77    /// The default longest gap between consecutive quarter frames of one cycle.
78    pub const DEFAULT_QUARTER_FRAME_TIMEOUT: Duration = Duration::from_millis(500);
79    /// The default age after which the last position is [`LockState::Stale`].
80    pub const DEFAULT_STALE_AFTER: Duration = Duration::from_secs(1);
81
82    /// A decoder with the default limits and no rate hint.
83    pub const fn new() -> Self {
84        Self {
85            quarter_frame_timeout: Self::DEFAULT_QUARTER_FRAME_TIMEOUT,
86            stale_after: Self::DEFAULT_STALE_AFTER,
87            rate_hint: None,
88            pieces: [0; 8],
89            received: 0,
90            last_piece: None,
91            direction: None,
92            last_event: None,
93        }
94    }
95
96    /// Sets the longest gap between consecutive quarter frames that still continues a cycle.
97    /// A longer gap starts a new cycle.
98    #[must_use]
99    pub const fn with_quarter_frame_timeout(mut self, timeout: Duration) -> Self {
100        self.quarter_frame_timeout = timeout;
101        self
102    }
103
104    /// Sets the age after which [`MtcDecoder::lock_state`] reports [`LockState::Stale`].
105    #[must_use]
106    pub const fn with_stale_after(mut self, stale_after: Duration) -> Self {
107        self.stale_after = stale_after;
108        self
109    }
110
111    /// Sets the rate the source is known to run at, such as a DAW session rate.
112    ///
113    /// The two-bit rate code cannot tell 29.97 from 30, 23.976 from 24, or mark 30 as drop-frame.
114    /// While the hint has the same nominal frame count as the incoming code, positions use the
115    /// hint. A hint at twice the code's count is a session that sends half-count MTC, as Pro Tools
116    /// sends 48, 50, 59.94 and 60 sessions with the codes of 24, 25 and 30: positions then use the
117    /// half rate with the hint's 1000/1001 factor and drop-frame counting, such as 29.97 for
118    /// 59.94, 29.97 DF for 59.94 DF, 23.976 for 47.952 and 30 DF for 60 DF. They keep the
119    /// half-count labels the stream carries; converting them to labels at the session rate is the
120    /// caller's. Otherwise the stream wins, because reading its frames at another count would
121    /// shift positions or reject frame numbers the hint cannot hold.
122    pub const fn set_rate_hint(&mut self, hint: Option<FrameRate>) {
123        self.rate_hint = hint;
124    }
125
126    /// Decodes one complete MIDI message received at `at`.
127    ///
128    /// Returns a position when the message completes a quarter-frame cycle or is a full frame,
129    /// and `None` for a partial cycle or a message that is not MIDI Time Code.
130    ///
131    /// # Errors
132    ///
133    /// [`MtcError::MalformedMessage`] for a quarter frame or full frame with the wrong shape, and
134    /// [`MtcError::InvalidTimecode`] when a complete message names a position that does not exist.
135    /// A malformed message discards the partial cycle. An invalid complete position consumes the
136    /// cycle as a valid one would. Neither error replaces or refreshes the last valid position.
137    pub fn feed(&mut self, message: &[u8], at: Duration) -> Result<Option<MtcEvent>, MtcError> {
138        match message {
139            [QUARTER_FRAME, data] if data & 0x80 == 0 => self.quarter_frame(*data, at),
140            [QUARTER_FRAME, ..] => {
141                self.clear_cycle();
142                Err(MtcError::MalformedMessage)
143            }
144            [
145                SYSEX_START,
146                UNIVERSAL_REAL_TIME,
147                _,
148                SUB_ID_TIME_CODE,
149                SUB_ID_FULL_FRAME,
150                ..,
151            ] => self.full_frame(message, at).map(Some),
152            _ => Ok(None),
153        }
154    }
155
156    /// Whether the decoder is following a source at `now`, on the same clock as
157    /// [`MtcDecoder::feed`].
158    pub const fn lock_state(&self, now: Duration) -> LockState {
159        match self.last_event {
160            None => LockState::Unlocked,
161            Some((_, at)) if now.saturating_sub(at).as_nanos() > self.stale_after.as_nanos() => {
162                LockState::Stale
163            }
164            Some((motion, _)) => LockState::Locked(motion),
165        }
166    }
167
168    /// Discards any partial cycle and the last position, as when the source changes. Limits and
169    /// the rate hint stay.
170    pub const fn reset(&mut self) {
171        self.clear_cycle();
172        self.last_event = None;
173    }
174
175    fn quarter_frame(&mut self, data: u8, at: Duration) -> Result<Option<MtcEvent>, MtcError> {
176        let piece = (data >> 4) & 0x07;
177        let direction = match self.last_piece {
178            Some((last, last_at)) if at.saturating_sub(last_at) < self.quarter_frame_timeout => {
179                match (piece + 8 - last) % 8 {
180                    1 => Some(Direction::Forward),
181                    7 => Some(Direction::Reverse),
182                    _ => None,
183                }
184            }
185            _ => None,
186        };
187        // A gap, skip, repeat or turn around ends the cycle so far.
188        if direction.is_none() || (self.direction.is_some() && direction != self.direction) {
189            self.received = 0;
190        }
191        self.direction = direction;
192        self.last_piece = Some((piece, at));
193        self.pieces[usize::from(piece)] = data & 0x0F;
194        self.received |= 1 << piece;
195
196        let (motion, cycle_end) = match direction {
197            Some(Direction::Forward) => (Motion::Forward, 7),
198            Some(Direction::Reverse) => (Motion::Reverse, 0),
199            None => return Ok(None),
200        };
201        if piece != cycle_end || self.received != ALL_PIECES {
202            return Ok(None);
203        }
204        self.received = 0;
205
206        // Bits the specification reserves are masked: 0000000f, 00ssssss, 00mmmmmm, 0rrh.
207        let p = self.pieces;
208        let fields = Fields {
209            hours: p[6] | ((p[7] & 0x01) << 4),
210            minutes: p[4] | ((p[5] & 0x03) << 4),
211            seconds: p[2] | ((p[3] & 0x03) << 4),
212            frames: p[0] | ((p[1] & 0x01) << 4),
213        };
214        let encoded = self.timecode(fields, (p[7] >> 1) & 0x03)?;
215        let timecode = match motion {
216            Motion::Forward => encoded.wrapping_add_frames(FORWARD_CYCLE_LATENCY),
217            Motion::Reverse | Motion::Located => encoded,
218        };
219        Ok(Some(self.record(timecode, motion, at)))
220    }
221
222    fn full_frame(&mut self, message: &[u8], at: Duration) -> Result<MtcEvent, MtcError> {
223        // A locate interrupts the running stream even when its payload is malformed.
224        self.clear_cycle();
225        // F0 7F <device> 01 01 0rrhhhhh 00mmmmmm 00ssssss 000fffff F7
226        let [
227            _,
228            _,
229            device,
230            _,
231            _,
232            hours,
233            minutes,
234            seconds,
235            frames,
236            SYSEX_END,
237        ] = *message
238        else {
239            return Err(MtcError::MalformedMessage);
240        };
241        if [device, hours, minutes, seconds, frames]
242            .iter()
243            .any(|byte| byte & 0x80 != 0)
244        {
245            return Err(MtcError::MalformedMessage);
246        }
247        let fields = Fields {
248            hours: hours & 0x1F,
249            minutes: minutes & 0x3F,
250            seconds: seconds & 0x3F,
251            frames: frames & 0x1F,
252        };
253        let timecode = self.timecode(fields, (hours >> 5) & 0x03)?;
254        Ok(self.record(timecode, Motion::Located, at))
255    }
256
257    fn timecode(&self, fields: Fields, code: u8) -> Result<Timecode, MtcError> {
258        let stream = stream_rate(code);
259        let rate = self
260            .rate_hint
261            .and_then(|hint| hinted_rate(hint, stream))
262            .unwrap_or(stream);
263        Timecode::from_fields(fields, rate).map_err(MtcError::InvalidTimecode)
264    }
265
266    const fn record(&mut self, timecode: Timecode, motion: Motion, at: Duration) -> MtcEvent {
267        self.last_event = Some((motion, at));
268        MtcEvent {
269            timecode,
270            motion,
271            at,
272        }
273    }
274
275    const fn clear_cycle(&mut self) {
276        self.received = 0;
277        self.last_piece = None;
278        self.direction = None;
279    }
280}
281
282/// The rate positions of a `stream` code use under `hint`: the hint when it counts the stream's
283/// frames, or for a hint at twice that count, the stream's count with the hint's 1000/1001 factor
284/// and drop-frame counting. `None` when the hint is another session's.
285fn hinted_rate(hint: FrameRate, stream: FrameRate) -> Option<FrameRate> {
286    if hint.nominal() == stream.nominal() {
287        Some(hint)
288    } else if u16::from(hint.nominal()) == 2 * u16::from(stream.nominal()) {
289        FrameRate::new(stream.nominal(), hint.is_ntsc(), hint.is_drop_frame()).ok()
290    } else {
291        None
292    }
293}
294
295impl Default for MtcDecoder {
296    fn default() -> Self {
297        Self::new()
298    }
299}