rtci-rtcp 0.4.1

RTCP packet parsing and serialization (RFC 3550, RFC 4585, RFC 5104, RFC 3611, RFC 8888) for WebRTC
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
use crate::{
    application_defined::*, goodbye::*, header::*,
    payload_feedbacks::application_layer_feedback::*, payload_feedbacks::full_intra_request::*,
    payload_feedbacks::layer_refresh_request::*, payload_feedbacks::picture_loss_indication::*,
    payload_feedbacks::receiver_estimated_maximum_bitrate::*,
    payload_feedbacks::reference_picture_selection_indication::*,
    payload_feedbacks::slice_loss_indication::*, payload_feedbacks::temporal_spatial_tradeoff::*,
    payload_feedbacks::video_back_channel_message::*, raw_packet::*, receiver_report::*,
    sender_report::*, source_description::*, transport_feedbacks::cc_feedback_report::*,
    transport_feedbacks::ecn_feedback::*, transport_feedbacks::pause_resume::*,
    transport_feedbacks::rapid_resynchronization_request::*, transport_feedbacks::tmmb::*,
    transport_feedbacks::transport_layer_cc::*, transport_feedbacks::transport_layer_nack::*,
};
use shared::{
    error::{Error, Result},
    marshal::{Marshal, Unmarshal},
};

use crate::extended_report::ExtendedReport;
use bytes::{Buf, BufMut, Bytes, BytesMut};
use std::any::Any;
use std::fmt;

/// Packet represents an RTCP packet, a protocol used for out-of-band statistics and
/// control information for an RTP session
pub trait Packet: Send + Sync + Marshal + Unmarshal + fmt::Display + fmt::Debug {
    /// This packet's RTCP header.
    fn header(&self) -> Header;
    /// The SSRCs this packet is about.
    ///
    /// Used to route feedback: a report's destination SSRCs identify the streams it concerns,
    /// which is how an SFU decides where to forward it.
    fn destination_ssrc(&self) -> Vec<u32>;
    /// The encoded size in bytes, header and padding included.
    fn raw_size(&self) -> usize;
    /// Downcasting hook, so a caller holding `Box<dyn Packet>` can recover the concrete type.
    fn as_any(&self) -> &dyn Any;
    /// Compares against another packet, since `PartialEq` is not object safe.
    fn equal(&self, other: &dyn Packet) -> bool;
    /// Clones this packet behind a trait object, since `Clone` is not object safe.
    fn cloned(&self) -> Box<dyn Packet>;
}

impl PartialEq for dyn Packet {
    fn eq(&self, other: &Self) -> bool {
        self.equal(other)
    }
}

impl Clone for Box<dyn Packet> {
    fn clone(&self) -> Box<dyn Packet> {
        self.cloned()
    }
}

/// marshal takes an array of Packets and serializes them to a single buffer
pub fn marshal(packets: &[Box<dyn Packet>]) -> Result<BytesMut> {
    // Size the compound packet up front and marshal each sub-packet straight
    // into it, instead of allocating a fresh BytesMut per sub-packet
    // (p.marshal()) and copying it in.
    let total: usize = packets.iter().map(|p| p.marshal_size()).sum();
    let mut out = BytesMut::new();
    out.resize(total, 0);
    let mut offset = 0;
    for p in packets {
        offset += p.marshal_to(&mut out[offset..])?;
    }
    Ok(out)
}

/// Unmarshal takes an entire udp datagram (which may consist of multiple RTCP packets) and
/// returns the unmarshaled packets it contains.
///
/// The datagram may be a compound packet (RFC 3550 §6.1) or a reduced-size one (RFC 5506): no
/// leading SR or RR is required. Use [`crate::compound_packet::validate_compound`] for the
/// header checks of RFC 3550 Appendix A.2.
///
/// A packet of a type or feedback format this crate does not model comes back as a
/// [`RawPacket`] holding its bytes. A packet of a known type that is malformed fails the whole
/// datagram; [`unmarshal_lenient`] keeps the others.
pub fn unmarshal<B>(raw_data: &mut B) -> Result<Vec<Box<dyn Packet>>>
where
    B: Buf,
{
    let mut packets = vec![];

    while raw_data.has_remaining() {
        let p = unmarshaller(raw_data)?;
        packets.push(p);
    }

    match packets.len() {
        // Empty Packet
        0 => Err(Error::InvalidHeader),

        // Multiple Packet
        _ => Ok(packets),
    }
}

