diff --git a/crates/timestamp/src/lib.rs b/crates/timestamp/src/lib.rs index a8bb0a562df..2d026af59fb 100644 --- a/crates/timestamp/src/lib.rs +++ b/crates/timestamp/src/lib.rs @@ -48,31 +48,39 @@ impl Timestamp { } } - pub fn signed_duration_since_secs(&self, start: Timestamps) -> f64 { + pub fn signed_duration_since_nanos(&self, start: Timestamps) -> i128 { match self { Self::Instant(instant) => { if let Some(duration) = instant.checked_duration_since(start.instant) { - duration.as_secs_f64() + i128::try_from(duration.as_nanos()).unwrap_or(i128::MAX) } else { - let reverse = start.instant.duration_since(*instant); - -(reverse.as_secs_f64()) + let reverse = start.instant.saturating_duration_since(*instant); + let nanos = i128::try_from(reverse.as_nanos()).unwrap_or(i128::MAX); + -nanos } } Self::SystemTime(time) => match time.duration_since(start.system_time) { - Ok(duration) => duration.as_secs_f64(), - Err(e) => -(e.duration().as_secs_f64()), + Ok(duration) => i128::try_from(duration.as_nanos()).unwrap_or(i128::MAX), + Err(e) => { + let nanos = i128::try_from(e.duration().as_nanos()).unwrap_or(i128::MAX); + -nanos + } }, #[cfg(windows)] Self::PerformanceCounter(counter) => { - counter.signed_duration_since_secs(start.performance_counter) + counter.signed_duration_since_nanos(start.performance_counter) } #[cfg(target_os = "macos")] Self::MachAbsoluteTime(time) => { - time.signed_duration_since_secs(start.mach_absolute_time) + time.signed_duration_since_nanos(start.mach_absolute_time) } } } + pub fn signed_duration_since_secs(&self, start: Timestamps) -> f64 { + self.signed_duration_since_nanos(start) as f64 / 1_000_000_000.0 + } + pub fn from_cpal(instant: cpal::StreamInstant) -> Self { #[cfg(windows)] { @@ -165,6 +173,11 @@ impl Timestamps { self.system_time } + #[cfg(windows)] + pub fn performance_counter(&self) -> PerformanceCounterTimestamp { + self.performance_counter + } + #[cfg(target_os = "macos")] pub fn mach_absolute_time(&self) -> MachAbsoluteTimestamp { self.mach_absolute_time diff --git a/crates/timestamp/src/macos.rs b/crates/timestamp/src/macos.rs index 178f6ae933b..799c3ab49bb 100644 --- a/crates/timestamp/src/macos.rs +++ b/crates/timestamp/src/macos.rs @@ -1,18 +1,47 @@ use cidre::mach::TimeBaseInfo; use std::{ ops::{Add, Sub}, + sync::OnceLock, time::Duration, }; -#[derive(Clone, Copy, Debug)] -pub struct MachAbsoluteTimestamp( - // Nanoseconds - u64, -); +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct MachAbsoluteTimestamp(u64); + +static TIMEBASE_RATIO: OnceLock<(u128, u128)> = OnceLock::new(); + +fn timebase_ratio() -> (u128, u128) { + *TIMEBASE_RATIO.get_or_init(|| { + let info = TimeBaseInfo::new(); + let numer = u128::from(info.numer.max(1)); + let denom = u128::from(info.denom.max(1)); + (numer, denom) + }) +} + +fn ticks_to_nanos_with_ratio(ticks: u64, numer: u128, denom: u128) -> u128 { + (u128::from(ticks) * numer + denom / 2) / denom +} + +fn nanos_to_ticks_with_ratio(nanos: u128, numer: u128, denom: u128) -> u64 { + let scaled = nanos.saturating_mul(denom); + let ticks = scaled.saturating_add(numer / 2) / numer; + u64::try_from(ticks).unwrap_or(u64::MAX) +} + +fn duration_from_nanos_u128(nanos: u128) -> Duration { + let secs = u64::try_from(nanos / 1_000_000_000).unwrap_or(u64::MAX); + let subsec_nanos = (nanos % 1_000_000_000) as u32; + if secs == u64::MAX { + Duration::MAX + } else { + Duration::new(secs, subsec_nanos) + } +} impl MachAbsoluteTimestamp { - pub fn new(nanos: u64) -> Self { - Self(nanos) + pub fn new(ticks: u64) -> Self { + Self(ticks) } pub fn now() -> Self { @@ -20,36 +49,33 @@ impl MachAbsoluteTimestamp { } pub fn duration_since(&self, other: Self) -> Duration { - let info = TimeBaseInfo::new(); - let freq = info.numer as f64 / info.denom as f64; - - let Some(diff) = self.0.checked_sub(other.0) else { - return Duration::ZERO; - }; - - Duration::from_nanos((diff as f64 * freq) as u64) + match self.checked_duration_since(other) { + Some(duration) => duration, + None => Duration::ZERO, + } } pub fn checked_duration_since(&self, other: Self) -> Option { - let info = TimeBaseInfo::new(); - let freq = info.numer as f64 / info.denom as f64; - let diff = self.0.checked_sub(other.0)?; - - Some(Duration::from_nanos((diff as f64 * freq) as u64)) + let (numer, denom) = timebase_ratio(); + let nanos = ticks_to_nanos_with_ratio(diff, numer, denom); + Some(duration_from_nanos_u128(nanos)) } - pub fn signed_duration_since_secs(&self, other: Self) -> f64 { - let info = TimeBaseInfo::new(); - let freq = info.numer as f64 / info.denom as f64; - - let nanos = if self.0 >= other.0 { - ((self.0 - other.0) as f64 * freq) as i64 + pub fn signed_duration_since_nanos(&self, other: Self) -> i128 { + let (numer, denom) = timebase_ratio(); + if self.0 >= other.0 { + let nanos = ticks_to_nanos_with_ratio(self.0 - other.0, numer, denom); + i128::try_from(nanos).unwrap_or(i128::MAX) } else { - -(((other.0 - self.0) as f64 * freq) as i64) - }; + let nanos = ticks_to_nanos_with_ratio(other.0 - self.0, numer, denom); + let clamped = i128::try_from(nanos).unwrap_or(i128::MAX); + -clamped + } + } - nanos as f64 / 1_000_000_000.0 + pub fn signed_duration_since_secs(&self, other: Self) -> f64 { + self.signed_duration_since_nanos(other) as f64 / 1_000_000_000.0 } pub fn from_cpal(instant: cpal::StreamInstant) -> Self { @@ -63,13 +89,12 @@ impl Add for MachAbsoluteTimestamp { type Output = Self; fn add(self, rhs: Duration) -> Self::Output { - let info = TimeBaseInfo::new(); // ns = ticks * numer / denom, so ticks = ns * denom / numer. // On Apple Silicon (numer/denom = 125/3) multiplying by numer/denom // instead would add ~1736x the intended duration. - let ticks = rhs.as_nanos() as f64 * info.denom as f64 / info.numer as f64; - - Self((self.0 as f64 + ticks) as u64) + let (numer, denom) = timebase_ratio(); + let ticks = nanos_to_ticks_with_ratio(rhs.as_nanos(), numer, denom); + Self(self.0.saturating_add(ticks)) } } @@ -77,10 +102,9 @@ impl Sub for MachAbsoluteTimestamp { type Output = Self; fn sub(self, rhs: Duration) -> Self::Output { - let info = TimeBaseInfo::new(); - let ticks = rhs.as_nanos() as f64 * info.denom as f64 / info.numer as f64; - - Self((self.0 as f64 - ticks).max(0.0) as u64) + let (numer, denom) = timebase_ratio(); + let ticks = nanos_to_ticks_with_ratio(rhs.as_nanos(), numer, denom); + Self(self.0.saturating_sub(ticks)) } } @@ -88,6 +112,15 @@ impl Sub for MachAbsoluteTimestamp { mod tests { use super::*; + #[test] + fn duration_since_returns_zero_when_earlier() { + let base = MachAbsoluteTimestamp::new(1_000); + let earlier = MachAbsoluteTimestamp::new(900); + + assert_eq!(earlier.duration_since(base), Duration::ZERO); + assert_eq!(earlier.checked_duration_since(base), None); + } + #[test] fn add_duration_roundtrips_through_duration_since() { let base = MachAbsoluteTimestamp::now(); @@ -128,4 +161,26 @@ mod tests { "add/sub of the same duration must cancel out, drifted {drift:?}" ); } + + #[test] + fn high_uptime_arithmetic_avoids_f64_precision_loss() { + let high_uptime = MachAbsoluteTimestamp::new((1u64 << 53) + 7); + assert_eq!(high_uptime + Duration::ZERO, high_uptime); + assert_eq!(high_uptime - Duration::ZERO, high_uptime); + + let step = Duration::from_millis(250); + let advanced = high_uptime + step; + assert!(advanced.0 > high_uptime.0); + assert_eq!(advanced - step, high_uptime); + + let forward_ns = advanced.signed_duration_since_nanos(high_uptime); + let backward_ns = high_uptime.signed_duration_since_nanos(advanced); + assert_eq!(forward_ns, -backward_ns); + assert!((forward_ns - 250_000_000).abs() <= 50); + + let ticks_6h = nanos_to_ticks_with_ratio(6 * 3_600 * 1_000_000_000, 125, 3); + assert_eq!(ticks_6h, 518_400_000_000); + let nanos_6h = ticks_to_nanos_with_ratio(ticks_6h, 125, 3); + assert_eq!(nanos_6h, 6 * 3_600 * 1_000_000_000); + } } diff --git a/crates/timestamp/src/master_clock.rs b/crates/timestamp/src/master_clock.rs index ff3e6a5cb7a..ec734811549 100644 --- a/crates/timestamp/src/master_clock.rs +++ b/crates/timestamp/src/master_clock.rs @@ -105,8 +105,8 @@ impl MasterClock { } pub fn remap_raw_ns(&self, source_ts: Timestamp) -> i64 { - let secs = source_ts.signed_duration_since_secs(self.timestamps); - seconds_to_ns_saturating(secs) + let nanos = source_ts.signed_duration_since_nanos(self.timestamps); + nanos.clamp(i128::from(i64::MIN), i128::from(i64::MAX)) as i64 } pub fn remap(&self, source_ts: Timestamp) -> i64 { @@ -130,19 +130,6 @@ fn samples_to_ns(samples: u64, rate: u32) -> u64 { } } -fn seconds_to_ns_saturating(secs: f64) -> i64 { - if !secs.is_finite() { - return 0; - } - let scaled = secs * 1_000_000_000.0; - if scaled >= i64::MAX as f64 { - i64::MAX - } else if scaled <= i64::MIN as f64 { - i64::MIN - } else { - scaled as i64 - } -} #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SourceClockOutcome { @@ -1313,4 +1300,25 @@ mod tests { } } } + + #[test] + fn remap_raw_ns_preserves_nanosecond_precision_over_multi_hour_recordings() { + let clock = clock(); + let offset = Duration::from_secs(6 * 3600) + Duration::from_nanos(123_456_789); + let future_instant = clock.start_instant() + offset; + + let remapped = clock.remap_raw_ns(Timestamp::Instant(future_instant)); + assert_eq!(remapped, offset.as_nanos() as i64); + } + + #[test] + fn remap_raw_ns_handles_negative_offsets_exactly() { + let clock = clock(); + let offset = Duration::from_millis(250) + Duration::from_nanos(7); + let base_system = clock.timestamps().system_time(); + let earlier_system = base_system.checked_sub(offset).unwrap(); + + let remapped = clock.remap_raw_ns(Timestamp::SystemTime(earlier_system)); + assert_eq!(remapped, -(offset.as_nanos() as i64)); + } } diff --git a/crates/timestamp/src/win.rs b/crates/timestamp/src/win.rs index c795e8fa997..685b2441636 100644 --- a/crates/timestamp/src/win.rs +++ b/crates/timestamp/src/win.rs @@ -6,7 +6,7 @@ use std::{ }; use windows::Win32::System::Performance::{QueryPerformanceCounter, QueryPerformanceFrequency}; -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct PerformanceCounterTimestamp(i128); static PERF_FREQ: OnceLock = OnceLock::new(); @@ -22,6 +22,26 @@ fn perf_freq() -> i64 { }) } +fn counter_diff_to_nanos(diff: i128, frequency: i64) -> i128 { + let freq = i128::from(frequency.max(1)); + let whole_secs = diff / freq; + let rem = diff % freq; + let rem_nanos = if rem >= 0 { + (rem * 1_000_000_000 + freq / 2) / freq + } else { + (rem * 1_000_000_000 - freq / 2) / freq + }; + let base_nanos = whole_secs.saturating_mul(1_000_000_000); + base_nanos.saturating_add(rem_nanos) +} + +fn duration_to_counter_ticks(duration: Duration, frequency: i64) -> i128 { + let freq = i128::from(frequency.max(1)); + let whole_ticks = i128::from(duration.as_secs()).saturating_mul(freq); + let subsec_ticks = (i128::from(duration.subsec_nanos()) * freq + 500_000_000) / 1_000_000_000; + whole_ticks.saturating_add(subsec_ticks) +} + impl PerformanceCounterTimestamp { pub fn new(value: i64) -> Self { Self(i128::from(value)) @@ -32,46 +52,44 @@ impl PerformanceCounterTimestamp { } pub fn duration_since(&self, other: Self) -> Duration { - let freq = perf_freq() as i128; - debug_assert!(freq > 0); - - let diff = self.0 - other.0; - - if diff <= 0 { - Duration::ZERO - } else { - let diff = diff as u128; - let freq = freq as u128; - - let secs = diff / freq; - let nanos = ((diff % freq) * 1_000_000_000u128) / freq; - - Duration::new(secs as u64, nanos as u32) + match self.checked_duration_since(other) { + Some(duration) => duration, + None => Duration::ZERO, } } pub fn checked_duration_since(&self, other: Self) -> Option { - let freq = perf_freq() as i128; + let freq = i128::from(perf_freq()); debug_assert!(freq > 0); let diff = self.0 - other.0; - if diff < 0 { - None - } else { - let diff = diff as u128; - let freq = freq as u128; + return None; + } - let secs = diff / freq; - let nanos = ((diff % freq) * 1_000_000_000u128) / freq; + let diff = diff as u128; + let freq = freq.max(1) as u128; + let mut secs = diff / freq; + let mut nanos = ((diff % freq) * 1_000_000_000u128 + freq / 2) / freq; + if nanos >= 1_000_000_000 { + secs += 1; + nanos -= 1_000_000_000; + } - Some(Duration::new(secs as u64, nanos as u32)) + let clamped_secs = u64::try_from(secs).unwrap_or(u64::MAX); + if clamped_secs == u64::MAX { + Some(Duration::MAX) + } else { + Some(Duration::new(clamped_secs, nanos as u32)) } } + pub fn signed_duration_since_nanos(&self, other: Self) -> i128 { + counter_diff_to_nanos(self.0 - other.0, perf_freq()) + } + pub fn signed_duration_since_secs(&self, other: Self) -> f64 { - let freq = perf_freq() as f64; - (self.0 - other.0) as f64 / freq + self.signed_duration_since_nanos(other) as f64 / 1_000_000_000.0 } pub fn now() -> Self { @@ -95,8 +113,8 @@ impl Add for PerformanceCounterTimestamp { type Output = Self; fn add(self, rhs: Duration) -> Self::Output { - let freq = perf_freq(); - Self(self.0 + (rhs.as_secs_f64() * freq as f64) as i128) + let ticks = duration_to_counter_ticks(rhs, perf_freq()); + Self(self.0.saturating_add(ticks)) } } @@ -104,8 +122,8 @@ impl Sub for PerformanceCounterTimestamp { type Output = Self; fn sub(self, rhs: Duration) -> Self::Output { - let freq = perf_freq(); - Self(self.0 - (rhs.as_secs_f64() * freq as f64) as i128) + let ticks = duration_to_counter_ticks(rhs, perf_freq()); + Self(self.0.saturating_sub(ticks)) } } @@ -165,4 +183,21 @@ mod tests { Duration::from_millis(10) ); } + + #[test] + fn high_uptime_duration_arithmetic_avoids_f64_precision_loss() { + let base = PerformanceCounterTimestamp::new((1i64 << 53) + 1); + assert_eq!(base + Duration::ZERO, base); + assert_eq!(base - Duration::ZERO, base); + + let delta = Duration::from_nanos(16_666_667); + let advanced = base + delta; + let expected_ticks = duration_to_counter_ticks(delta, perf_freq()); + assert_eq!(advanced.0 - base.0, expected_ticks); + assert_eq!(advanced - delta, base); + + let later = base + Duration::from_millis(500); + assert_eq!(later.signed_duration_since_nanos(base), 500_000_000); + assert_eq!(base.signed_duration_since_nanos(later), -500_000_000); + } }