diff --git a/crates/rist-rs-bits/src/rtcp/mod.rs b/crates/rist-rs-bits/src/rtcp/mod.rs index 6c18dc3..eae25fc 100644 --- a/crates/rist-rs-bits/src/rtcp/mod.rs +++ b/crates/rist-rs-bits/src/rtcp/mod.rs @@ -297,7 +297,7 @@ impl<'a> Iterator for RTCPPacketViewIterator<'a> { mod test { use core::ops::Sub; - use rist_rs_types::traits::time::clock::StdSystemClock; + use rist_rs_types::{time::ntp, traits::time::clock::StdSystemClock}; use super::RTCPPacketView; use crate::rtcp::RTCPPacketViewIterator; diff --git a/crates/rist-rs-types/src/time/ntp.rs b/crates/rist-rs-types/src/time/ntp.rs index 48de7f2..a6615b6 100644 --- a/crates/rist-rs-types/src/time/ntp.rs +++ b/crates/rist-rs-types/src/time/ntp.rs @@ -1,7 +1,7 @@ use core::fmt::Display; use std::{ops::Add, time::Duration}; -use crate::traits::time::clock::Clock; +use crate::traits::time::clock::{Clock, TimePoint}; #[derive(Debug, Clone, Copy)] pub struct Timestamp { @@ -17,12 +17,20 @@ impl Display for Timestamp { impl Timestamp { const FRAC: f64 = std::u32::MAX as f64; - const EPOCH_DELTA: u64 = 2_208_988_800; pub fn new(sec: u32, frac: u32) -> Timestamp { Timestamp { sec, frac } } + pub fn from_time_point( + tp: C::TimePoint, + ) -> Result::Error> { + let ep = tp.duration_since(C::epoch())?; + let ns = (ep.subsec_nanos() as f64 * Self::FRAC * 1.0e-9) as u32; + let s = (ep.as_secs() as i64 + C::ntp_epoch_offset()) as u32; + Ok(Self::new(s, ns)) + } + pub fn seconds(&self) -> u32 { self.sec } @@ -45,7 +53,7 @@ impl Timestamp { pub fn to_instant(&self) -> C::TimePoint { C::epoch().add(Duration::new( - self.sec as u64 - Self::EPOCH_DELTA, + (self.sec as i64 - C::ntp_epoch_offset()) as u64, self.frac_ns() as u32, )) } diff --git a/crates/rist-rs-types/src/traits/time/clock/mod.rs b/crates/rist-rs-types/src/traits/time/clock/mod.rs index 5e135bb..7083274 100644 --- a/crates/rist-rs-types/src/traits/time/clock/mod.rs +++ b/crates/rist-rs-types/src/traits/time/clock/mod.rs @@ -64,7 +64,11 @@ pub trait Clock: Clone + Send + 'static { /// Returns true if the clocks time is monotonically increasing fn is_monotonic(&self) -> bool; + // This clocks epoch as a point in time fn epoch() -> Self::TimePoint; + + // Offset of this clocks epoch to the NTP epoch in seconds + fn ntp_epoch_offset() -> i64; } cfg_std! { @@ -94,6 +98,10 @@ cfg_std! { fn epoch() -> Self::TimePoint { std::time::UNIX_EPOCH } + + fn ntp_epoch_offset() -> i64 { + 2208988800 + } } impl TimePoint for SystemTime {