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. When they differ, the stream wins, because reading its frames at another count would
116 /// shift positions or reject frame numbers the hint cannot hold.
117 pub const fn set_rate_hint(&mut self, hint: Option<FrameRate>) {
118 self.rate_hint = hint;
119 }
120
121 /// Decodes one complete MIDI message received at `at`.
122 ///
123 /// Returns a position when the message completes a quarter-frame cycle or is a full frame,
124 /// and `None` for a partial cycle or a message that is not MIDI Time Code.
125 ///
126 /// # Errors
127 ///
128 /// [`MtcError::MalformedMessage`] for a quarter frame or full frame with the wrong shape, and
129 /// [`MtcError::InvalidTimecode`] when a complete message names a position that does not exist.
130 /// A malformed message discards the partial cycle. An invalid complete position consumes the
131 /// cycle as a valid one would. Neither error replaces or refreshes the last valid position.
132 pub fn feed(&mut self, message: &[u8], at: Duration) -> Result<Option<MtcEvent>, MtcError> {
133 match message {
134 [QUARTER_FRAME, data] if data & 0x80 == 0 => self.quarter_frame(*data, at),
135 [QUARTER_FRAME, ..] => {
136 self.clear_cycle();
137 Err(MtcError::MalformedMessage)
138 }
139 [
140 SYSEX_START,
141 UNIVERSAL_REAL_TIME,
142 _,
143 SUB_ID_TIME_CODE,
144 SUB_ID_FULL_FRAME,
145 ..,
146 ] => self.full_frame(message, at).map(Some),
147 _ => Ok(None),
148 }
149 }
150
151 /// Whether the decoder is following a source at `now`, on the same clock as
152 /// [`MtcDecoder::feed`].
153 pub const fn lock_state(&self, now: Duration) -> LockState {
154 match self.last_event {
155 None => LockState::Unlocked,
156 Some((_, at)) if now.saturating_sub(at).as_nanos() > self.stale_after.as_nanos() => {
157 LockState::Stale
158 }
159 Some((motion, _)) => LockState::Locked(motion),
160 }
161 }
162
163 /// Discards any partial cycle and the last position, as when the source changes. Limits and
164 /// the rate hint stay.
165 pub const fn reset(&mut self) {
166 self.clear_cycle();
167 self.last_event = None;
168 }
169
170 fn quarter_frame(&mut self, data: u8, at: Duration) -> Result<Option<MtcEvent>, MtcError> {
171 let piece = (data >> 4) & 0x07;
172 let direction = match self.last_piece {
173 Some((last, last_at)) if at.saturating_sub(last_at) < self.quarter_frame_timeout => {
174 match (piece + 8 - last) % 8 {
175 1 => Some(Direction::Forward),
176 7 => Some(Direction::Reverse),
177 _ => None,
178 }
179 }
180 _ => None,
181 };
182 // A gap, skip, repeat or turn around ends the cycle so far.
183 if direction.is_none() || (self.direction.is_some() && direction != self.direction) {
184 self.received = 0;
185 }
186 self.direction = direction;
187 self.last_piece = Some((piece, at));
188 self.pieces[usize::from(piece)] = data & 0x0F;
189 self.received |= 1 << piece;
190
191 let (motion, cycle_end) = match direction {
192 Some(Direction::Forward) => (Motion::Forward, 7),
193 Some(Direction::Reverse) => (Motion::Reverse, 0),
194 None => return Ok(None),
195 };
196 if piece != cycle_end || self.received != ALL_PIECES {
197 return Ok(None);
198 }
199 self.received = 0;
200
201 // Bits the specification reserves are masked: 0000000f, 00ssssss, 00mmmmmm, 0rrh.
202 let p = self.pieces;
203 let fields = Fields {
204 hours: p[6] | ((p[7] & 0x01) << 4),
205 minutes: p[4] | ((p[5] & 0x03) << 4),
206 seconds: p[2] | ((p[3] & 0x03) << 4),
207 frames: p[0] | ((p[1] & 0x01) << 4),
208 };
209 let encoded = self.timecode(fields, (p[7] >> 1) & 0x03)?;
210 let timecode = match motion {
211 Motion::Forward => encoded.wrapping_add_frames(FORWARD_CYCLE_LATENCY),
212 Motion::Reverse | Motion::Located => encoded,
213 };
214 Ok(Some(self.record(timecode, motion, at)))
215 }
216
217 fn full_frame(&mut self, message: &[u8], at: Duration) -> Result<MtcEvent, MtcError> {
218 // A locate interrupts the running stream even when its payload is malformed.
219 self.clear_cycle();
220 // F0 7F <device> 01 01 0rrhhhhh 00mmmmmm 00ssssss 000fffff F7
221 let [
222 _,
223 _,
224 device,
225 _,
226 _,
227 hours,
228 minutes,
229 seconds,
230 frames,
231 SYSEX_END,
232 ] = *message
233 else {
234 return Err(MtcError::MalformedMessage);
235 };
236 if [device, hours, minutes, seconds, frames]
237 .iter()
238 .any(|byte| byte & 0x80 != 0)
239 {
240 return Err(MtcError::MalformedMessage);
241 }
242 let fields = Fields {
243 hours: hours & 0x1F,
244 minutes: minutes & 0x3F,
245 seconds: seconds & 0x3F,
246 frames: frames & 0x1F,
247 };
248 let timecode = self.timecode(fields, (hours >> 5) & 0x03)?;
249 Ok(self.record(timecode, Motion::Located, at))
250 }
251
252 fn timecode(&self, fields: Fields, code: u8) -> Result<Timecode, MtcError> {
253 let stream = stream_rate(code);
254 let rate = match self.rate_hint {
255 Some(hint) if hint.nominal() == stream.nominal() => hint,
256 _ => stream,
257 };
258 Timecode::from_fields(fields, rate).map_err(MtcError::InvalidTimecode)
259 }
260
261 const fn record(&mut self, timecode: Timecode, motion: Motion, at: Duration) -> MtcEvent {
262 self.last_event = Some((motion, at));
263 MtcEvent {
264 timecode,
265 motion,
266 at,
267 }
268 }
269
270 const fn clear_cycle(&mut self) {
271 self.received = 0;
272 self.last_piece = None;
273 self.direction = None;
274 }
275}
276
277impl Default for MtcDecoder {
278 fn default() -> Self {
279 Self::new()
280 }
281}