1 //! The rational and the timebase that every timestamp is read against.2 //!3 //! A timebase is not a float. A rate of 30000/1001 has to stay exact, because a4 //! timestamp that drifts by one tick moves a frame and a cut. The pair stays5 //! reduced so that two equal rates have equal fields.6 7 use std::time::Duration;8 9 use crate::VideoError;10 11 /// Nanoseconds in one second. All conversions pass through this unit, which is12 /// finer than any rate that the deploy carries.13 pub(crate) const NANOS_PER_SEC: u128 = 1_000_000_000;14 15 /// A rational number, always reduced, denominator positive.16 #[derive(Clone, Copy, PartialEq, Eq, Debug)]17 pub struct Rational {18 /// The numerator.19 pub num: u64,20 /// The denominator. It is never zero.21 pub den: u64,22 }23 24 impl Rational {25 /// A rational from its two parts. Reduction keeps equality a field compare.26 pub fn new(num: u64, den: u64) -> Result<Rational, VideoError> {27 if den == 0 {28 return Err(VideoError::Division);29 }30 let g = gcd(num, den);31 Ok(Rational {32 num: num / g,33 den: den / g,34 })35 }36 37 /// A frame rate. It is a rational for the same reason as a timebase.38 pub fn fps(num: u64, den: u64) -> Result<Rational, VideoError> {39 Rational::new(num, den)40 }41 }42 43 /// A timebase: the unit of the timestamps of one track.44 #[derive(Clone, Copy, PartialEq, Eq, Debug)]45 pub struct Timebase(pub Rational);46 47 impl Timebase {48 /// A timebase whose tick is `num / den` seconds.49 pub fn new(num: u64, den: u64) -> Result<Timebase, VideoError> {50 let rate = Rational::new(num, den)?;51 if rate.num == 0 {52 return Err(VideoError::Division);53 }54 Ok(Timebase(rate))55 }56 57 /// The number of whole ticks that end at or before `at`.58 pub fn ticks(&self, at: Duration) -> u64 {59 if self.0.num == 0 {60 return 0;61 }62 let numerator = at.as_nanos().saturating_mul(u128::from(self.0.den));63 let denominator = u128::from(self.0.num).saturating_mul(NANOS_PER_SEC);64 let ticks = numerator / denominator;65 u64::try_from(ticks).unwrap_or(u64::MAX)66 }67 68 /// The time at the start of tick `ticks`.69 pub fn time(&self, ticks: u64) -> Duration {70 if self.0.num == 0 {71 return Duration::ZERO;72 }73 let numerator = u128::from(ticks)74 .saturating_mul(u128::from(self.0.num))75 .saturating_mul(NANOS_PER_SEC);76 let nanos = numerator / u128::from(self.0.den);77 duration_from_nanos(nanos)78 }79 }80 81 /// The greatest common divisor. Zero with a positive number gives that number,82 /// which keeps `0/den` reduced to `0/1`.83 fn gcd(a: u64, b: u64) -> u64 {84 let (mut a, mut b) = (a, b);85 while b != 0 {86 let rest = a % b;87 a = b;88 b = rest;89 }90 a.max(1)91 }92 93 /// A duration from nanoseconds, saturating at what `Duration` can hold.94 pub(crate) fn duration_from_nanos(nanos: u128) -> Duration {95 let secs = nanos / NANOS_PER_SEC;96 let sub = (nanos % NANOS_PER_SEC) as u32;97 let secs = u64::try_from(secs).unwrap_or(u64::MAX);98 Duration::new(secs, sub)99 }