Skip to main content

rtci_shared/
time.rs

1//! Monotonic, Unix and NTP time.
2//!
3//! Protocol logic measures time with a monotonic [`Instant`](std::time::Instant), which cannot go
4//! backwards but has no absolute meaning. RTCP timestamps need the opposite: wall-clock time in
5//! NTP format. [`SystemInstant`](crate::time::SystemInstant) captures both once, so either can be derived from the other later
6//! without re-reading a clock that may have been adjusted in between.
7use std::ops::Add;
8use std::sync::OnceLock;
9use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
10
11#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
12/// A monotonic [`Instant`] paired with the wall-clock time it was taken at.
13///
14/// Sans-I/O protocol code measures time with a monotonic [`Instant`], but RTCP timestamps
15/// and NTP fields need wall-clock time. Capturing both once lets either be derived from the
16/// other later without re-reading the (non-monotonic) system clock.
17pub struct SystemInstant {
18    instant: Instant,
19    duration_since_unix_epoch: Duration,
20}
21
22impl SystemInstant {
23    /// Captures the current monotonic instant together with the current wall-clock time.
24    pub fn now(now: Instant) -> Self {
25        Self {
26            instant: now,
27            duration_since_unix_epoch: SystemTime::now()
28                .duration_since(UNIX_EPOCH)
29                .unwrap_or_else(|_| Duration::from_secs(0)),
30        }
31    }
32
33    /// The process's one wall-clock anchor, taken at the first call (with `now` as its
34    /// monotonic half) and the same for every later caller.
35    ///
36    /// RTCP fields that compare NTP times written by different parts of an endpoint use it:
37    /// RFC 8888 section 3.1 derives the report timestamp "from the same clock used to generate
38    /// the NTP timestamp field in RTCP SR packets", and RFC 3550 section 6.4.1 has every
39    /// sender report of a participant on one wallclock. Each taking its own
40    /// [`now`](Self::now) at a different moment would pair a different wall-clock reading with
41    /// each anchor instant: under a clock the caller drives (virtual time) the two differ by
42    /// however far that clock ran ahead of the machine's.
43    pub fn shared(now: Instant) -> Self {
44        static SHARED: OnceLock<SystemInstant> = OnceLock::new();
45        *SHARED.get_or_init(|| Self::now(now))
46    }
47
48    /// Pairs a monotonic instant with the wall-clock time the caller says it corresponds to.
49    ///
50    /// Reads no clock: for a time derived from another [`SystemInstant`] (an earlier or later
51    /// instant on the same anchor) or carried by a protocol field (an RTCP sender report's NTP
52    /// timestamp).
53    pub fn at(instant: Instant, duration_since_unix_epoch: Duration) -> Self {
54        Self {
55            instant,
56            duration_since_unix_epoch,
57        }
58    }
59
60    /// Only used for deserialization
61    pub fn from_epoch(duration_since_unix_epoch: Duration) -> Self {
62        let system_now = SystemTime::now(); // Exemption: wall-clock is correct here to deserialization only
63        let instant_now = Instant::now(); // Exemption: Instant-now is correct here to deserialization only
64
65        let duration_since_approx = system_now
66            .duration_since(UNIX_EPOCH + duration_since_unix_epoch)
67            .unwrap_or_else(|_| Duration::from_secs(0));
68
69        let instant = instant_now - duration_since_approx;
70
71        Self {
72            instant,
73            duration_since_unix_epoch,
74        }
75    }
76
77    /// Converts a Unix-epoch duration back into the monotonic [`Instant`] it corresponds to.
78    pub fn instant(&self, duration_since_unix_epoch: Duration) -> Instant {
79        self.instant + duration_since_unix_epoch - self.duration_since_unix_epoch
80    }
81
82    /// The wall-clock time, as a duration since the Unix epoch, captured at construction.
83    pub fn duration_since_unix_epoch(&self) -> Duration {
84        self.duration_since_unix_epoch
85    }
86
87    /// Converts the monotonic `now` into wall-clock time as a duration since the Unix epoch.
88    /// An instant before the anchor's maps to as much before its wall-clock time (saturating
89    /// at the Unix epoch).
90    pub fn unix(&self, now: Instant) -> Duration {
91        match now.checked_duration_since(self.instant) {
92            Some(after) => after.add(self.duration_since_unix_epoch),
93            None => self
94                .duration_since_unix_epoch
95                .saturating_sub(self.instant.duration_since(now)),
96        }
97    }
98
99    /// Converts the monotonic `now` into a 64-bit NTP timestamp, as RTCP Sender Reports carry.
100    pub fn ntp(&self, now: Instant) -> u64 {
101        SystemInstant::unix2ntp(self.unix(now))
102    }
103
104    /// Converts a Unix-epoch duration into a 64-bit NTP timestamp.
105    ///
106    /// The result is seconds since the NTP epoch (1900-01-01) in the high 32 bits and a binary
107    /// fraction of a second in the low 32.
108    pub fn unix2ntp(duration_since_unix_epoch: Duration) -> u64 {
109        let u = duration_since_unix_epoch.as_nanos() as u64;
110
111        let mut s = u / 1_000_000_000;
112        s += 0x83AA7E80; //offset in seconds between unix epoch and ntp epoch
113        let mut f = u % 1_000_000_000;
114        f <<= 32;
115        f /= 1_000_000_000;
116        s <<= 32;
117
118        s | f
119    }
120
121    /// Converts a 64-bit NTP timestamp into a duration since the Unix epoch.
122    ///
123    /// The inverse of [`Self::unix2ntp`].
124    pub fn ntp2unix(ntp: u64) -> Duration {
125        let mut s = ntp >> 32;
126        let mut f = ntp & 0xFFFFFFFF;
127        f *= 1_000_000_000;
128        f >>= 32;
129        s -= 0x83AA7E80;
130        let u = s * 1_000_000_000 + f;
131
132        /*let duration_since_unix_epoch =*/
133        Duration::new(u / 1_000_000_000, (u % 1_000_000_000) as u32)
134    }
135}
136
137#[cfg(test)]
138mod tests {
139    use super::*;
140
141    /// An instant before the anchor is as far before its wall-clock time; it used to stop at
142    /// the anchor's.
143    #[test]
144    fn an_instant_before_the_anchor_maps_to_an_earlier_wall_clock_time() {
145        let at = Instant::now() + Duration::from_secs(10);
146        let anchor = SystemInstant::at(at, Duration::from_secs(1_000));
147        assert_eq!(
148            Duration::from_secs(997),
149            anchor.unix(at - Duration::from_secs(3))
150        );
151        assert_eq!(
152            Duration::from_secs(1_002),
153            anchor.unix(at + Duration::from_secs(2))
154        );
155    }
156
157    /// Every caller of `shared` gets the one anchor, whatever instant it passes.
158    #[test]
159    fn the_shared_anchor_is_one_for_every_caller() {
160        let now = Instant::now();
161        let first = SystemInstant::shared(now);
162        let second = SystemInstant::shared(now + Duration::from_secs(60));
163        assert_eq!(first, second);
164        assert_eq!(first.ntp(now), second.ntp(now));
165    }
166}