/// Like [`unmarshal`], but a packet of a known type that fails its own parse does not cost the
/// datagram: it comes back as a [`RawPacket`] with its bytes, and the packets around it are
/// parsed as usual.
///
/// The framing is not negotiable: a bad version, or a length that runs past the datagram,
/// leaves no way to find the next packet and fails the datagram here too.
pub fn unmarshal_lenient<B>(raw_data: &mut B) -> Result<Vec<Box<dyn Packet>>>
where
    B: Buf,
{
    let mut packets: Vec<Box<dyn Packet>> = vec![];

    while raw_data.has_remaining() {
        let framed = next_packet(raw_data)?;
        match parse_packet(&framed) {
            Ok(p) => packets.push(p),
            Err(_) => packets.push(Box::new(RawPacket(framed.whole()))),
        }
    }

    if packets.is_empty() {
        return Err(Error::InvalidHeader);
    }
    Ok(packets)
}

/// One RTCP packet cut off a datagram: its four header octets and the `length` words after
/// them.
///
/// The two are kept apart so that the body of a packet read from a `Bytes` stays a view of
/// the datagram: nothing is copied or allocated to frame a packet of a type this crate parses.
pub(crate) struct FramedPacket {
    header: [u8; HEADER_LENGTH],
    body: Bytes,
}

impl FramedPacket {
    /// The packet as it arrived, in one buffer: what an unparsed packet keeps.
    fn whole(&self) -> Bytes {
        let mut packet = BytesMut::with_capacity(HEADER_LENGTH + self.body.len());
        packet.put_slice(&self.header);
        packet.put_slice(&self.body);
        packet.freeze()
    }

    /// The packet as a reader for the type-specific parser, which reads the header again.
    fn reader(&self) -> impl Buf + '_ {
        self.header.as_slice().chain(self.body.clone())
    }
}

/// Cuts the first RTCP packet off a datagram by the header's length field.
pub(crate) fn next_packet<B>(raw_data: &mut B) -> Result<FramedPacket>
where
    B: Buf,
{
    if raw_data.remaining() < HEADER_LENGTH {
        return Err(Error::PacketTooShort);
    }
    let mut header = [0u8; HEADER_LENGTH];
    raw_data.copy_to_slice(&mut header);
    if (header[0] >> VERSION_SHIFT) & VERSION_MASK != RTP_VERSION {
        return Err(Error::BadVersion);
    }

    let length = u16::from_be_bytes([header[2], header[3]]) as usize * 4;
    if length > raw_data.remaining() {
        return Err(Error::PacketTooShort);
    }

    Ok(FramedPacket {
        header,
        body: raw_data.copy_to_bytes(length),
    })
}

/// Parses one RTCP packet.
fn parse_packet(framed: &FramedPacket) -> Result<Box<dyn Packet>> {
    let format = (framed.header[0] >> COUNT_SHIFT) & COUNT_MASK;
    let in_packet = &mut framed.reader();

    let p: Box<dyn Packet> = match PacketType::from(framed.header[1]) {
        PacketType::SenderReport => Box::new(SenderReport::unmarshal(in_packet)?),
        PacketType::ReceiverReport => Box::new(ReceiverReport::unmarshal(in_packet)?),
        PacketType::SourceDescription => Box::new(SourceDescription::unmarshal(in_packet)?),
        PacketType::Goodbye => Box::new(Goodbye::unmarshal(in_packet)?),
        PacketType::ApplicationDefined => Box::new(ApplicationDefined::unmarshal(in_packet)?),

        PacketType::TransportSpecificFeedback => match format {
            FORMAT_TLN => Box::new(TransportLayerNack::unmarshal(in_packet)?),
            FORMAT_TMMBR => Box::new(TemporaryMaximumBitrateRequest::unmarshal(in_packet)?),
            FORMAT_TMMBN => Box::new(TemporaryMaximumBitrateNotification::unmarshal(in_packet)?),
            FORMAT_RRR => Box::new(RapidResynchronizationRequest::unmarshal(in_packet)?),
            FORMAT_TCC => Box::new(TransportLayerCc::unmarshal(in_packet)?),
            FORMAT_CCFB => Box::new(CcFeedbackReport::unmarshal(in_packet)?),
            FORMAT_ECN => Box::new(EcnFeedback::unmarshal(in_packet)?),
            FORMAT_PAUSE_RESUME => Box::new(PauseResume::unmarshal(in_packet)?),
            _ => Box::new(RawPacket(framed.whole())),
        },
        PacketType::PayloadSpecificFeedback => match format {
            FORMAT_PLI => Box::new(PictureLossIndication::unmarshal(in_packet)?),
            FORMAT_SLI => Box::new(SliceLossIndication::unmarshal(in_packet)?),
            FORMAT_RPSI => Box::new(ReferencePictureSelectionIndication::unmarshal(in_packet)?),
            FORMAT_FIR => Box::new(FullIntraRequest::unmarshal(in_packet)?),
            FORMAT_TSTR => Box::new(TemporalSpatialTradeoffRequest::unmarshal(in_packet)?),
            FORMAT_TSTN => Box::new(TemporalSpatialTradeoffNotification::unmarshal(in_packet)?),
            FORMAT_VBCM => Box::new(VideoBackChannelMessage::unmarshal(in_packet)?),
            FORMAT_LRR => Box::new(LayerRefreshRequest::unmarshal(in_packet)?),
            // RFC 4585 6.4: the application identifies its own messages. REMB does so by the
            // four octets that open its FCI; anything else is some other application's.
            FORMAT_AFB if is_remb(&framed.body) => {
                Box::new(ReceiverEstimatedMaximumBitrate::unmarshal(in_packet)?)
            }
            FORMAT_AFB => Box::new(ApplicationLayerFeedback::unmarshal(in_packet)?),
            _ => Box::new(RawPacket(framed.whole())),
        },
        PacketType::ExtendedReport => Box::new(ExtendedReport::unmarshal(in_packet)?),
        _ => Box::new(RawPacket(framed.whole())),
    };

    Ok(p)
}

