rtc-rtp 0.9.0

RTC RTP in Rust
Documentation
#[cfg(test)]
mod abs_send_time_extension_test;

use shared::{
    error::{Error, Result},
    marshal::{Marshal, MarshalSize, Unmarshal},
};

use bytes::{Buf, BufMut};

pub const ABS_SEND_TIME_EXTENSION_SIZE: usize = 3;

/// AbsSendTimeExtension is a extension payload format in
/// <http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time>
#[derive(PartialEq, Eq, Debug, Default, Copy, Clone)]
pub struct AbsSendTimeExtension {
    pub timestamp: u64,
}

impl Unmarshal for AbsSendTimeExtension {
    /// Unmarshal parses the passed byte slice and stores the result in the members.
    fn unmarshal<B>(raw_packet: &mut B) -> Result<Self>
    where
        Self: Sized,
        B: Buf,
    {
        if raw_packet.remaining() < ABS_SEND_TIME_EXTENSION_SIZE {
            return Err(Error::ErrBufferTooSmall);
        }

        let b0 = raw_packet.get_u8();
        let b1 = raw_packet.get_u8();
        let b2 = raw_packet.get_u8();
        let timestamp = (b0 as u64) << 16 | (b1 as u64) << 8 | b2 as u64;

        Ok(AbsSendTimeExtension { timestamp })
    }
}

impl MarshalSize for AbsSendTimeExtension {
    /// MarshalSize returns the size of the AbsSendTimeExtension once marshaled.
    fn marshal_size(&self) -> usize {
        ABS_SEND_TIME_EXTENSION_SIZE
    }
}

impl Marshal for AbsSendTimeExtension {
    /// MarshalTo serializes the members to buffer.
    fn marshal_to(&self, mut buf: &mut [u8]) -> Result<usize> {
        if buf.remaining_mut() < ABS_SEND_TIME_EXTENSION_SIZE {
            return Err(Error::ErrBufferTooSmall);
        }

        buf.put_u8(((self.timestamp & 0xFF0000) >> 16) as u8);
        buf.put_u8(((self.timestamp & 0xFF00) >> 8) as u8);
        buf.put_u8((self.timestamp & 0xFF) as u8);

        Ok(ABS_SEND_TIME_EXTENSION_SIZE)
    }
}

impl AbsSendTimeExtension {
    /// NewAbsSendTimeExtension makes new AbsSendTimeExtension from time.Time.
    pub fn new(send_time_ntp: u64) -> Self {
        AbsSendTimeExtension {
            timestamp: /*unix2ntp(send_time)*/ send_time_ntp >> 14,
        }
    }

    /// Estimate absolute send time according to the receive time.
    /// Note that if the transmission delay is larger than 64 seconds, estimated time will be wrong.
    pub fn estimate(&self, receive_ntp: u64) -> u64 {
        //let receive_ntp = unix2ntp(receive);
        let mut ntp = receive_ntp & 0xFFFFFFC000000000 | (self.timestamp & 0xFFFFFF) << 14;
        if receive_ntp < ntp {
            // Receive time must be always later than send time
            ntp -= 0x1000000 << 14;
        }

        ntp
        //ntp2unix(ntp)
    }
}