Skip to main content

smpte_timecode/timecode/
position.rs

1use core::fmt;
2
3use super::{FrameRate, Ratio, Rounding, TimecodeError};
4
5/// The four fields of a timecode label.
6#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
7pub struct Fields {
8    /// Hours, 0 to 23.
9    pub hours: u8,
10    /// Minutes, 0 to 59.
11    pub minutes: u8,
12    /// Seconds, 0 to 59.
13    pub seconds: u8,
14    /// Frames, 0 up to the nominal frame rate.
15    pub frames: u8,
16}
17
18/// A position within one 24-hour timecode day at a [`FrameRate`].
19///
20/// The position is a frame count from `00:00:00:00`, so arithmetic is exact and drop-frame labels
21/// only matter when parsing and formatting. Arithmetic wraps at midnight in both directions.
22///
23/// ```
24/// use smpte_timecode::{FrameRate, Timecode};
25///
26/// let start = Timecode::parse("00:00:59;29", FrameRate::FPS_29_97_DF)?;
27/// assert_eq!(start.frames(), 1799);
28/// assert_eq!(start.wrapping_add_frames(1).to_string(), "00:01:00;02");
29/// # Ok::<(), smpte_timecode::TimecodeError>(())
30/// ```
31#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
32pub struct Timecode {
33    frames: u32,
34    rate: FrameRate,
35}
36
37impl Timecode {
38    /// The position `frames` frames after `00:00:00:00`.
39    ///
40    /// # Errors
41    ///
42    /// [`TimecodeError::FrameOutOfRange`] when `frames` is not below
43    /// [`FrameRate::frames_per_day`].
44    pub const fn from_frames(frames: u32, rate: FrameRate) -> Result<Self, TimecodeError> {
45        if frames >= rate.frames_per_day() {
46            return Err(TimecodeError::FrameOutOfRange);
47        }
48        Ok(Self { frames, rate })
49    }
50
51    /// The position that `fields` label at `rate`.
52    ///
53    /// # Errors
54    ///
55    /// [`TimecodeError::FieldOutOfRange`] for a field outside its range and
56    /// [`TimecodeError::DroppedLabel`] for a label drop-frame counting skips.
57    pub const fn from_fields(fields: Fields, rate: FrameRate) -> Result<Self, TimecodeError> {
58        let Fields {
59            hours,
60            minutes,
61            seconds,
62            frames,
63        } = fields;
64        if hours > 23 || minutes > 59 || seconds > 59 || frames >= rate.nominal() {
65            return Err(TimecodeError::FieldOutOfRange);
66        }
67        let dropped = rate.dropped_per_minute();
68        if minutes % 10 != 0 && seconds == 0 && (frames as u32) < dropped {
69            return Err(TimecodeError::DroppedLabel);
70        }
71        let total_minutes = hours as u32 * 60 + minutes as u32;
72        let labels = (total_minutes * 60 + seconds as u32) * rate.nominal() as u32 + frames as u32;
73        let skipped = dropped * (total_minutes - total_minutes / 10);
74        Ok(Self {
75            frames: labels - skipped,
76            rate,
77        })
78    }
79
80    /// Parses `HH:MM:SS:FF`. Drop-frame rates also accept `HH:MM:SS;FF`. The frame field has two
81    /// or three digits. Surrounding whitespace is not accepted.
82    ///
83    /// # Errors
84    ///
85    /// [`TimecodeError::InvalidSyntax`] for any other shape, [`TimecodeError::DropFrameSeparator`]
86    /// for `;` at a non-drop-frame rate, and the errors of [`Timecode::from_fields`].
87    pub const fn parse(text: &str, rate: FrameRate) -> Result<Self, TimecodeError> {
88        let bytes = text.as_bytes();
89        if (bytes.len() != 11 && bytes.len() != 12) || bytes[2] != b':' || bytes[5] != b':' {
90            return Err(TimecodeError::InvalidSyntax);
91        }
92        let drop_separator = match bytes[8] {
93            b':' => false,
94            b';' => true,
95            _ => return Err(TimecodeError::InvalidSyntax),
96        };
97        let (Some(hours), Some(minutes), Some(seconds), Some(frames)) = (
98            digits(bytes, 0, 2),
99            digits(bytes, 3, 5),
100            digits(bytes, 6, 8),
101            digits(bytes, 9, bytes.len()),
102        ) else {
103            return Err(TimecodeError::InvalidSyntax);
104        };
105        if drop_separator && !rate.is_drop_frame() {
106            return Err(TimecodeError::DropFrameSeparator);
107        }
108        if frames > u8::MAX as u16 {
109            return Err(TimecodeError::FieldOutOfRange);
110        }
111        Self::from_fields(
112            Fields {
113                hours: hours as u8,
114                minutes: minutes as u8,
115                seconds: seconds as u8,
116                frames: frames as u8,
117            },
118            rate,
119        )
120    }
121
122    /// The position at `seconds` after midnight, rounded to a whole frame.
123    ///
124    /// # Errors
125    ///
126    /// [`TimecodeError::FrameOutOfRange`] when the rounded frame falls outside the day.
127    pub const fn from_seconds(
128        seconds: Ratio,
129        rate: FrameRate,
130        rounding: Rounding,
131    ) -> Result<Self, TimecodeError> {
132        let fps = rate.frames_per_second();
133        let numer = seconds.numer() as u128 * fps.numer() as u128;
134        let denom = seconds.denom() as u128 * fps.denom() as u128;
135        Self::from_frame_count(rounding.divide(numer, denom), rate)
136    }
137
138    /// The position of sample `samples` at `sample_rate` samples per second, rounded to a whole
139    /// frame. Pass a pulled sample rate from [`Pull::apply`](crate::Pull::apply) for pulled audio.
140    ///
141    /// # Errors
142    ///
143    /// [`TimecodeError::ZeroSampleRate`] for a zero `sample_rate`, [`TimecodeError::Overflow`]
144    /// when the exact product does not fit in 128 bits, and [`TimecodeError::FrameOutOfRange`]
145    /// when the rounded frame falls outside the day.
146    pub const fn from_samples(
147        samples: u64,
148        sample_rate: Ratio,
149        rate: FrameRate,
150        rounding: Rounding,
151    ) -> Result<Self, TimecodeError> {
152        if sample_rate.numer() == 0 {
153            return Err(TimecodeError::ZeroSampleRate);
154        }
155        let fps = rate.frames_per_second();
156        let Some(numer) =
157            (samples as u128 * sample_rate.denom() as u128).checked_mul(fps.numer() as u128)
158        else {
159            return Err(TimecodeError::Overflow);
160        };
161        let denom = sample_rate.numer() as u128 * fps.denom() as u128;
162        Self::from_frame_count(rounding.divide(numer, denom), rate)
163    }
164
165    /// The frame count from `00:00:00:00`.
166    pub const fn frames(self) -> u32 {
167        self.frames
168    }
169
170    /// The frame rate.
171    pub const fn rate(self) -> FrameRate {
172        self.rate
173    }
174
175    /// The label fields of this position.
176    pub const fn fields(self) -> Fields {
177        let rate = self.rate;
178        let nominal = rate.nominal() as u32;
179        let dropped = rate.dropped_per_minute();
180        let mut labels = self.frames;
181        if dropped > 0 {
182            let tens = labels / rate.frames_per_ten_minutes();
183            let remaining = labels % rate.frames_per_ten_minutes();
184            // The first minute of each ten-minute block has no skipped labels.
185            let skipped_minutes = if remaining < dropped {
186                0
187            } else {
188                (remaining - dropped) / rate.frames_per_minute()
189            };
190            labels += dropped * (tens * 9 + skipped_minutes);
191        }
192        let seconds = labels / nominal;
193        let minutes = seconds / 60;
194        Fields {
195            hours: (minutes / 60) as u8,
196            minutes: (minutes % 60) as u8,
197            seconds: (seconds % 60) as u8,
198            frames: (labels % nominal) as u8,
199        }
200    }
201
202    /// The position `delta` frames later, or earlier for a negative `delta`, wrapping at midnight.
203    pub const fn wrapping_add_frames(self, delta: i64) -> Self {
204        let day = self.rate.frames_per_day() as i64;
205        let frames = (self.frames as i64 + delta.rem_euclid(day)) % day;
206        Self {
207            frames: frames as u32,
208            rate: self.rate,
209        }
210    }
211
212    /// The exact time since midnight in seconds.
213    ///
214    /// ```
215    /// use smpte_timecode::{FrameRate, Ratio, Timecode};
216    ///
217    /// let hour = Timecode::parse("01:00:00:00", FrameRate::FPS_23_976)?;
218    /// assert_eq!(hour.to_seconds(), Ratio::new(18_018, 5)?); // 3603.6 s
219    /// # Ok::<(), smpte_timecode::TimecodeError>(())
220    /// ```
221    pub const fn to_seconds(self) -> Ratio {
222        let fps = self.rate.frames_per_second();
223        Ratio::reduced(self.frames as u64 * fps.denom(), fps.numer())
224    }
225
226    /// The sample at this position for `sample_rate` samples per second, rounded to a whole
227    /// sample. NTSC rates rarely land on a whole sample, so the rounding is part of the call.
228    ///
229    /// ```
230    /// use smpte_timecode::{FrameRate, Ratio, Rounding, Timecode};
231    ///
232    /// let hour = Timecode::parse("01:00:00;00", FrameRate::FPS_29_97_DF)?;
233    /// let rate = Ratio::from_integer(48_000);
234    /// // Exactly 172 799 827.2 samples.
235    /// assert_eq!(hour.to_samples(rate, Rounding::Down)?, 172_799_827);
236    /// assert_eq!(hour.to_samples(rate, Rounding::Up)?, 172_799_828);
237    /// # Ok::<(), smpte_timecode::TimecodeError>(())
238    /// ```
239    ///
240    /// # Errors
241    ///
242    /// [`TimecodeError::Overflow`] when the sample does not fit in `u64`.
243    pub const fn to_samples(
244        self,
245        sample_rate: Ratio,
246        rounding: Rounding,
247    ) -> Result<u64, TimecodeError> {
248        let fps = self.rate.frames_per_second();
249        // At most 2^24 frames × 2^10 × 2^64 and 2^17 × 2^64, so neither product overflows.
250        let numer = self.frames as u128 * fps.denom() as u128 * sample_rate.numer() as u128;
251        let denom = fps.numer() as u128 * sample_rate.denom() as u128;
252        let samples = rounding.divide(numer, denom);
253        if samples > u64::MAX as u128 {
254            return Err(TimecodeError::Overflow);
255        }
256        Ok(samples as u64)
257    }
258
259    const fn from_frame_count(frames: u128, rate: FrameRate) -> Result<Self, TimecodeError> {
260        if frames >= rate.frames_per_day() as u128 {
261            return Err(TimecodeError::FrameOutOfRange);
262        }
263        Ok(Self {
264            frames: frames as u32,
265            rate,
266        })
267    }
268}
269
270impl fmt::Display for Timecode {
271    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
272        let Fields {
273            hours,
274            minutes,
275            seconds,
276            frames,
277        } = self.fields();
278        let separator = if self.rate.is_drop_frame() { ';' } else { ':' };
279        write!(
280            f,
281            "{hours:02}:{minutes:02}:{seconds:02}{separator}{frames:02}"
282        )
283    }
284}
285
286/// The decimal value of `bytes[start..end]`, or `None` if any byte is not an ASCII digit.
287const fn digits(bytes: &[u8], start: usize, end: usize) -> Option<u16> {
288    let mut value = 0;
289    let mut index = start;
290    while index < end {
291        let byte = bytes[index];
292        if !byte.is_ascii_digit() {
293            return None;
294        }
295        value = value * 10 + (byte - b'0') as u16;
296        index += 1;
297    }
298    Some(value)
299}