smpte_timecode/mtc/
encoder.rs1use 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
7const CYCLE_FRAMES: i64 = 2;
9
10#[derive(Clone, Debug)]
30pub struct MtcEncoder {
31 timecode: Timecode,
32 direction: Direction,
33 code: u8,
34 piece: u8,
35}
36
37impl MtcEncoder {
38 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 pub const fn timecode(&self) -> Timecode {
63 self.timecode
64 }
65
66 pub const fn direction(&self) -> Direction {
68 self.direction
69 }
70
71 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 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}