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/// Whether the NTP timestamp `ntp` falls where a positive leap second could make it
138/// ambiguous: the last second of the last day of a month (UTC) or the second after it.
139///
140/// RFC 7164 section 5: "generating or using NTP timestamps during the entire last second of a
141/// day on which a positive leap second has been scheduled SHOULD be avoided. Note that the
142/// period to be avoided has a real-time duration of two seconds"; section 5.1: senders and
143/// receivers "MAY assume that a positive leap second occurs at the end of the last day of
144/// every month". On a clock that does not bear the leap second (this one counts seconds
145/// uniformly) those two seconds read 23:59:59 and 00:00:00. Timestamps of the NTP era that
146/// starts in 2036 are taken as such.
147pub fn near_leap_second(ntp: u64) -> bool {
148 const NTP_TO_UNIX: u64 = 0x83AA_7E80;
149 const DAY: u64 = 86_400;
150 let mut seconds = ntp >> 32;
151 if seconds < NTP_TO_UNIX {
152 // Era 1 (from 2036-02-07): the seconds field wrapped.
153 seconds += 1 << 32;
154 }
155 let unix = seconds - NTP_TO_UNIX;
156 let (day, second_of_day) = (unix / DAY, unix % DAY);
157 match second_of_day {
158 // 23:59:59 on the last day of a month: the next day is the first.
159 86_399 => day_of_month(day + 1) == 1,
160 // 00:00:00 on the first day of a month: where the leap second's real time falls.
161 0 => day_of_month(day) == 1,
162 _ => false,
163 }
164}
165
166/// The day of the month (1 to 31) of the civil (proleptic Gregorian) date `days` days after
167/// 1970-01-01 (H. Hinnant's `civil_from_days`).
168fn day_of_month(days: u64) -> u64 {
169 let z = days + 719_468;
170 let era = z / 146_097;
171 let day_of_era = z - era * 146_097;
172 let year_of_era =
173 (day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
174 let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
175 let month_index = (5 * day_of_year + 2) / 153;
176 day_of_year - (153 * month_index + 2) / 5 + 1
177}
178
179#[cfg(test)]
180mod tests {
181
182 /// The NTP timestamp of `unix` seconds (and `millis`) after the Unix epoch.
183 fn ntp_at(unix: u64, millis: u64) -> u64 {
184 SystemInstant::unix2ntp(Duration::from_millis(unix * 1000 + millis))
185 }
186
187 /// RFC 7164 sections 5 and 5.1: the last second of the last day of every month and the
188 /// second after it, and nothing else; month lengths and leap years as the calendar has
189 /// them.
190 #[test]
191 fn the_two_seconds_around_the_end_of_every_month_are_near_a_leap_second() {
192 // 2016-12-31 23:59:59, a day that had one; 2026-11-30 and 2026-12-31 23:59:59.
193 for unix in [1_483_228_799u64, 1_796_083_199, 1_798_761_599] {
194 assert!(near_leap_second(ntp_at(unix, 0)), "{unix}");
195 assert!(near_leap_second(ntp_at(unix, 999)), "{unix}");
196 assert!(near_leap_second(ntp_at(unix + 1, 500)), "{unix} + 1");
197 assert!(!near_leap_second(ntp_at(unix - 1, 999)), "{unix} - 1");
198 assert!(!near_leap_second(ntp_at(unix + 2, 0)), "{unix} + 2");
199 }
200 // February: the 29th in a leap year, the 28th otherwise.
201 assert!(near_leap_second(ntp_at(1_709_251_199, 0))); // 2024-02-29 23:59:59
202 assert!(!near_leap_second(ntp_at(1_709_164_799, 0))); // 2024-02-28 23:59:59
203 assert!(near_leap_second(ntp_at(1_740_787_199, 0))); // 2025-02-28 23:59:59
204 // Mid-month, mid-day.
205 assert!(!near_leap_second(ntp_at(1_795_521_600, 0))); // 2026-11-24 12:00:00
206 // NTP era 1: 2036-02-29 23:59:59.
207 assert!(near_leap_second(ntp_at(2_087_942_399, 0)));
208 }
209 use super::*;
210
211 /// An instant before the anchor is as far before its wall-clock time; it used to stop at
212 /// the anchor's.
213 #[test]
214 fn an_instant_before_the_anchor_maps_to_an_earlier_wall_clock_time() {
215 let at = Instant::now() + Duration::from_secs(10);
216 let anchor = SystemInstant::at(at, Duration::from_secs(1_000));
217 assert_eq!(
218 Duration::from_secs(997),
219 anchor.unix(at - Duration::from_secs(3))
220 );
221 assert_eq!(
222 Duration::from_secs(1_002),
223 anchor.unix(at + Duration::from_secs(2))
224 );
225 }
226
227 /// Every caller of `shared` gets the one anchor, whatever instant it passes.
228 #[test]
229 fn the_shared_anchor_is_one_for_every_caller() {
230 let now = Instant::now();
231 let first = SystemInstant::shared(now);
232 let second = SystemInstant::shared(now + Duration::from_secs(60));
233 assert_eq!(first, second);
234 assert_eq!(first.ntp(now), second.ntp(now));
235 }
236}