forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust381.4 MiBb8521ccTahinli7 hours ago4437 commits

timebase.rs334 lines, 11.1 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 /// Seconds as a float. Display only.
202 pub fn as_secs_f64(&self) -> f64 {
203 self.ticks as f64 * self.base.as_secs_f64()
204 }
205}
206
207impl PartialEq for Timestamp {
208 fn eq(&self, other: &Self) -> bool {
209 self.cmp(other) == Ordering::Equal
210 }
211}
212
213impl Eq for Timestamp {}
214
215impl PartialOrd for Timestamp {
216 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
217 Some(self.cmp(other))
218 }
219}
220
221impl Ord for Timestamp {
222 /// Exact cross-base comparison: both sides are put over the common
223 /// denominator in [`i128`] rather than converted (and rounded) first.
224 fn cmp(&self, other: &Self) -> Ordering {
225 let a = self.ticks as i128 * self.base.num() as i128 * other.base.den() as i128;
226 let b = other.ticks as i128 * other.base.num() as i128 * self.base.den() as i128;
227 a.cmp(&b)
228 }
229}
230
231#[cfg(test)]
232mod tests {
233 use super::*;
234
235 #[test]
236 fn reduces_and_compares_equal() {
237 assert_eq!(TimeBase::new(2, 4), TimeBase::new(1, 2));
238 // NTSC fractions are already reduced and must survive verbatim.
239 assert_eq!(TimeBase::NTSC_FILM.num(), 1001);
240 assert_eq!(TimeBase::NTSC_FILM.den(), 24_000);
241 assert_eq!(TimeBase::NTSC_FILM.inverse(), TimeBase::new(24_000, 1001));
242 }
243
244 #[test]
245 fn rejects_non_positive_parts() {
246 assert!(TimeBase::try_new(1, 0).is_err());
247 assert!(TimeBase::try_new(0, 1).is_err());
248 assert!(TimeBase::try_new(-1, 24_000).is_err());
249 }
250
251 #[test]
252 fn ntsc_ten_hours_zero_drift() {
253 // 10 h of 24000/1001 film: frame index -> exact base and back.
254 let frames = 863_136_i64; // 10 h at 23.976 fps
255 let film = TimeBase::NTSC_FILM;
256 let fine = TimeBase::new(1, 24_000_000);
257 let ticks = film
258 .checked_rescale(frames, fine, Rounding::Nearest)
259 .unwrap();
260 assert_eq!(ticks, frames * 1001 * 1000);
261 assert_eq!(
262 fine.checked_rescale(ticks, film, Rounding::Nearest)
263 .unwrap(),
264 frames
265 );
266 // Per-frame accumulation must equal the closed form: no drift.
267 let mut acc = 0_i64;
268 for _ in 0..frames {
269 acc += 1001 * 1000;
270 }
271 assert_eq!(acc, ticks);
272 }
273
274 #[test]
275 fn ntsc_never_becomes_integer_fps() {
276 // 23.976 fps as a rate, one second of it, in the film base.
277 let one_second = TimeBase::SECONDS
278 .checked_rescale(1, TimeBase::NTSC_FILM, Rounding::Nearest)
279 .unwrap();
280 assert_eq!(one_second, 24); // 23.976 frames rounds to 24 ticks, never 23
281 // A 24 fps base would be a different instant; prove the two differ.
282 let film = Timestamp::new(24, TimeBase::NTSC_FILM);
283 let flat = Timestamp::new(24, TimeBase::new(1, 24));
284 assert!(film > flat);
285 }
286
287 #[test]
288 fn rounding_modes() {
289 let ms = TimeBase::MILLIS;
290 let s = TimeBase::SECONDS;
291 // 1500 ms -> seconds under each mode.
292 assert_eq!(ms.rescale(1500, s, Rounding::Down), 1);
293 assert_eq!(ms.rescale(1500, s, Rounding::Up), 2);
294 assert_eq!(ms.rescale(1500, s, Rounding::Zero), 1);
295 assert_eq!(ms.rescale(1500, s, Rounding::Nearest), 2);
296 // Negative timestamps (B-frame dts) round symmetrically.
297 assert_eq!(ms.rescale(-1500, s, Rounding::Down), -2);
298 assert_eq!(ms.rescale(-1500, s, Rounding::Up), -1);
299 assert_eq!(ms.rescale(-1500, s, Rounding::Zero), -1);
300 assert_eq!(ms.rescale(-1500, s, Rounding::Nearest), -2);
301 }
302
303 #[test]
304 fn overflow_is_reported_not_wrapped() {
305 // Seconds into nanoseconds: 2^63 seconds does not fit.
306 let s = TimeBase::SECONDS;
307 assert_eq!(
308 s.checked_rescale(i64::MAX, TimeBase::NANOS, Rounding::Nearest),
309 None
310 );
311 assert_eq!(
312 s.rescale(i64::MAX, TimeBase::NANOS, Rounding::Nearest),
313 i64::MAX
314 );
315 assert_eq!(
316 s.rescale(i64::MIN, TimeBase::NANOS, Rounding::Nearest),
317 i64::MIN
318 );
319 // In range, nothing saturates.
320 assert_eq!(
321 s.checked_rescale(3, TimeBase::NANOS, Rounding::Nearest),
322 Some(3_000_000_000)
323 );
324 }
325
326 #[test]
327 fn timestamp_math() {
328 let a = Timestamp::new(90_000, TimeBase::MPEG_TS); // 1 s
329 let b = Timestamp::new(1_000, TimeBase::MILLIS); // 1 s
330 assert_eq!(a, b);
331 assert_eq!(a.rescale(TimeBase::MILLIS, Rounding::Nearest).ticks, 1_000);
332 assert!(Timestamp::new(0, TimeBase::MILLIS) < a);
333 }
334}