#[cfg(test)]
mod ntp_timestamp_extension_test;
use bytes::{Buf, BufMut};
use shared::{
error::{Error, Result},
marshal::{Marshal, MarshalSize, Unmarshal},
};
pub const NTP_64_URI: &str = "urn:ietf:params:rtp-hdrext:ntp-64";
pub const NTP_56_URI: &str = "urn:ietf:params:rtp-hdrext:ntp-56";
pub const NTP_64_EXTENSION_SIZE: usize = 8;
pub const NTP_56_EXTENSION_SIZE: usize = 7;
#[derive(PartialEq, Eq, Debug, Default, Copy, Clone)]
pub struct Ntp64Extension {
pub ntp_time: u64,
}
impl Unmarshal for Ntp64Extension {
fn unmarshal<B>(raw: &mut B) -> Result<Self>
where
Self: Sized,
B: Buf,
{
if raw.remaining() < NTP_64_EXTENSION_SIZE {
return Err(Error::ErrBufferTooSmall);
}
Ok(Self {
ntp_time: raw.get_u64(),
})
}
}
impl MarshalSize for Ntp64Extension {
fn marshal_size(&self) -> usize {
NTP_64_EXTENSION_SIZE
}
}
impl Marshal for Ntp64Extension {
fn marshal_to(&self, mut buf: &mut [u8]) -> Result<usize> {
if buf.remaining_mut() < NTP_64_EXTENSION_SIZE {
return Err(Error::ErrBufferTooSmall);
}
buf.put_u64(self.ntp_time);
Ok(NTP_64_EXTENSION_SIZE)
}
}
#[derive(PartialEq, Eq, Debug, Default, Copy, Clone)]
pub struct Ntp56Extension {
pub low_bits: u64,
}
impl Ntp56Extension {
pub fn new(ntp_time: u64) -> Self {
Self {
low_bits: ntp_time & 0x00FF_FFFF_FFFF_FFFF,
}
}
pub fn ntp_time(&self, sender_report_ntp: u64) -> u64 {
let base = sender_report_ntp & 0xFF00_0000_0000_0000;
let step = 1u64 << 56;
[base.wrapping_sub(step), base, base.wrapping_add(step)]
.into_iter()
.map(|upper| upper | self.low_bits)
.min_by_key(|candidate| candidate.abs_diff(sender_report_ntp))
.unwrap_or(base | self.low_bits)
}
}
impl Unmarshal for Ntp56Extension {
fn unmarshal<B>(raw: &mut B) -> Result<Self>
where
Self: Sized,
B: Buf,
{
if raw.remaining() < NTP_56_EXTENSION_SIZE {
return Err(Error::ErrBufferTooSmall);
}
let mut low_bits = 0u64;
for _ in 0..NTP_56_EXTENSION_SIZE {
low_bits = (low_bits << 8) | u64::from(raw.get_u8());
}
Ok(Self { low_bits })
}
}
impl MarshalSize for Ntp56Extension {
fn marshal_size(&self) -> usize {
NTP_56_EXTENSION_SIZE
}
}
impl Marshal for Ntp56Extension {
fn marshal_to(&self, mut buf: &mut [u8]) -> Result<usize> {
if buf.remaining_mut() < NTP_56_EXTENSION_SIZE {
return Err(Error::ErrBufferTooSmall);
}
for shift in (0..NTP_56_EXTENSION_SIZE).rev() {
buf.put_u8((self.low_bits >> (8 * shift)) as u8);
}
Ok(NTP_56_EXTENSION_SIZE)
}
}