/// unmarshaller is a factory which pulls the first RTCP packet from a bytestream,
/// and returns it's parsed representation, and the amount of data that was processed.
pub(crate) fn unmarshaller<B>(raw_data: &mut B) -> Result<Box<dyn Packet>>
where
    B: Buf,
{
    parse_packet(&next_packet(raw_data)?)
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::reception_report::*;
    use bytes::Bytes;

    #[test]
    fn test_packet_unmarshal() {
        let mut data = Bytes::from_static(&[
            // Receiver Report (offset=0)
            0x81, 0xc9, 0x0, 0x7, // v=2, p=0, count=1, RR, len=7
            0x90, 0x2f, 0x9e, 0x2e, // ssrc=0x902f9e2e
            0xbc, 0x5e, 0x9a, 0x40, // ssrc=0xbc5e9a40
            0x0, 0x0, 0x0, 0x0, // fracLost=0, totalLost=0
            0x0, 0x0, 0x46, 0xe1, // lastSeq=0x46e1
            0x0, 0x0, 0x1, 0x11, // jitter=273
            0x9, 0xf3, 0x64, 0x32, // lsr=0x9f36432
            0x0, 0x2, 0x4a, 0x79, // delay=150137
            // Source Description (offset=32)
            0x81, 0xca, 0x0, 0xc, // v=2, p=0, count=1, SDES, len=12
            0x90, 0x2f, 0x9e, 0x2e, // ssrc=0x902f9e2e
            0x1, 0x26, // CNAME, len=38
            0x7b, 0x39, 0x63, 0x30, 0x30, 0x65, 0x62, 0x39, 0x32, 0x2d, 0x31, 0x61, 0x66, 0x62,
            0x2d, 0x39, 0x64, 0x34, 0x39, 0x2d, 0x61, 0x34, 0x37, 0x64, 0x2d, 0x39, 0x31, 0x66,
            0x36, 0x34, 0x65, 0x65, 0x65, 0x36, 0x39, 0x66, 0x35,
            0x7d, // text="{9c00eb92-1afb-9d49-a47d-91f64eee69f5}"
            0x0, 0x0, 0x0, 0x0, // END + padding
            // Goodbye (offset=84)
            0x81, 0xcb, 0x0, 0x1, // v=2, p=0, count=1, BYE, len=1
            0x90, 0x2f, 0x9e, 0x2e, // source=0x902f9e2e
            0x81, 0xce, 0x0, 0x2, // Picture Loss Indication (offset=92)
            0x90, 0x2f, 0x9e, 0x2e, // sender=0x902f9e2e
            0x90, 0x2f, 0x9e, 0x2e, // media=0x902f9e2e
            0x85, 0xcd, 0x0, 0x2, // RapidResynchronizationRequest (offset=104)
            0x90, 0x2f, 0x9e, 0x2e, // sender=0x902f9e2e
            0x90, 0x2f, 0x9e, 0x2e, // media=0x902f9e2e
        ]);

        let packet = unmarshal(&mut data).expect("Error unmarshalling packets");

        let a = ReceiverReport {
            ssrc: 0x902f9e2e,
            reports: vec![ReceptionReport {
                ssrc: 0xbc5e9a40,
                fraction_lost: 0,
                total_lost: 0,
                last_sequence_number: 0x46e1,
                jitter: 273,
                last_sender_report: 0x9f36432,
                delay: 150137,
            }],
            ..Default::default()
        };

        let b = SourceDescription {
            chunks: vec![SourceDescriptionChunk {
                source: 0x902f9e2e,
                items: vec![SourceDescriptionItem {
                    sdes_type: SdesType::SdesCname,
                    text: Bytes::from_static(b"{9c00eb92-1afb-9d49-a47d-91f64eee69f5}"),
                }],
            }],
        };

        let c = Goodbye {
            sources: vec![0x902f9e2e],
            ..Default::default()
        };

        let d = PictureLossIndication {
            sender_ssrc: 0x902f9e2e,
            media_ssrc: 0x902f9e2e,
        };

        let e = RapidResynchronizationRequest {
            sender_ssrc: 0x902f9e2e,
            media_ssrc: 0x902f9e2e,
        };

        let expected: Vec<Box<dyn Packet>> = vec![
            Box::new(a),
            Box::new(b),
            Box::new(c),
            Box::new(d),
            Box::new(e),
        ];

        assert!(packet == expected, "Invalid packets");
    }

    #[test]
    fn test_packet_unmarshal_empty() -> Result<()> {
        let result = unmarshal(&mut Bytes::new());
        if let Err(got) = result {
            let want = Error::InvalidHeader;
            assert_eq!(got, want, "Unmarshal(nil) err = {got}, want {want}");
        } else {
            panic!("want error");
        }

        Ok(())
    }

    #[test]
    fn test_packet_invalid_header_length() -> Result<()> {
        let mut data = Bytes::from_static(&[
            // Goodbye (offset=84)
            // v=2, p=0, count=1, BYE, len=100
            0x81, 0xcb, 0x0, 0x64,
        ]);

        let result = unmarshal(&mut data);
        if let Err(got) = result {
            let want = Error::PacketTooShort;
            assert_eq!(
                got, want,
                "Unmarshal(invalid_header_length) err = {got}, want {want}"
            );
        } else {
            panic!("want error");
        }

        Ok(())
    }
    #[test]
    fn test_packet_unmarshal_firefox() -> Result<()> {
        // issue report from https://github.com/webrtc-rs/srtp/issues/7
        let tests = vec![
            Bytes::from_static(&[
                143, 205, 0, 6, 65, 227, 184, 49, 118, 243, 78, 96, 42, 63, 0, 5, 12, 162, 166, 0,
                32, 5, 200, 4, 0, 4, 0, 0,
            ]),
            Bytes::from_static(&[
                143, 205, 0, 9, 65, 227, 184, 49, 118, 243, 78, 96, 42, 68, 0, 17, 12, 162, 167, 1,
                32, 17, 88, 0, 4, 0, 4, 8, 108, 0, 4, 0, 4, 12, 0, 4, 0, 4, 4, 0,
            ]),
            Bytes::from_static(&[
                143, 205, 0, 8, 65, 227, 184, 49, 118, 243, 78, 96, 42, 91, 0, 12, 12, 162, 168, 3,
                32, 12, 220, 4, 0, 4, 0, 8, 128, 4, 0, 4, 0, 8, 0, 0,
            ]),
            Bytes::from_static(&[
                143, 205, 0, 7, 65, 227, 184, 49, 118, 243, 78, 96, 42, 103, 0, 8, 12, 162, 169, 4,
                32, 8, 232, 4, 0, 4, 0, 4, 4, 0, 0, 0,
            ]),
        ];

        for mut test in tests {
            unmarshal(&mut test)?;
        }

        Ok(())
    }

    // Round-trips a compound through packet::marshal -> packet::unmarshal ->
    // packet::marshal and asserts byte-stability, covering the in-place compound
    // marshal and the sub-packet unmarshaller.
    #[test]
    fn test_marshal_compound_roundtrip() -> Result<()> {
        use crate::reception_report::ReceptionReport;

        let rr = ReceiverReport {
            ssrc: 0x902f9e2e,
            reports: vec![ReceptionReport {
                ssrc: 0xbc5e9a40,
                fraction_lost: 0,
                total_lost: 0,
                last_sequence_number: 0x46e1,
                jitter: 273,
                last_sender_report: 0x9f36432,
                delay: 150137,
            }],
            ..Default::default()
        };
        let pli = PictureLossIndication {
            sender_ssrc: 0x902f9e2e,
            media_ssrc: 0x902f9e2e,
        };
        let packets: Vec<Box<dyn Packet>> = vec![Box::new(rr), Box::new(pli)];

        let raw1 = marshal(&packets)?;
        let out = unmarshal(&mut raw1.clone().freeze())?;
        assert_eq!(out.len(), 2, "expected two sub-packets");
        let raw2 = marshal(&out)?;
        assert_eq!(raw1, raw2, "compound marshal/unmarshal round-trip mismatch");

        Ok(())
    }
}