Skip to main content

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