rtc_rtp/extension/abs_send_time_extension/
mod.rs

1#[cfg(test)]
2mod abs_send_time_extension_test;
3
4use shared::{
5    error::{Error, Result},
6    marshal::{Marshal, MarshalSize, Unmarshal},
7};
8
9use bytes::{Buf, BufMut};
10
11pub const ABS_SEND_TIME_EXTENSION_SIZE: usize = 3;
12
13/// AbsSendTimeExtension is a extension payload format in
14/// <http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time>
15#[derive(PartialEq, Eq, Debug, Default, Copy, Clone)]
16pub struct AbsSendTimeExtension {
17    pub timestamp: u64,
18}
19
20impl Unmarshal for AbsSendTimeExtension {
21    /// Unmarshal parses the passed byte slice and stores the result in the members.
22    fn unmarshal<B>(raw_packet: &mut B) -> Result<Self>
23    where
24        Self: Sized,
25        B: Buf,
26    {
27        if raw_packet.remaining() < ABS_SEND_TIME_EXTENSION_SIZE {
28            return Err(Error::ErrBufferTooSmall);
29        }
30
31        let b0 = raw_packet.get_u8();
32        let b1 = raw_packet.get_u8();
33        let b2 = raw_packet.get_u8();
34        let timestamp = (b0 as u64) << 16 | (b1 as u64) << 8 | b2 as u64;
35
36        Ok(AbsSendTimeExtension { timestamp })
37    }
38}
39
40impl MarshalSize for AbsSendTimeExtension {
41    /// MarshalSize returns the size of the AbsSendTimeExtension once marshaled.
42    fn marshal_size(&self) -> usize {
43        ABS_SEND_TIME_EXTENSION_SIZE
44    }
45}
46
47impl Marshal for AbsSendTimeExtension {
48    /// MarshalTo serializes the members to buffer.
49    fn marshal_to(&self, mut buf: &mut [u8]) -> Result<usize> {
50        if buf.remaining_mut() < ABS_SEND_TIME_EXTENSION_SIZE {
51            return Err(Error::ErrBufferTooSmall);
52        }
53
54        buf.put_u8(((self.timestamp & 0xFF0000) >> 16) as u8);
55        buf.put_u8(((self.timestamp & 0xFF00) >> 8) as u8);
56        buf.put_u8((self.timestamp & 0xFF) as u8);
57
58        Ok(ABS_SEND_TIME_EXTENSION_SIZE)
59    }
60}
61
62impl AbsSendTimeExtension {
63    /// NewAbsSendTimeExtension makes new AbsSendTimeExtension from time.Time.
64    pub fn new(send_time_ntp: u64) -> Self {
65        AbsSendTimeExtension {
66            timestamp: /*unix2ntp(send_time)*/ send_time_ntp >> 14,
67        }
68    }
69
70    /// Estimate absolute send time according to the receive time.
71    /// Note that if the transmission delay is larger than 64 seconds, estimated time will be wrong.
72    pub fn estimate(&self, receive_ntp: u64) -> u64 {
73        //let receive_ntp = unix2ntp(receive);
74        let mut ntp = receive_ntp & 0xFFFFFFC000000000 | (self.timestamp & 0xFFFFFF) << 14;
75        if receive_ntp < ntp {
76            // Receive time must be always later than send time
77            ntp -= 0x1000000 << 14;
78        }
79
80        ntp
81        //ntp2unix(ntp)
82    }
83}