File
Blob: firmware/vendor/str0m/src/util/time_tricks.rs
| 1 | use std::backtrace::Backtrace; |
| 2 | use std::sync::LazyLock; |
| 3 | use std::time::{Duration, Instant, SystemTime}; |
| 4 | |
| 5 | pub(crate) fn not_happening() -> Instant { |
| 6 | const YEARS_100: Duration = Duration::from_secs(60 * 60 * 24 * 365 * 100); |
| 7 | static FUTURE: LazyLock<Instant> = LazyLock::new(|| Instant::now() + YEARS_100); |
| 8 | *FUTURE |
| 9 | } |
| 10 | |
| 11 | // The goal here is to make a constant "beginning of time" in both Instant and SystemTime |
| 12 | // that we can use as relative values for the rest of str0m. |
| 13 | // This is indeed a bit dodgy, but we want str0m's internal idea of time to be completely |
| 14 | // driven from the external API using `Instant`. What works against us is that Instant can't |
| 15 | // represent things like UNIX EPOCH (but SystemTime can). |
| 16 | static BEGINNING_OF_TIME: LazyLock<(Instant, SystemTime)> = LazyLock::new(|| { |
| 17 | // These two should be "frozen" the same instant. Hopefully they are not differing too much. |
| 18 | let now = Instant::now(); |
| 19 | let now_sys = SystemTime::now(); |
| 20 | |
| 21 | // Find an Instant in the past which is up to an hour back. |
| 22 | let beginning_of_time = { |
| 23 | let mut secs = 3600; |
| 24 | loop { |
| 25 | let dur = Duration::from_secs(secs); |
| 26 | if let Some(v) = now.checked_sub(dur) { |
| 27 | break v; |
| 28 | } |
| 29 | secs -= 1; |
| 30 | if secs == 0 { |
| 31 | panic!("Failed to find a beginning of time instant"); |
| 32 | } |
| 33 | } |
| 34 | }; |
| 35 | |
| 36 | // This might be less than 1 hour if the machine uptime is less. |
| 37 | let since_beginning_of_time = Instant::now() - beginning_of_time; |
| 38 | |
| 39 | let beginning_of_time_sys = now_sys - since_beginning_of_time; |
| 40 | |
| 41 | // This pair represents our "beginning of time" for the same moment. |
| 42 | (beginning_of_time, beginning_of_time_sys) |
| 43 | }); |
| 44 | |
| 45 | pub fn epoch_to_beginning() -> Duration { |
| 46 | BEGINNING_OF_TIME |
| 47 | .1 |
| 48 | .duration_since(SystemTime::UNIX_EPOCH) |
| 49 | .expect("beginning of time to be after epoch") |
| 50 | } |
| 51 | |
| 52 | pub(crate) fn already_happened() -> Instant { |
| 53 | BEGINNING_OF_TIME.0 |
| 54 | } |
| 55 | |
| 56 | pub trait InstantExt { |
| 57 | /// Convert an Instant to a Duration for unix time. |
| 58 | /// |
| 59 | /// First ever time must be "now". |
| 60 | /// |
| 61 | /// panics if `time` goes backwards, i.e. we use this for one Instant and then an earlier Instant. |
| 62 | fn to_unix_duration(&self) -> Duration; |
| 63 | |
| 64 | /// Convert an Instant to a Duration for ntp time. |
| 65 | fn to_ntp_duration(&self) -> Duration; |
| 66 | |
| 67 | /// Convert an Instant to a SystemTime for ntp time |
| 68 | fn to_system_time(&self) -> SystemTime; |
| 69 | } |
| 70 | |
| 71 | pub trait SystemTimeExt { |
| 72 | /// Convert an ntp_64 as seen in SR to a SystemTime. |
| 73 | fn from_ntp_64(v: u64) -> SystemTime; |
| 74 | |
| 75 | /// Convert a SystemTime to ntp_64. |
| 76 | fn as_ntp_64(&self) -> u64; |
| 77 | } |
| 78 | |
| 79 | // RTP spec "wallclock" uses NTP time, which starts at 1900-01-01. |
| 80 | // |
| 81 | // https://tools.ietf.org/html/rfc868 |
| 82 | // |
| 83 | // 365 days * 70 years + 17 leap year days |
| 84 | // (365 * 70 + 17) * 86400 = 2208988800 |
| 85 | const SECS_1900: u64 = 2_208_988_800; |
| 86 | const MICROS_1900: u64 = SECS_1900 * 1_000_000; |
| 87 | |
| 88 | /// 2^32 as float. |
| 89 | const F32: f64 = 4_294_967_296.0; |
| 90 | |
| 91 | impl InstantExt for Instant { |
| 92 | fn to_unix_duration(&self) -> Duration { |
| 93 | // This is a bit fishy. We "freeze" a moment in time for Instant and SystemTime, |
| 94 | // so we can make relative comparisons of Instant - Instant and translate that to |
| 95 | // SystemTime - unix epoch. Hopefully the error is quite small. |
| 96 | if *self < BEGINNING_OF_TIME.0 { |
| 97 | warn!("{}", Backtrace::force_capture()); |
| 98 | warn!("Time went backwards from beginning_of_time Instant"); |
| 99 | } |
| 100 | |
| 101 | let duration_since_time_0 = self.duration_since(BEGINNING_OF_TIME.0); |
| 102 | let system_time = BEGINNING_OF_TIME.1 + duration_since_time_0; |
| 103 | |
| 104 | system_time |
| 105 | .duration_since(SystemTime::UNIX_EPOCH) |
| 106 | .expect("clock to go forwards from unix epoch") |
| 107 | } |
| 108 | |
| 109 | fn to_ntp_duration(&self) -> Duration { |
| 110 | self.to_unix_duration() + Duration::from_micros(MICROS_1900) |
| 111 | } |
| 112 | |
| 113 | fn to_system_time(&self) -> SystemTime { |
| 114 | // This is a bit fishy. We "freeze" a moment in time for Instant and SystemTime, |
| 115 | // so we can make relative comparisons of Instant - Instant and translate that to |
| 116 | // SystemTime - unix epoch. Hopefully the error is quite small. |
| 117 | if *self < BEGINNING_OF_TIME.0 { |
| 118 | warn!("{}", Backtrace::force_capture()); |
| 119 | warn!("Time went backwards from beginning_of_time Instant"); |
| 120 | } |
| 121 | |
| 122 | let duration_since_time_0 = self.duration_since(BEGINNING_OF_TIME.0); |
| 123 | BEGINNING_OF_TIME.1 + duration_since_time_0 |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | impl SystemTimeExt for SystemTime { |
| 128 | fn from_ntp_64(v: u64) -> SystemTime { |
| 129 | // https://tools.ietf.org/html/rfc3550#section-4 |
| 130 | // Wallclock time (absolute date and time) is represented using the |
| 131 | // timestamp format of the Network Time Protocol (NTP), which is in |
| 132 | // seconds relative to 0h UTC on 1 January 1900 [4]. The full |
| 133 | // resolution NTP timestamp is a 64-bit unsigned fixed-point number with |
| 134 | // the integer part in the first 32 bits and the fractional part in the |
| 135 | // last 32 bits. |
| 136 | let secs_ntp = (v as f64) / F32; |
| 137 | |
| 138 | // Shift to UNIX EPOCH |
| 139 | let secs_epoch = secs_ntp - SECS_1900 as f64; |
| 140 | |
| 141 | // Duration not allowed to be negative |
| 142 | let secs_dur = Duration::try_from_secs_f64(secs_epoch).unwrap_or(Duration::ZERO); |
| 143 | |
| 144 | // Time in SystemTime |
| 145 | SystemTime::UNIX_EPOCH + secs_dur |
| 146 | } |
| 147 | |
| 148 | fn as_ntp_64(&self) -> u64 { |
| 149 | let secs_epoch = if let Ok(value) = self.duration_since(SystemTime::UNIX_EPOCH) { |
| 150 | value.as_secs_f64() + SECS_1900 as f64 |
| 151 | } else { |
| 152 | 0.0 |
| 153 | }; |
| 154 | |
| 155 | (secs_epoch * F32) as u64 |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | #[cfg(test)] |
| 160 | mod test { |
| 161 | use super::*; |
| 162 | |
| 163 | #[test] |
| 164 | fn not_happening_works() { |
| 165 | assert_eq!(not_happening(), not_happening()); |
| 166 | assert!(Instant::now() < not_happening()); |
| 167 | } |
| 168 | |
| 169 | #[test] |
| 170 | fn already_happened_works() { |
| 171 | assert_eq!(already_happened(), already_happened()); |
| 172 | assert!(Instant::now() > already_happened()); |
| 173 | } |
| 174 | |
| 175 | #[test] |
| 176 | fn already_happened_ne() { |
| 177 | assert_ne!(not_happening(), already_happened()) |
| 178 | } |
| 179 | |
| 180 | #[test] |
| 181 | fn ntp_64_from_to() { |
| 182 | let now = SystemTime::now(); |
| 183 | let ntp = now.as_ntp_64(); |
| 184 | let now2 = SystemTime::from_ntp_64(ntp); |
| 185 | let abs = if now > now2 { |
| 186 | now.duration_since(now2) |
| 187 | } else { |
| 188 | now2.duration_since(now) |
| 189 | }; |
| 190 | assert!(abs.unwrap() < Duration::from_millis(1)); |
| 191 | } |
| 192 | |
| 193 | #[test] |
| 194 | fn from_ntp_64_zero() { |
| 195 | let s = SystemTime::from_ntp_64(0); |
| 196 | assert_eq!( |
| 197 | s.duration_since(SystemTime::UNIX_EPOCH).unwrap(), |
| 198 | Duration::ZERO |
| 199 | ); |
| 200 | } |
| 201 | |
| 202 | #[test] |
| 203 | fn from_ntp_64_val1() { |
| 204 | let s = SystemTime::from_ntp_64((3971792775u64 << 32) | 4184015405u64); |
| 205 | match s.duration_since(SystemTime::UNIX_EPOCH) { |
| 206 | Ok(n) => assert_eq!(n.as_micros(), 1762803975974166), |
| 207 | Err(_) => panic!("Cannot calculate unix epoch"), |
| 208 | } |
| 209 | } |
| 210 | } |