Skip to content

Commit

Permalink
instant to ntp timestamp
Browse files Browse the repository at this point in the history
  • Loading branch information
jonasohland committed Dec 29, 2023
1 parent 9c85ed7 commit 889fec7
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 4 deletions.
2 changes: 1 addition & 1 deletion crates/rist-rs-bits/src/rtcp/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
14 changes: 11 additions & 3 deletions crates/rist-rs-types/src/time/ntp.rs
Original file line number Diff line number Diff line change
@@ -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 {
Expand All @@ -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<C: Clock>(
tp: C::TimePoint,
) -> Result<Timestamp, <C::TimePoint as TimePoint>::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
}
Expand All @@ -45,7 +53,7 @@ impl Timestamp {

pub fn to_instant<C: Clock>(&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,
))
}
Expand Down
8 changes: 8 additions & 0 deletions crates/rist-rs-types/src/traits/time/clock/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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! {
Expand Down Expand Up @@ -94,6 +98,10 @@ cfg_std! {
fn epoch() -> Self::TimePoint {
std::time::UNIX_EPOCH
}

fn ntp_epoch_offset() -> i64 {
2208988800
}
}

impl TimePoint for SystemTime {
Expand Down

0 comments on commit 889fec7

Please sign in to comment.