Skip to main content

rtci_rtp/packet/
mod.rs

1#[cfg(test)]
2mod packet_test;
3#[cfg(test)]
4mod padding_size_test;
5
6use crate::header::*;
7use shared::{
8    error::{Error, Result},
9    marshal::{Marshal, MarshalSize, Unmarshal},
10};
11
12use bytes::{Buf, BufMut, Bytes};
13use std::fmt;
14
15/// Packet represents an RTP Packet
16/// NOTE: Raw is populated by Marshal/Unmarshal and should not be modified
17#[derive(Debug, Eq, PartialEq, Default, Clone)]
18pub struct Packet {
19    /// The packet header.
20    pub header: Header,
21    /// The media payload, in whatever format the payload type implies.
22    pub payload: Bytes,
23}
24
25impl fmt::Display for Packet {
26    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27        let mut out = "RTP PACKET:\n".to_string();
28
29        out += format!("\tVersion: {}\n", self.header.version).as_str();
30        out += format!("\tMarker: {}\n", self.header.marker).as_str();
31        out += format!("\tPayload Type: {}\n", self.header.payload_type).as_str();
32        out += format!("\tSequence Number: {}\n", self.header.sequence_number).as_str();
33        out += format!("\tTimestamp: {}\n", self.header.timestamp).as_str();
34        out += format!("\tSSRC: {} ({:x})\n", self.header.ssrc, self.header.ssrc).as_str();
35        out += format!("\tPayload Length: {}\n", self.payload.len()).as_str();
36
37        write!(f, "{out}")
38    }
39}
40
41impl Unmarshal for Packet {
42    /// Unmarshal parses the passed byte slice and stores the result in the Header this method is called upon
43    fn unmarshal<B>(raw_packet: &mut B) -> Result<Self>
44    where
45        Self: Sized,
46        B: Buf,
47    {
48        let mut header = Header::unmarshal(raw_packet)?;
49        let payload_len = raw_packet.remaining();
50        let payload = raw_packet.copy_to_bytes(payload_len);
51        if header.padding {
52            if payload_len > 0 {
53                let padding_len = payload[payload_len - 1] as usize;
54                if padding_len <= payload_len {
55                    // Kept, so the packet re-marshals with the padding it arrived with
56                    // (RFC 3550 5.1); a count of 0 is not valid padding and is not kept.
57                    header.padding_size = padding_len as u8;
58                    Ok(Packet {
59                        header,
60                        payload: payload.slice(..payload_len - padding_len),
61                    })
62                } else {
63                    Err(Error::ErrShortPacket)
64                }
65            } else {
66                Err(Error::ErrShortPacket)
67            }
68        } else {
69            Ok(Packet { header, payload })
70        }
71    }
72}
73
74impl MarshalSize for Packet {
75    /// MarshalSize returns the size of the packet once marshaled.
76    fn marshal_size(&self) -> usize {
77        let payload_len = self.payload.len();
78        self.header.marshal_size() + payload_len + self.padding_len()
79    }
80}
81
82impl Marshal for Packet {
83    /// MarshalTo serializes the packet and writes to the buffer.
84    fn marshal_to(&self, mut buf: &mut [u8]) -> Result<usize> {
85        if buf.remaining_mut() < self.marshal_size() {
86            return Err(Error::ErrBufferTooSmall);
87        }
88
89        let n = self.header.marshal_to(buf)?;
90        buf = &mut buf[n..];
91        buf.put(&*self.payload);
92        let padding_len = if self.header.padding {
93            let padding_len = self.padding_len();
94            for i in 0..padding_len {
95                if i != padding_len - 1 {
96                    buf.put_u8(0);
97                } else {
98                    buf.put_u8(padding_len as u8);
99                }
100            }
101            padding_len
102        } else {
103            0
104        };
105
106        Ok(n + self.payload.len() + padding_len)
107    }
108}
109
110impl Packet {
111    /// The padding octets marshal appends: the header's `padding_size` when set, else enough to
112    /// reach the next 32-bit boundary (at least one block of 4).
113    fn padding_len(&self) -> usize {
114        if !self.header.padding {
115            return 0;
116        }
117        if self.header.padding_size > 0 {
118            return usize::from(self.header.padding_size);
119        }
120        match get_padding(self.payload.len()) {
121            0 => 4,
122            padding_len => padding_len,
123        }
124    }
125}
126
127/// getPadding Returns the padding required to make the length a multiple of 4
128fn get_padding(len: usize) -> usize {
129    if len.is_multiple_of(4) {
130        0
131    } else {
132        4 - (len % 4)
133    }
134}