Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 21 additions & 8 deletions crates/timestamp/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
{
Expand Down Expand Up @@ -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
Expand Down
129 changes: 92 additions & 37 deletions crates/timestamp/src/macos.rs
Original file line number Diff line number Diff line change
@@ -1,55 +1,81 @@
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 {
Self(cidre::mach::abs_time())
}

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<Duration> {
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 {
Expand All @@ -63,31 +89,38 @@ impl Add<Duration> 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))
}
}

impl Sub<Duration> 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))
}
}

#[cfg(test)]
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();
Expand Down Expand Up @@ -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);
}
}
38 changes: 23 additions & 15 deletions crates/timestamp/src/master_clock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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 {
Expand Down Expand Up @@ -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));
}
}
Loading