forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB8defefbTahinli6 days ago3947 commits

timebase.rs349 lines, 11.7 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 // Checked: a fuzzed TimestampScale makes `num` large, and a tick count times
94 // two such factors overflows i128 (found by the ec-matroska seek fuzz target).
95 let n = (ticks as i128)
96 .checked_mul(self.num as i128)?
97 .checked_mul(to.den as i128)?;
98 let d = self.den as i128 * to.num as i128;
99 i64::try_from(rounding.div(n, d)).ok()
100 }
101
102 /// Seconds as a float. Display and logging only — never feed this back into
103 /// a timestamp.
104 pub fn as_secs_f64(&self) -> f64 {
105 self.num as f64 / self.den as f64
106 }
107
108 /// Seconds per tick: 1/1.
109 pub const SECONDS: TimeBase = TimeBase::new(1, 1);
110 /// Milliseconds: 1/1000 (Matroska default TimestampScale territory).
111 pub const MILLIS: TimeBase = TimeBase::new(1, 1_000);
112 /// Microseconds: 1/1_000_000.
113 pub const MICROS: TimeBase = TimeBase::new(1, 1_000_000);
114 /// Nanoseconds: 1/1_000_000_000 (Matroska timestamps).
115 pub const NANOS: TimeBase = TimeBase::new(1, 1_000_000_000);
116 /// MPEG transport/program stream clock: 1/90000.
117 pub const MPEG_TS: TimeBase = TimeBase::new(1, 90_000);
118 /// NTSC film frame duration: 1001/24000 (23.976 fps, exactly).
119 pub const NTSC_FILM: TimeBase = TimeBase::new(1001, 24_000);
120 /// NTSC video frame duration: 1001/30000 (29.97 fps, exactly).
121 pub const NTSC_VIDEO: TimeBase = TimeBase::new(1001, 30_000);
122}
123
124/// How a rescale that does not divide evenly picks its integer result.
125#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
126pub enum Rounding {
127 /// Toward negative infinity.
128 Down,
129 /// Toward positive infinity.
130 Up,
131 /// Toward zero (truncate).
132 Zero,
133 /// To the nearest, halves away from zero. The default: it is what seek and
134 /// container timestamp conversion want.
135 #[default]
136 Nearest,
137}
138
139impl Rounding {
140 /// Divide `n` by a positive `d` under this rounding mode.
141 fn div(self, n: i128, d: i128) -> i128 {
142 debug_assert!(d > 0, "time base denominators are positive by construction");
143 let q = n / d;
144 let r = n % d;
145 match self {
146 Rounding::Zero => q,
147 Rounding::Down => {
148 if r < 0 {
149 q - 1
150 } else {
151 q
152 }
153 }
154 Rounding::Up => {
155 if r > 0 {
156 q + 1
157 } else {
158 q
159 }
160 }
161 Rounding::Nearest => {
162 if r.abs() * 2 >= d {
163 if n >= 0 { q + 1 } else { q - 1 }
164 } else {
165 q
166 }
167 }
168 }
169 }
170}
171
172/// A tick count carrying its own [`TimeBase`].
173///
174/// Ordering and equality compare *instants*, exactly, across different bases.
175#[derive(Debug, Clone, Copy)]
176pub struct Timestamp {
177 /// Tick count in `base`.
178 pub ticks: i64,
179 /// Duration of one tick.
180 pub base: TimeBase,
181}
182
183impl Timestamp {
184 /// A timestamp of `ticks` in `base`.
185 pub const fn new(ticks: i64, base: TimeBase) -> Timestamp {
186 Timestamp { ticks, base }
187 }
188
189 /// The same instant expressed in `base`, saturating at [`i64`] bounds.
190 pub fn rescale(&self, base: TimeBase, rounding: Rounding) -> Timestamp {
191 Timestamp::new(self.base.rescale(self.ticks, base, rounding), base)
192 }
193
194 /// The same instant expressed in `base`, or `None` on [`i64`] overflow.
195 pub fn checked_rescale(&self, base: TimeBase, rounding: Rounding) -> Option<Timestamp> {
196 self.base
197 .checked_rescale(self.ticks, base, rounding)
198 .map(|t| Timestamp::new(t, base))
199 }
200
201 /// Advance by `ticks` of this timestamp's own base.
202 pub fn checked_add_ticks(&self, ticks: i64) -> Option<Timestamp> {
203 self.ticks
204 .checked_add(ticks)
205 .map(|t| Timestamp::new(t, self.base))
206 }
207
208 /// `self - other`, in this timestamp's base, exact.
209 pub fn checked_diff(&self, other: Timestamp) -> Option<i64> {
210 let o = other.checked_rescale(self.base, Rounding::Nearest)?;
211 self.ticks.checked_sub(o.ticks)
212 }
213
214 /// Seconds as a float. Display only.
215 pub fn as_secs_f64(&self) -> f64 {
216 self.ticks as f64 * self.base.as_secs_f64()
217 }
218}
219
220impl PartialEq for Timestamp {
221 fn eq(&self, other: &Self) -> bool {
222 self.cmp(other) == Ordering::Equal
223 }
224}
225
226impl Eq for Timestamp {}
227
228impl PartialOrd for Timestamp {
229 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
230 Some(self.cmp(other))
231 }
232}
233
234impl Ord for Timestamp {
235 /// Exact cross-base comparison: both sides are put over the common
236 /// denominator in [`i128`] rather than converted (and rounded) first.
237 fn cmp(&self, other: &Self) -> Ordering {
238 let a = self.ticks as i128 * self.base.num() as i128 * other.base.den() as i128;
239 let b = other.ticks as i128 * other.base.num() as i128 * self.base.den() as i128;
240 a.cmp(&b)
241 }
242}
243
244#[cfg(test)]
245mod tests {
246 use super::*;
247
248 #[test]
249 fn reduces_and_compares_equal() {
250 assert_eq!(TimeBase::new(2, 4), TimeBase::new(1, 2));
251 // NTSC fractions are already reduced and must survive verbatim.
252 assert_eq!(TimeBase::NTSC_FILM.num(), 1001);
253 assert_eq!(TimeBase::NTSC_FILM.den(), 24_000);
254 assert_eq!(TimeBase::NTSC_FILM.inverse(), TimeBase::new(24_000, 1001));
255 }
256
257 #[test]
258 fn rejects_non_positive_parts() {
259 assert!(TimeBase::try_new(1, 0).is_err());
260 assert!(TimeBase::try_new(0, 1).is_err());
261 assert!(TimeBase::try_new(-1, 24_000).is_err());
262 }
263
264 #[test]
265 fn ntsc_ten_hours_zero_drift() {
266 // 10 h of 24000/1001 film: frame index -> exact base and back.
267 let frames = 863_136_i64; // 10 h at 23.976 fps
268 let film = TimeBase::NTSC_FILM;
269 let fine = TimeBase::new(1, 24_000_000);
270 let ticks = film
271 .checked_rescale(frames, fine, Rounding::Nearest)
272 .unwrap();
273 assert_eq!(ticks, frames * 1001 * 1000);
274 assert_eq!(
275 fine.checked_rescale(ticks, film, Rounding::Nearest)
276 .unwrap(),
277 frames
278 );
279 // Per-frame accumulation must equal the closed form: no drift.
280 let mut acc = 0_i64;
281 for _ in 0..frames {
282 acc += 1001 * 1000;
283 }
284 assert_eq!(acc, ticks);
285 }
286
287 #[test]
288 fn ntsc_never_becomes_integer_fps() {
289 // 23.976 fps as a rate, one second of it, in the film base.
290 let one_second = TimeBase::SECONDS
291 .checked_rescale(1, TimeBase::NTSC_FILM, Rounding::Nearest)
292 .unwrap();
293 assert_eq!(one_second, 24); // 23.976 frames rounds to 24 ticks, never 23
294 // A 24 fps base would be a different instant; prove the two differ.
295 let film = Timestamp::new(24, TimeBase::NTSC_FILM);
296 let flat = Timestamp::new(24, TimeBase::new(1, 24));
297 assert!(film > flat);
298 }
299
300 #[test]
301 fn rounding_modes() {
302 let ms = TimeBase::MILLIS;
303 let s = TimeBase::SECONDS;
304 // 1500 ms -> seconds under each mode.
305 assert_eq!(ms.rescale(1500, s, Rounding::Down), 1);
306 assert_eq!(ms.rescale(1500, s, Rounding::Up), 2);
307 assert_eq!(ms.rescale(1500, s, Rounding::Zero), 1);
308 assert_eq!(ms.rescale(1500, s, Rounding::Nearest), 2);
309 // Negative timestamps (B-frame dts) round symmetrically.
310 assert_eq!(ms.rescale(-1500, s, Rounding::Down), -2);
311 assert_eq!(ms.rescale(-1500, s, Rounding::Up), -1);
312 assert_eq!(ms.rescale(-1500, s, Rounding::Zero), -1);
313 assert_eq!(ms.rescale(-1500, s, Rounding::Nearest), -2);
314 }
315
316 #[test]
317 fn overflow_is_reported_not_wrapped() {
318 // Seconds into nanoseconds: 2^63 seconds does not fit.
319 let s = TimeBase::SECONDS;
320 assert_eq!(
321 s.checked_rescale(i64::MAX, TimeBase::NANOS, Rounding::Nearest),
322 None
323 );
324 assert_eq!(
325 s.rescale(i64::MAX, TimeBase::NANOS, Rounding::Nearest),
326 i64::MAX
327 );
328 assert_eq!(
329 s.rescale(i64::MIN, TimeBase::NANOS, Rounding::Nearest),
330 i64::MIN
331 );
332 // In range, nothing saturates.
333 assert_eq!(
334 s.checked_rescale(3, TimeBase::NANOS, Rounding::Nearest),
335 Some(3_000_000_000)
336 );
337 }
338
339 #[test]
340 fn timestamp_math() {
341 let a = Timestamp::new(90_000, TimeBase::MPEG_TS); // 1 s
342 let b = Timestamp::new(1_000, TimeBase::MILLIS); // 1 s
343 assert_eq!(a, b);
344 assert_eq!(a.checked_diff(b), Some(0));
345 assert_eq!(a.checked_add_ticks(90_000).unwrap().ticks, 180_000);
346 assert_eq!(a.rescale(TimeBase::MILLIS, Rounding::Nearest).ticks, 1_000);
347 assert!(Timestamp::new(0, TimeBase::MILLIS) < a);
348 }
349}