forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBfc705c7Tahinli3 months ago174 commits

timebase.rs345 lines, 11.5 KiBHistoryRawDownload
1//! Exact rational time. No `f64` anywhere on a timing path.
2//!
3//! Every timestamp in the family is an integer tick count plus the [`TimeBase`]
4//! that gives the tick its duration in seconds. NTSC rates are exactly
5//! representable (`24000/1001`, `30000/1001`, `60000/1001`) and stay exact
6//! through rescaling, which is why `23.976` can never decay into `23.0` here.
7
8use std::cmp::Ordering;
9
10use crate::error::{Error, Result};
11
12/// A positive rational number of seconds per tick, stored reduced.
13///
14/// Also used as a *rate* (frames per second) where a rate is what is meant;
15/// [`TimeBase::inverse`] converts between the two readings.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
17pub struct TimeBase {
18 num: i64,
19 den: i64,
20}
21
22const fn gcd(mut a: i64, mut b: i64) -> i64 {
23 while b != 0 {
24 let t = a % b;
25 a = b;
26 b = t;
27 }
28 a
29}
30
31impl TimeBase {
32 /// Reduced `num/den`. Panics if either part is not positive — for literals;
33 /// use [`TimeBase::try_new`] for values parsed out of a container.
34 pub const fn new(num: i64, den: i64) -> TimeBase {
35 assert!(num > 0 && den > 0, "time base parts must be positive");
36 let g = gcd(num, den);
37 TimeBase {
38 num: num / g,
39 den: den / g,
40 }
41 }
42
43 /// Reduced `num/den`, or [`Error::Corrupt`] if either part is not positive.
44 pub fn try_new(num: i64, den: i64) -> Result<TimeBase> {
45 if num <= 0 || den <= 0 {
46 return Err(Error::corrupt(format!(
47 "time base {num}/{den} not positive"
48 )));
49 }
50 Ok(TimeBase::new(num, den))
51 }
52
53 /// Tick duration of a sample rate, i.e. `1/rate` (48 kHz audio: `1/48000`).
54 pub const fn from_rate(rate: u32) -> TimeBase {
55 TimeBase::new(1, rate as i64)
56 }
57
58 /// Numerator of the reduced fraction.
59 pub const fn num(&self) -> i64 {
60 self.num
61 }
62
63 /// Denominator of the reduced fraction.
64 pub const fn den(&self) -> i64 {
65 self.den
66 }
67
68 /// `den/num` — a tick duration read as a rate, or a rate as a duration.
69 pub const fn inverse(&self) -> TimeBase {
70 TimeBase {
71 num: self.den,
72 den: self.num,
73 }
74 }
75
76 /// Convert `ticks` from this base into `to`, saturating at [`i64`] bounds.
77 ///
78 /// Saturation is unreachable for real media (i64 nanoseconds is 292 years);
79 /// use [`TimeBase::checked_rescale`] when the input is attacker-controlled
80 /// and the difference must be observed.
81 pub fn rescale(&self, ticks: i64, to: TimeBase, rounding: Rounding) -> i64 {
82 match self.checked_rescale(ticks, to, rounding) {
83 Some(v) => v,
84 None if ticks >= 0 => i64::MAX,
85 None => i64::MIN,
86 }
87 }
88
89 /// Convert `ticks` from this base into `to`, or `None` on [`i64`] overflow.
90 ///
91 /// Exact: the whole computation runs in [`i128`] and rounds exactly once.
92 pub fn checked_rescale(&self, ticks: i64, to: TimeBase, rounding: Rounding) -> Option<i64> {
93 let n = ticks as i128 * self.num as i128 * to.den as i128;
94 let d = self.den as i128 * to.num as i128;
95 i64::try_from(rounding.div(n, d)).ok()
96 }
97
98 /// Seconds as a float. Display and logging only — never feed this back into
99 /// a timestamp.
100 pub fn as_secs_f64(&self) -> f64 {
101 self.num as f64 / self.den as f64
102 }
103
104 /// Seconds per tick: 1/1.
105 pub const SECONDS: TimeBase = TimeBase::new(1, 1);
106 /// Milliseconds: 1/1000 (Matroska default TimestampScale territory).
107 pub const MILLIS: TimeBase = TimeBase::new(1, 1_000);
108 /// Microseconds: 1/1_000_000.
109 pub const MICROS: TimeBase = TimeBase::new(1, 1_000_000);
110 /// Nanoseconds: 1/1_000_000_000 (Matroska timestamps).
111 pub const NANOS: TimeBase = TimeBase::new(1, 1_000_000_000);
112 /// MPEG transport/program stream clock: 1/90000.
113 pub const MPEG_TS: TimeBase = TimeBase::new(1, 90_000);
114 /// NTSC film frame duration: 1001/24000 (23.976 fps, exactly).
115 pub const NTSC_FILM: TimeBase = TimeBase::new(1001, 24_000);
116 /// NTSC video frame duration: 1001/30000 (29.97 fps, exactly).
117 pub const NTSC_VIDEO: TimeBase = TimeBase::new(1001, 30_000);
118}
119
120/// How a rescale that does not divide evenly picks its integer result.
121#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
122pub enum Rounding {
123 /// Toward negative infinity.
124 Down,
125 /// Toward positive infinity.
126 Up,
127 /// Toward zero (truncate).
128 Zero,
129 /// To the nearest, halves away from zero. The default: it is what seek and
130 /// container timestamp conversion want.
131 #[default]
132 Nearest,
133}
134
135impl Rounding {
136 /// Divide `n` by a positive `d` under this rounding mode.
137 fn div(self, n: i128, d: i128) -> i128 {
138 debug_assert!(d > 0, "time base denominators are positive by construction");
139 let q = n / d;
140 let r = n % d;
141 match self {
142 Rounding::Zero => q,
143 Rounding::Down => {
144 if r < 0 {
145 q - 1
146 } else {
147 q
148 }
149 }
150 Rounding::Up => {
151 if r > 0 {
152 q + 1
153 } else {
154 q
155 }
156 }
157 Rounding::Nearest => {
158 if r.abs() * 2 >= d {
159 if n >= 0 { q + 1 } else { q - 1 }
160 } else {
161 q
162 }
163 }
164 }
165 }
166}
167
168/// A tick count carrying its own [`TimeBase`].
169///
170/// Ordering and equality compare *instants*, exactly, across different bases.
171#[derive(Debug, Clone, Copy)]
172pub struct Timestamp {
173 /// Tick count in `base`.
174 pub ticks: i64,
175 /// Duration of one tick.
176 pub base: TimeBase,
177}
178
179impl Timestamp {
180 /// A timestamp of `ticks` in `base`.
181 pub const fn new(ticks: i64, base: TimeBase) -> Timestamp {
182 Timestamp { ticks, base }
183 }
184
185 /// The same instant expressed in `base`, saturating at [`i64`] bounds.
186 pub fn rescale(&self, base: TimeBase, rounding: Rounding) -> Timestamp {
187 Timestamp::new(self.base.rescale(self.ticks, base, rounding), base)
188 }
189
190 /// The same instant expressed in `base`, or `None` on [`i64`] overflow.
191 pub fn checked_rescale(&self, base: TimeBase, rounding: Rounding) -> Option<Timestamp> {
192 self.base
193 .checked_rescale(self.ticks, base, rounding)
194 .map(|t| Timestamp::new(t, base))
195 }
196
197 /// Advance by `ticks` of this timestamp's own base.
198 pub fn checked_add_ticks(&self, ticks: i64) -> Option<Timestamp> {
199 self.ticks
200 .checked_add(ticks)
201 .map(|t| Timestamp::new(t, self.base))
202 }
203
204 /// `self - other`, in this timestamp's base, exact.
205 pub fn checked_diff(&self, other: Timestamp) -> Option<i64> {
206 let o = other.checked_rescale(self.base, Rounding::Nearest)?;
207 self.ticks.checked_sub(o.ticks)
208 }
209
210 /// Seconds as a float. Display only.
211 pub fn as_secs_f64(&self) -> f64 {
212 self.ticks as f64 * self.base.as_secs_f64()
213 }
214}
215
216impl PartialEq for Timestamp {
217 fn eq(&self, other: &Self) -> bool {
218 self.cmp(other) == Ordering::Equal
219 }
220}
221
222impl Eq for Timestamp {}
223
224impl PartialOrd for Timestamp {
225 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
226 Some(self.cmp(other))
227 }
228}
229
230impl Ord for Timestamp {
231 /// Exact cross-base comparison: both sides are put over the common
232 /// denominator in [`i128`] rather than converted (and rounded) first.
233 fn cmp(&self, other: &Self) -> Ordering {
234 let a = self.ticks as i128 * self.base.num() as i128 * other.base.den() as i128;
235 let b = other.ticks as i128 * other.base.num() as i128 * self.base.den() as i128;
236 a.cmp(&b)
237 }
238}
239
240#[cfg(test)]
241mod tests {
242 use super::*;
243
244 #[test]
245 fn reduces_and_compares_equal() {
246 assert_eq!(TimeBase::new(2, 4), TimeBase::new(1, 2));
247 // NTSC fractions are already reduced and must survive verbatim.
248 assert_eq!(TimeBase::NTSC_FILM.num(), 1001);
249 assert_eq!(TimeBase::NTSC_FILM.den(), 24_000);
250 assert_eq!(TimeBase::NTSC_FILM.inverse(), TimeBase::new(24_000, 1001));
251 }
252
253 #[test]
254 fn rejects_non_positive_parts() {
255 assert!(TimeBase::try_new(1, 0).is_err());
256 assert!(TimeBase::try_new(0, 1).is_err());
257 assert!(TimeBase::try_new(-1, 24_000).is_err());
258 }
259
260 #[test]
261 fn ntsc_ten_hours_zero_drift() {
262 // 10 h of 24000/1001 film: frame index -> exact base and back.
263 let frames = 863_136_i64; // 10 h at 23.976 fps
264 let film = TimeBase::NTSC_FILM;
265 let fine = TimeBase::new(1, 24_000_000);
266 let ticks = film
267 .checked_rescale(frames, fine, Rounding::Nearest)
268 .unwrap();
269 assert_eq!(ticks, frames * 1001 * 1000);
270 assert_eq!(
271 fine.checked_rescale(ticks, film, Rounding::Nearest)
272 .unwrap(),
273 frames
274 );
275 // Per-frame accumulation must equal the closed form: no drift.
276 let mut acc = 0_i64;
277 for _ in 0..frames {
278 acc += 1001 * 1000;
279 }
280 assert_eq!(acc, ticks);
281 }
282
283 #[test]
284 fn ntsc_never_becomes_integer_fps() {
285 // 23.976 fps as a rate, one second of it, in the film base.
286 let one_second = TimeBase::SECONDS
287 .checked_rescale(1, TimeBase::NTSC_FILM, Rounding::Nearest)
288 .unwrap();
289 assert_eq!(one_second, 24); // 23.976 frames rounds to 24 ticks, never 23
290 // A 24 fps base would be a different instant; prove the two differ.
291 let film = Timestamp::new(24, TimeBase::NTSC_FILM);
292 let flat = Timestamp::new(24, TimeBase::new(1, 24));
293 assert!(film > flat);
294 }
295
296 #[test]
297 fn rounding_modes() {
298 let ms = TimeBase::MILLIS;
299 let s = TimeBase::SECONDS;
300 // 1500 ms -> seconds under each mode.
301 assert_eq!(ms.rescale(1500, s, Rounding::Down), 1);
302 assert_eq!(ms.rescale(1500, s, Rounding::Up), 2);
303 assert_eq!(ms.rescale(1500, s, Rounding::Zero), 1);
304 assert_eq!(ms.rescale(1500, s, Rounding::Nearest), 2);
305 // Negative timestamps (B-frame dts) round symmetrically.
306 assert_eq!(ms.rescale(-1500, s, Rounding::Down), -2);
307 assert_eq!(ms.rescale(-1500, s, Rounding::Up), -1);
308 assert_eq!(ms.rescale(-1500, s, Rounding::Zero), -1);
309 assert_eq!(ms.rescale(-1500, s, Rounding::Nearest), -2);
310 }
311
312 #[test]
313 fn overflow_is_reported_not_wrapped() {
314 // Seconds into nanoseconds: 2^63 seconds does not fit.
315 let s = TimeBase::SECONDS;
316 assert_eq!(
317 s.checked_rescale(i64::MAX, TimeBase::NANOS, Rounding::Nearest),
318 None
319 );
320 assert_eq!(
321 s.rescale(i64::MAX, TimeBase::NANOS, Rounding::Nearest),
322 i64::MAX
323 );
324 assert_eq!(
325 s.rescale(i64::MIN, TimeBase::NANOS, Rounding::Nearest),
326 i64::MIN
327 );
328 // In range, nothing saturates.
329 assert_eq!(
330 s.checked_rescale(3, TimeBase::NANOS, Rounding::Nearest),
331 Some(3_000_000_000)
332 );
333 }
334
335 #[test]
336 fn timestamp_math() {
337 let a = Timestamp::new(90_000, TimeBase::MPEG_TS); // 1 s
338 let b = Timestamp::new(1_000, TimeBase::MILLIS); // 1 s
339 assert_eq!(a, b);
340 assert_eq!(a.checked_diff(b), Some(0));
341 assert_eq!(a.checked_add_ticks(90_000).unwrap().ticks, 180_000);
342 assert_eq!(a.rescale(TimeBase::MILLIS, Rounding::Nearest).ticks, 1_000);
343 assert!(Timestamp::new(0, TimeBase::MILLIS) < a);
344 }
345}