Skip to main content

rtci_rtcp/
packet.rs

1use crate::{
2    application_defined::*, goodbye::*, header::*,
3    payload_feedbacks::application_layer_feedback::*, payload_feedbacks::full_intra_request::*,
4    payload_feedbacks::layer_refresh_request::*, payload_feedbacks::picture_loss_indication::*,
5    payload_feedbacks::receiver_estimated_maximum_bitrate::*,
6    payload_feedbacks::reference_picture_selection_indication::*,
7    payload_feedbacks::slice_loss_indication::*, payload_feedbacks::temporal_spatial_tradeoff::*,
8    payload_feedbacks::video_back_channel_message::*, raw_packet::*, receiver_report::*,
9    sender_report::*, source_description::*, transport_feedbacks::cc_feedback_report::*,
10    transport_feedbacks::ecn_feedback::*, transport_feedbacks::pause_resume::*,
11    transport_feedbacks::rapid_resynchronization_request::*, transport_feedbacks::tmmb::*,
12    transport_feedbacks::transport_layer_cc::*, transport_feedbacks::transport_layer_nack::*,
13};
14use shared::{
15    error::{Error, Result},
16    marshal::{Marshal, Unmarshal},
17};
18
19use crate::extended_report::ExtendedReport;
20use bytes::{Buf, BufMut, Bytes, BytesMut};
21use std::any::Any;
22use std::fmt;
23
24/// Packet represents an RTCP packet, a protocol used for out-of-band statistics and
25/// control information for an RTP session
26pub trait Packet: Send + Sync + Marshal + Unmarshal + fmt::Display + fmt::Debug {
27    /// This packet's RTCP header.
28    fn header(&self) -> Header;
29    /// The SSRCs this packet is about.
30    ///
31    /// Used to route feedback: a report's destination SSRCs identify the streams it concerns,
32    /// which is how an SFU decides where to forward it.
33    fn destination_ssrc(&self) -> Vec<u32>;
34    /// The encoded size in bytes, header and padding included.
35    fn raw_size(&self) -> usize;
36    /// Downcasting hook, so a caller holding `Box<dyn Packet>` can recover the concrete type.
37    fn as_any(&self) -> &dyn Any;
38    /// Compares against another packet, since `PartialEq` is not object safe.
39    fn equal(&self, other: &dyn Packet) -> bool;
40    /// Clones this packet behind a trait object, since `Clone` is not object safe.
41    fn cloned(&self) -> Box<dyn Packet>;
42}
43
44impl PartialEq for dyn Packet {
45    fn eq(&self, other: &Self) -> bool {
46        self.equal(other)
47    }
48}
49
50impl Clone for Box<dyn Packet> {
51    fn clone(&self) -> Box<dyn Packet> {
52        self.cloned()
53    }
54}
55
56/// marshal takes an array of Packets and serializes them to a single buffer
57pub fn marshal(packets: &[Box<dyn Packet>]) -> Result<BytesMut> {
58    // Size the compound packet up front and marshal each sub-packet straight
59    // into it, instead of allocating a fresh BytesMut per sub-packet
60    // (p.marshal()) and copying it in.
61    let total: usize = packets.iter().map(|p| p.marshal_size()).sum();
62    let mut out = BytesMut::new();
63    out.resize(total, 0);
64    let mut offset = 0;
65    for p in packets {
66        offset += p.marshal_to(&mut out[offset..])?;
67    }
68    Ok(out)
69}
70
71/// Unmarshal takes an entire udp datagram (which may consist of multiple RTCP packets) and
72/// returns the unmarshaled packets it contains.
73///
74/// The datagram may be a compound packet (RFC 3550 ยง6.1) or a reduced-size one (RFC 5506): no
75/// leading SR or RR is required. Use [`crate::compound_packet::validate_compound`] for the
76/// header checks of RFC 3550 Appendix A.2.
77///
78/// A packet of a type or feedback format this crate does not model comes back as a
79/// [`RawPacket`] holding its bytes. A packet of a known type that is malformed fails the whole
80/// datagram; [`unmarshal_lenient`] keeps the others.
81pub fn unmarshal<B>(raw_data: &mut B) -> Result<Vec<Box<dyn Packet>>>
82where
83    B: Buf,
84{
85    let mut packets = vec![];
86
87    while raw_data.has_remaining() {
88        let p = unmarshaller(raw_data)?;
89        packets.push(p);
90    }
91
92    match packets.len() {
93        // Empty Packet
94        0 => Err(Error::InvalidHeader),
95
96        // Multiple Packet
97        _ => Ok(packets),
98    }
99}
100
101/// Like [`unmarshal`], but a packet of a known type that fails its own parse does not cost the
102/// datagram: it comes back as a [`RawPacket`] with its bytes, and the packets around it are
103/// parsed as usual.
104///
105/// The framing is not negotiable: a bad version, or a length that runs past the datagram,
106/// leaves no way to find the next packet and fails the datagram here too.
107pub fn unmarshal_lenient<B>(raw_data: &mut B) -> Result<Vec<Box<dyn Packet>>>
108where
109    B: Buf,
110{
111    let mut packets: Vec<Box<dyn Packet>> = vec![];
112
113    while raw_data.has_remaining() {
114        let framed = next_packet(raw_data)?;
115        match parse_packet(&framed) {
116            Ok(p) => packets.push(p),
117            Err(_) => packets.push(Box::new(RawPacket(framed.whole()))),
118        }
119    }
120
121    if packets.is_empty() {
122        return Err(Error::InvalidHeader);
123    }
124    Ok(packets)
125}
126
127/// One RTCP packet cut off a datagram: its four header octets and the `length` words after
128/// them.
129///
130/// The two are kept apart so that the body of a packet read from a `Bytes` stays a view of
131/// the datagram: nothing is copied or allocated to frame a packet of a type this crate parses.
132pub(crate) struct FramedPacket {
133    header: [u8; HEADER_LENGTH],
134    body: Bytes,
135}
136
137impl FramedPacket {
138    /// The packet as it arrived, in one buffer: what an unparsed packet keeps.
139    fn whole(&self) -> Bytes {
140        let mut packet = BytesMut::with_capacity(HEADER_LENGTH + self.body.len());
141        packet.put_slice(&self.header);
142        packet.put_slice(&self.body);
143        packet.freeze()
144    }
145
146    /// The packet as a reader for the type-specific parser, which reads the header again.
147    fn reader(&self) -> impl Buf + '_ {
148        self.header.as_slice().chain(self.body.clone())
149    }
150}
151
152/// Cuts the first RTCP packet off a datagram by the header's length field.
153pub(crate) fn next_packet<B>(raw_data: &mut B) -> Result<FramedPacket>
154where
155    B: Buf,
156{
157    if raw_data.remaining() < HEADER_LENGTH {
158        return Err(Error::PacketTooShort);
159    }
160    let mut header = [0u8; HEADER_LENGTH];
161    raw_data.copy_to_slice(&mut header);
162    if (header[0] >> VERSION_SHIFT) & VERSION_MASK != RTP_VERSION {
163        return Err(Error::BadVersion);
164    }
165
166    let length = u16::from_be_bytes([header[2], header[3]]) as usize * 4;
167    if length > raw_data.remaining() {
168        return Err(Error::PacketTooShort);
169    }
170
171    Ok(FramedPacket {
172        header,
173        body: raw_data.copy_to_bytes(length),
174    })
175}
176
177/// Parses one RTCP packet.
178fn parse_packet(framed: &FramedPacket) -> Result<Box<dyn Packet>> {
179    let format = (framed.header[0] >> COUNT_SHIFT) & COUNT_MASK;
180    let in_packet = &mut framed.reader();
181
182    let p: Box<dyn Packet> = match PacketType::from(framed.header[1]) {
183        PacketType::SenderReport => Box::new(SenderReport::unmarshal(in_packet)?),
184        PacketType::ReceiverReport => Box::new(ReceiverReport::unmarshal(in_packet)?),
185        PacketType::SourceDescription => Box::new(SourceDescription::unmarshal(in_packet)?),
186        PacketType::Goodbye => Box::new(Goodbye::unmarshal(in_packet)?),
187        PacketType::ApplicationDefined => Box::new(ApplicationDefined::unmarshal(in_packet)?),
188
189        PacketType::TransportSpecificFeedback => match format {
190            FORMAT_TLN => Box::new(TransportLayerNack::unmarshal(in_packet)?),
191            FORMAT_TMMBR => Box::new(TemporaryMaximumBitrateRequest::unmarshal(in_packet)?),
192            FORMAT_TMMBN => Box::new(TemporaryMaximumBitrateNotification::unmarshal(in_packet)?),
193            FORMAT_RRR => Box::new(RapidResynchronizationRequest::unmarshal(in_packet)?),
194            FORMAT_TCC => Box::new(TransportLayerCc::unmarshal(in_packet)?),
195            FORMAT_CCFB => Box::new(CcFeedbackReport::unmarshal(in_packet)?),
196            FORMAT_ECN => Box::new(EcnFeedback::unmarshal(in_packet)?),
197            FORMAT_PAUSE_RESUME => Box::new(PauseResume::unmarshal(in_packet)?),
198            _ => Box::new(RawPacket(framed.whole())),
199        },
200        PacketType::PayloadSpecificFeedback => match format {
201            FORMAT_PLI => Box::new(PictureLossIndication::unmarshal(in_packet)?),
202            FORMAT_SLI => Box::new(SliceLossIndication::unmarshal(in_packet)?),
203            FORMAT_RPSI => Box::new(ReferencePictureSelectionIndication::unmarshal(in_packet)?),
204            FORMAT_FIR => Box::new(FullIntraRequest::unmarshal(in_packet)?),
205            FORMAT_TSTR => Box::new(TemporalSpatialTradeoffRequest::unmarshal(in_packet)?),
206            FORMAT_TSTN => Box::new(TemporalSpatialTradeoffNotification::unmarshal(in_packet)?),
207            FORMAT_VBCM => Box::new(VideoBackChannelMessage::unmarshal(in_packet)?),
208            FORMAT_LRR => Box::new(LayerRefreshRequest::unmarshal(in_packet)?),
209            // RFC 4585 6.4: the application identifies its own messages. REMB does so by the
210            // four octets that open its FCI; anything else is some other application's.
211            FORMAT_AFB if is_remb(&framed.body) => {
212                Box::new(ReceiverEstimatedMaximumBitrate::unmarshal(in_packet)?)
213            }
214            FORMAT_AFB => Box::new(ApplicationLayerFeedback::unmarshal(in_packet)?),
215            _ => Box::new(RawPacket(framed.whole())),
216        },
217        PacketType::ExtendedReport => Box::new(ExtendedReport::unmarshal(in_packet)?),
218        _ => Box::new(RawPacket(framed.whole())),
219    };
220
221    Ok(p)
222}
223
224/// unmarshaller is a factory which pulls the first RTCP packet from a bytestream,
225/// and returns it's parsed representation, and the amount of data that was processed.
226pub(crate) fn unmarshaller<B>(raw_data: &mut B) -> Result<Box<dyn Packet>>
227where
228    B: Buf,
229{
230    parse_packet(&next_packet(raw_data)?)
231}
232
233#[cfg(test)]
234mod test {
235    use super::*;
236    use crate::reception_report::*;
237    use bytes::Bytes;
238
239    #[test]
240    fn test_packet_unmarshal() {
241        let mut data = Bytes::from_static(&[
242            // Receiver Report (offset=0)
243            0x81, 0xc9, 0x0, 0x7, // v=2, p=0, count=1, RR, len=7
244            0x90, 0x2f, 0x9e, 0x2e, // ssrc=0x902f9e2e
245            0xbc, 0x5e, 0x9a, 0x40, // ssrc=0xbc5e9a40
246            0x0, 0x0, 0x0, 0x0, // fracLost=0, totalLost=0
247            0x0, 0x0, 0x46, 0xe1, // lastSeq=0x46e1
248            0x0, 0x0, 0x1, 0x11, // jitter=273
249            0x9, 0xf3, 0x64, 0x32, // lsr=0x9f36432
250            0x0, 0x2, 0x4a, 0x79, // delay=150137
251            // Source Description (offset=32)
252            0x81, 0xca, 0x0, 0xc, // v=2, p=0, count=1, SDES, len=12
253            0x90, 0x2f, 0x9e, 0x2e, // ssrc=0x902f9e2e
254            0x1, 0x26, // CNAME, len=38
255            0x7b, 0x39, 0x63, 0x30, 0x30, 0x65, 0x62, 0x39, 0x32, 0x2d, 0x31, 0x61, 0x66, 0x62,
256            0x2d, 0x39, 0x64, 0x34, 0x39, 0x2d, 0x61, 0x34, 0x37, 0x64, 0x2d, 0x39, 0x31, 0x66,
257            0x36, 0x34, 0x65, 0x65, 0x65, 0x36, 0x39, 0x66, 0x35,
258            0x7d, // text="{9c00eb92-1afb-9d49-a47d-91f64eee69f5}"
259            0x0, 0x0, 0x0, 0x0, // END + padding
260            // Goodbye (offset=84)
261            0x81, 0xcb, 0x0, 0x1, // v=2, p=0, count=1, BYE, len=1
262            0x90, 0x2f, 0x9e, 0x2e, // source=0x902f9e2e
263            0x81, 0xce, 0x0, 0x2, // Picture Loss Indication (offset=92)
264            0x90, 0x2f, 0x9e, 0x2e, // sender=0x902f9e2e
265            0x90, 0x2f, 0x9e, 0x2e, // media=0x902f9e2e
266            0x85, 0xcd, 0x0, 0x2, // RapidResynchronizationRequest (offset=104)
267            0x90, 0x2f, 0x9e, 0x2e, // sender=0x902f9e2e
268            0x90, 0x2f, 0x9e, 0x2e, // media=0x902f9e2e
269        ]);
270
271        let packet = unmarshal(&mut data).expect("Error unmarshalling packets");
272
273        let a = ReceiverReport {
274            ssrc: 0x902f9e2e,
275            reports: vec![ReceptionReport {
276                ssrc: 0xbc5e9a40,
277                fraction_lost: 0,
278                total_lost: 0,
279                last_sequence_number: 0x46e1,
280                jitter: 273,
281                last_sender_report: 0x9f36432,
282                delay: 150137,
283            }],
284            ..Default::default()
285        };
286
287        let b = SourceDescription {
288            chunks: vec![SourceDescriptionChunk {
289                source: 0x902f9e2e,
290                items: vec![SourceDescriptionItem {
291                    sdes_type: SdesType::SdesCname,
292                    text: Bytes::from_static(b"{9c00eb92-1afb-9d49-a47d-91f64eee69f5}"),
293                }],
294            }],
295        };
296
297        let c = Goodbye {
298            sources: vec![0x902f9e2e],
299            ..Default::default()
300        };
301
302        let d = PictureLossIndication {
303            sender_ssrc: 0x902f9e2e,
304            media_ssrc: 0x902f9e2e,
305        };
306
307        let e = RapidResynchronizationRequest {
308            sender_ssrc: 0x902f9e2e,
309            media_ssrc: 0x902f9e2e,
310        };
311
312        let expected: Vec<Box<dyn Packet>> = vec![
313            Box::new(a),
314            Box::new(b),
315            Box::new(c),
316            Box::new(d),
317            Box::new(e),
318        ];
319
320        assert!(packet == expected, "Invalid packets");
321    }
322
323    #[test]
324    fn test_packet_unmarshal_empty() -> Result<()> {
325        let result = unmarshal(&mut Bytes::new());
326        if let Err(got) = result {
327            let want = Error::InvalidHeader;
328            assert_eq!(got, want, "Unmarshal(nil) err = {got}, want {want}");
329        } else {
330            panic!("want error");
331        }
332
333        Ok(())
334    }
335
336    #[test]
337    fn test_packet_invalid_header_length() -> Result<()> {
338        let mut data = Bytes::from_static(&[
339            // Goodbye (offset=84)
340            // v=2, p=0, count=1, BYE, len=100
341            0x81, 0xcb, 0x0, 0x64,
342        ]);
343
344        let result = unmarshal(&mut data);
345        if let Err(got) = result {
346            let want = Error::PacketTooShort;
347            assert_eq!(
348                got, want,
349                "Unmarshal(invalid_header_length) err = {got}, want {want}"
350            );
351        } else {
352            panic!("want error");
353        }
354
355        Ok(())
356    }
357    #[test]
358    fn test_packet_unmarshal_firefox() -> Result<()> {
359        // issue report from https://github.com/webrtc-rs/srtp/issues/7
360        let tests = vec![
361            Bytes::from_static(&[
362                143, 205, 0, 6, 65, 227, 184, 49, 118, 243, 78, 96, 42, 63, 0, 5, 12, 162, 166, 0,
363                32, 5, 200, 4, 0, 4, 0, 0,
364            ]),
365            Bytes::from_static(&[
366                143, 205, 0, 9, 65, 227, 184, 49, 118, 243, 78, 96, 42, 68, 0, 17, 12, 162, 167, 1,
367                32, 17, 88, 0, 4, 0, 4, 8, 108, 0, 4, 0, 4, 12, 0, 4, 0, 4, 4, 0,
368            ]),
369            Bytes::from_static(&[
370                143, 205, 0, 8, 65, 227, 184, 49, 118, 243, 78, 96, 42, 91, 0, 12, 12, 162, 168, 3,
371                32, 12, 220, 4, 0, 4, 0, 8, 128, 4, 0, 4, 0, 8, 0, 0,
372            ]),
373            Bytes::from_static(&[
374                143, 205, 0, 7, 65, 227, 184, 49, 118, 243, 78, 96, 42, 103, 0, 8, 12, 162, 169, 4,
375                32, 8, 232, 4, 0, 4, 0, 4, 4, 0, 0, 0,
376            ]),
377        ];
378
379        for mut test in tests {
380            unmarshal(&mut test)?;
381        }
382
383        Ok(())
384    }
385
386    // Round-trips a compound through packet::marshal -> packet::unmarshal ->
387    // packet::marshal and asserts byte-stability, covering the in-place compound
388    // marshal and the sub-packet unmarshaller.
389    #[test]
390    fn test_marshal_compound_roundtrip() -> Result<()> {
391        use crate::reception_report::ReceptionReport;
392
393        let rr = ReceiverReport {
394            ssrc: 0x902f9e2e,
395            reports: vec![ReceptionReport {
396                ssrc: 0xbc5e9a40,
397                fraction_lost: 0,
398                total_lost: 0,
399                last_sequence_number: 0x46e1,
400                jitter: 273,
401                last_sender_report: 0x9f36432,
402                delay: 150137,
403            }],
404            ..Default::default()
405        };
406        let pli = PictureLossIndication {
407            sender_ssrc: 0x902f9e2e,
408            media_ssrc: 0x902f9e2e,
409        };
410        let packets: Vec<Box<dyn Packet>> = vec![Box::new(rr), Box::new(pli)];
411
412        let raw1 = marshal(&packets)?;
413        let out = unmarshal(&mut raw1.clone().freeze())?;
414        assert_eq!(out.len(), 2, "expected two sub-packets");
415        let raw2 = marshal(&out)?;
416        assert_eq!(raw1, raw2, "compound marshal/unmarshal round-trip mismatch");
417
418        Ok(())
419    }
420}