use core::time::Duration;
use super::{
Direction, Motion, MtcError, QUARTER_FRAME, SUB_ID_FULL_FRAME, SUB_ID_TIME_CODE, SYSEX_END,
SYSEX_START, UNIVERSAL_REAL_TIME, stream_rate,
};
use crate::{Fields, FrameRate, Timecode};
const ALL_PIECES: u8 = 0xFF;
const FORWARD_CYCLE_LATENCY: i64 = 2;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct MtcEvent {
pub timecode: Timecode,
pub motion: Motion,
pub at: Duration,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum LockState {
Unlocked,
Locked(Motion),
Stale,
}
#[derive(Clone, Debug)]
pub struct MtcDecoder {
quarter_frame_timeout: Duration,
stale_after: Duration,
rate_hint: Option<FrameRate>,
pieces: [u8; 8],
received: u8,
last_piece: Option<(u8, Duration)>,
direction: Option<Direction>,
last_event: Option<(Motion, Duration)>,
}
impl MtcDecoder {
pub const DEFAULT_QUARTER_FRAME_TIMEOUT: Duration = Duration::from_millis(500);
pub const DEFAULT_STALE_AFTER: Duration = Duration::from_secs(1);
pub const fn new() -> Self {
Self {
quarter_frame_timeout: Self::DEFAULT_QUARTER_FRAME_TIMEOUT,
stale_after: Self::DEFAULT_STALE_AFTER,
rate_hint: None,
pieces: [0; 8],
received: 0,
last_piece: None,
direction: None,
last_event: None,
}
}
#[must_use]
pub const fn with_quarter_frame_timeout(mut self, timeout: Duration) -> Self {
self.quarter_frame_timeout = timeout;
self
}
#[must_use]
pub const fn with_stale_after(mut self, stale_after: Duration) -> Self {
self.stale_after = stale_after;
self
}
pub const fn set_rate_hint(&mut self, hint: Option<FrameRate>) {
self.rate_hint = hint;
}
pub fn feed(&mut self, message: &[u8], at: Duration) -> Result<Option<MtcEvent>, MtcError> {
match message {
[QUARTER_FRAME, data] if data & 0x80 == 0 => self.quarter_frame(*data, at),
[QUARTER_FRAME, ..] => {
self.clear_cycle();
Err(MtcError::MalformedMessage)
}
[
SYSEX_START,
UNIVERSAL_REAL_TIME,
_,
SUB_ID_TIME_CODE,
SUB_ID_FULL_FRAME,
..,
] => self.full_frame(message, at).map(Some),
_ => Ok(None),
}
}
pub const fn lock_state(&self, now: Duration) -> LockState {
match self.last_event {
None => LockState::Unlocked,
Some((_, at)) if now.saturating_sub(at).as_nanos() > self.stale_after.as_nanos() => {
LockState::Stale
}
Some((motion, _)) => LockState::Locked(motion),
}
}
pub const fn reset(&mut self) {
self.clear_cycle();
self.last_event = None;
}
fn quarter_frame(&mut self, data: u8, at: Duration) -> Result<Option<MtcEvent>, MtcError> {
let piece = (data >> 4) & 0x07;
let direction = match self.last_piece {
Some((last, last_at)) if at.saturating_sub(last_at) < self.quarter_frame_timeout => {
match (piece + 8 - last) % 8 {
1 => Some(Direction::Forward),
7 => Some(Direction::Reverse),
_ => None,
}
}
_ => None,
};
if direction.is_none() || (self.direction.is_some() && direction != self.direction) {
self.received = 0;
}
self.direction = direction;
self.last_piece = Some((piece, at));
self.pieces[usize::from(piece)] = data & 0x0F;
self.received |= 1 << piece;
let (motion, cycle_end) = match direction {
Some(Direction::Forward) => (Motion::Forward, 7),
Some(Direction::Reverse) => (Motion::Reverse, 0),
None => return Ok(None),
};
if piece != cycle_end || self.received != ALL_PIECES {
return Ok(None);
}
self.received = 0;
let p = self.pieces;
let fields = Fields {
hours: p[6] | ((p[7] & 0x01) << 4),
minutes: p[4] | ((p[5] & 0x03) << 4),
seconds: p[2] | ((p[3] & 0x03) << 4),
frames: p[0] | ((p[1] & 0x01) << 4),
};
let encoded = self.timecode(fields, (p[7] >> 1) & 0x03)?;
let timecode = match motion {
Motion::Forward => encoded.wrapping_add_frames(FORWARD_CYCLE_LATENCY),
Motion::Reverse | Motion::Located => encoded,
};
Ok(Some(self.record(timecode, motion, at)))
}
fn full_frame(&mut self, message: &[u8], at: Duration) -> Result<MtcEvent, MtcError> {
self.clear_cycle();
let [
_,
_,
device,
_,
_,
hours,
minutes,
seconds,
frames,
SYSEX_END,
] = *message
else {
return Err(MtcError::MalformedMessage);
};
if [device, hours, minutes, seconds, frames]
.iter()
.any(|byte| byte & 0x80 != 0)
{
return Err(MtcError::MalformedMessage);
}
let fields = Fields {
hours: hours & 0x1F,
minutes: minutes & 0x3F,
seconds: seconds & 0x3F,
frames: frames & 0x1F,
};
let timecode = self.timecode(fields, (hours >> 5) & 0x03)?;
Ok(self.record(timecode, Motion::Located, at))
}
fn timecode(&self, fields: Fields, code: u8) -> Result<Timecode, MtcError> {
let stream = stream_rate(code);
let rate = self
.rate_hint
.and_then(|hint| hinted_rate(hint, stream))
.unwrap_or(stream);
Timecode::from_fields(fields, rate).map_err(MtcError::InvalidTimecode)
}
const fn record(&mut self, timecode: Timecode, motion: Motion, at: Duration) -> MtcEvent {
self.last_event = Some((motion, at));
MtcEvent {
timecode,
motion,
at,
}
}
const fn clear_cycle(&mut self) {
self.received = 0;
self.last_piece = None;
self.direction = None;
}
}
fn hinted_rate(hint: FrameRate, stream: FrameRate) -> Option<FrameRate> {
if hint.nominal() == stream.nominal() {
Some(hint)
} else if u16::from(hint.nominal()) == 2 * u16::from(stream.nominal()) {
FrameRate::new(stream.nominal(), hint.is_ntsc(), hint.is_drop_frame()).ok()
} else {
None
}
}
impl Default for MtcDecoder {
fn default() -> Self {
Self::new()
}
}