Skip to main content

rtci_rtcp/
raw_packet.rs

1use crate::{Packet, header::*, util::*};
2
3use shared::{
4    error::{Error, Result},
5    marshal::{Marshal, MarshalSize, Unmarshal},
6};
7
8use bytes::{Buf, BufMut, Bytes};
9use std::any::Any;
10use std::fmt;
11
12/// RawPacket represents an unparsed RTCP packet. It's returned by Unmarshal when
13/// a packet with an unknown type is encountered.
14#[derive(Debug, PartialEq, Eq, Default, Clone)]
15pub struct RawPacket(pub Bytes);
16
17impl fmt::Display for RawPacket {
18    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
19        write!(f, "RawPacket: {self:?}")
20    }
21}
22
23impl Packet for RawPacket {
24    /// Header returns the Header associated with this packet.
25    fn header(&self) -> Header {
26        Header::unmarshal(&mut self.0.clone()).unwrap_or_default()
27    }
28
29    /// destination_ssrc returns an array of SSRC values that this packet refers to.
30    fn destination_ssrc(&self) -> Vec<u32> {
31        vec![]
32    }
33
34    fn raw_size(&self) -> usize {
35        self.0.len()
36    }
37
38    fn as_any(&self) -> &dyn Any {
39        self
40    }
41
42    fn equal(&self, other: &dyn Packet) -> bool {
43        other.as_any().downcast_ref::<RawPacket>() == Some(self)
44    }
45
46    fn cloned(&self) -> Box<dyn Packet> {
47        Box::new(self.clone())
48    }
49}
50
51impl MarshalSize for RawPacket {
52    fn marshal_size(&self) -> usize {
53        let l = self.raw_size();
54        // align to 32-bit boundary
55        l + get_padding_size(l)
56    }
57}
58
59impl Marshal for RawPacket {
60    /// Marshal encodes the packet in binary.
61    fn marshal_to(&self, mut buf: &mut [u8]) -> Result<usize> {
62        let h = Header::unmarshal(&mut self.0.clone())?;
63        buf.put(self.0.clone());
64        if h.padding {
65            put_padding(buf, self.raw_size());
66        }
67        Ok(self.marshal_size())
68    }
69}
70
71impl Unmarshal for RawPacket {
72    /// Unmarshal decodes the packet from binary.
73    fn unmarshal<B>(raw_packet: &mut B) -> Result<Self>
74    where
75        Self: Sized,
76        B: Buf,
77    {
78        if raw_packet.remaining() < HEADER_LENGTH {
79            return Err(Error::PacketTooShort);
80        }
81
82        // The bytes are kept exactly as they arrived, the type octet included: a packet of a
83        // type this crate does not model is written back as what it was.
84        let raw = raw_packet.copy_to_bytes(raw_packet.remaining());
85        Header::unmarshal(&mut raw.clone())?;
86
87        Ok(RawPacket(raw))
88    }
89}
90
91#[cfg(test)]
92mod test {
93    use super::*;
94
95    #[test]
96    fn test_raw_packet_roundtrip() -> Result<()> {
97        let tests: Vec<(&str, RawPacket, Option<Error>)> = vec![
98            (
99                "valid",
100                RawPacket(Bytes::from_static(&[
101                    0x81, 0xcb, 0x00, 0x0c, // v=2, p=0, count=1, BYE, len=12
102                    0x90, 0x2f, 0x9e, 0x2e, // ssrc=0x902f9e2e
103                    0x03, 0x46, 0x4f, 0x4f, // len=3, text=FOO
104                ])),
105                None,
106            ),
107            (
108                "short header",
109                RawPacket(Bytes::from_static(&[0x80])),
110                Some(Error::PacketTooShort),
111            ),
112            (
113                "invalid header",
114                RawPacket(
115                    // v=0, p=0, count=0, RR, len=4
116                    Bytes::from_static(&[0x00, 0xc9, 0x00, 0x04]),
117                ),
118                Some(Error::BadVersion),
119            ),
120        ];
121
122        for (name, pkt, unmarshal_error) in tests {
123            let result = pkt.marshal();
124            assert_eq!(
125                result.is_err(),
126                unmarshal_error.is_some(),
127                "Unmarshal {name}: err = {result:?}, want {unmarshal_error:?}"
128            );
129
130            if result.is_err() {
131                continue;
132            }
133
134            let mut data = result.unwrap();
135
136            let result = RawPacket::unmarshal(&mut data);
137
138            assert_eq!(
139                result.is_err(),
140                unmarshal_error.is_some(),
141                "Unmarshal {name}: err = {result:?}, want {unmarshal_error:?}"
142            );
143
144            if result.is_err() {
145                continue;
146            }
147
148            let decoded = result.unwrap();
149
150            assert_eq!(
151                decoded, pkt,
152                "{name} raw round trip: got {decoded:?}, want {pkt:?}"
153            )
154        }
155
156        Ok(())
157    }
158}