Skip to main content

rtci_rtcp/
header.rs

1//! The RTCP header.
2//!
3//! Four bytes on every packet: version and padding flags, a 5-bit count whose meaning depends on
4//! the packet type, the [`PacketType`](crate::header::PacketType) itself, and a length in 32-bit words. The `*_SHIFT` and
5//! `*_MASK` constants describe how the flags pack into the first octet.
6//!
7//! The length field is why RTCP is compound: several packets can be concatenated in one
8//! datagram and walked by stepping over each header's length.
9use shared::{
10    error::{Error, Result},
11    marshal::{Marshal, MarshalSize, Unmarshal},
12};
13
14use bytes::{Buf, BufMut, Bytes};
15
16/// PacketType specifies the type of an RTCP packet
17/// RTCP packet types registered with IANA. See: <https://www.iana.org/assignments/rtp-parameters/rtp-parameters.xhtml#rtp-parameters-4>
18///
19/// The enum converts to and from the type octet with `u8::from` / `PacketType::from`; a value
20/// this crate does not model is kept in [`PacketType::Other`], so a packet of an unknown type
21/// is written back with the type it arrived with.
22#[derive(Default, Debug, Copy, Clone, PartialEq, Eq)]
23#[non_exhaustive]
24pub enum PacketType {
25    #[default]
26    /// No packet type: the type octet 0, and the value of a default header.
27    Unsupported,
28    /// Sender Report ([RFC 3550] §6.4.1): a sender's timing and packet counts.
29    SenderReport, // 200, RFC 3550, 6.4.1
30    /// Receiver Report ([RFC 3550] §6.4.2): reception quality from a receiver.
31    ReceiverReport, // 201, RFC 3550, 6.4.2
32    /// Source Description ([RFC 3550] §6.5): CNAME and other source metadata.
33    SourceDescription, // 202, RFC 3550, 6.5
34    /// BYE ([RFC 3550] §6.6): the source is leaving the session.
35    Goodbye, // 203, RFC 3550, 6.6
36    /// APP ([RFC 3550] §6.7): application-defined data.
37    ApplicationDefined, // 204, RFC 3550, 6.7
38    /// Transport-layer feedback ([RFC 4585]): NACK, TMMBR, TMMBN, transport-wide CC, CCFB.
39    TransportSpecificFeedback, // 205, RFC 4585, 6.2
40    /// Payload-specific feedback ([RFC 4585] §6.3): PLI, SLI, RPSI, FIR, TSTR, TSTN, VBCM, LRR,
41    /// application-layer feedback (REMB).
42    PayloadSpecificFeedback, // 206, RFC 4585, 6.3
43    /// Extended Report ([RFC 3611]).
44    ExtendedReport, // 207, RFC 3611
45    /// A packet type this crate does not model, with its type octet.
46    Other(u8),
47}
48
49// Transport and payload specific feedback messages overload the count field to act as a
50// message type (FMT). Those are listed here.
51
52/// FMT of the Slice Loss Indication (PSFB, RFC 4585 §6.3.2).
53pub const FORMAT_SLI: u8 = 2;
54/// FMT of the Picture Loss Indication (PSFB, RFC 4585 §6.3.1).
55pub const FORMAT_PLI: u8 = 1;
56/// FMT of the Reference Picture Selection Indication (PSFB, RFC 4585 §6.3.3).
57pub const FORMAT_RPSI: u8 = 3;
58/// FMT of the Full Intra Request (PSFB, RFC 5104 §4.3.1).
59pub const FORMAT_FIR: u8 = 4;
60/// FMT of the Temporal-Spatial Trade-off Request (PSFB, RFC 5104 §4.3.2).
61pub const FORMAT_TSTR: u8 = 5;
62/// FMT of the Temporal-Spatial Trade-off Notification (PSFB, RFC 5104 §4.3.3).
63pub const FORMAT_TSTN: u8 = 6;
64/// FMT of the Video Back Channel Message (PSFB, RFC 5104 §4.3.4).
65pub const FORMAT_VBCM: u8 = 7;
66/// FMT of the Layer Refresh Request (PSFB, RFC 9627 §3).
67pub const FORMAT_LRR: u8 = 10;
68/// FMT of application-layer feedback (PSFB, RFC 4585 §6.4), which REMB is one kind of.
69pub const FORMAT_AFB: u8 = 15;
70/// FMT of the generic NACK (RTPFB, RFC 4585 §6.2.1).
71pub const FORMAT_TLN: u8 = 1;
72/// FMT of the Temporary Maximum Media Stream Bit Rate Request (RTPFB, RFC 5104 §4.2.1).
73pub const FORMAT_TMMBR: u8 = 3;
74/// FMT of the Temporary Maximum Media Stream Bit Rate Notification (RTPFB, RFC 5104 §4.2.2).
75pub const FORMAT_TMMBN: u8 = 4;
76/// FMT of the Rapid Resynchronisation Request (RTPFB, RFC 6051 §3.2).
77pub const FORMAT_RRR: u8 = 5;
78/// FMT of REMB: application-layer feedback whose payload starts with `REMB`.
79pub const FORMAT_REMB: u8 = 15;
80/// FMT of transport-wide congestion control feedback (RTPFB).
81/// <https://tools.ietf.org/html/draft-holmer-rmcat-transport-wide-cc-extensions-01#page-5>
82pub const FORMAT_TCC: u8 = 15;
83/// FMT value for CCFB (Congestion Control Feedback) per RFC 8888
84pub const FORMAT_CCFB: u8 = 11;
85/// FMT value for the RTCP ECN Feedback packet (RFC 6679 section 5.1)
86pub const FORMAT_ECN: u8 = 8;
87/// FMT of the PAUSE-RESUME message (RTPFB, RFC 7728 section 7).
88pub const FORMAT_PAUSE_RESUME: u8 = 9;
89
90impl std::fmt::Display for PacketType {
91    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
92        let s = match self {
93            PacketType::Unsupported => "Unsupported",
94            PacketType::Other(pt) => return write!(f, "PT{pt}"),
95            PacketType::SenderReport => "SR",
96            PacketType::ReceiverReport => "RR",
97            PacketType::SourceDescription => "SDES",
98            PacketType::Goodbye => "BYE",
99            PacketType::ApplicationDefined => "APP",
100            PacketType::TransportSpecificFeedback => "TSFB",
101            PacketType::PayloadSpecificFeedback => "PSFB",
102            PacketType::ExtendedReport => "XR",
103        };
104        write!(f, "{s}")
105    }
106}
107
108impl From<u8> for PacketType {
109    fn from(b: u8) -> Self {
110        match b {
111            0 => PacketType::Unsupported,
112            200 => PacketType::SenderReport,       // RFC 3550, 6.4.1
113            201 => PacketType::ReceiverReport,     // RFC 3550, 6.4.2
114            202 => PacketType::SourceDescription,  // RFC 3550, 6.5
115            203 => PacketType::Goodbye,            // RFC 3550, 6.6
116            204 => PacketType::ApplicationDefined, // RFC 3550, 6.7
117            205 => PacketType::TransportSpecificFeedback, // RFC 4585, 6.2
118            206 => PacketType::PayloadSpecificFeedback, // RFC 4585, 6.3
119            207 => PacketType::ExtendedReport,     // RFC 3611
120            other => PacketType::Other(other),
121        }
122    }
123}
124
125impl From<PacketType> for u8 {
126    fn from(t: PacketType) -> Self {
127        match t {
128            PacketType::Unsupported => 0,
129            PacketType::SenderReport => 200,
130            PacketType::ReceiverReport => 201,
131            PacketType::SourceDescription => 202,
132            PacketType::Goodbye => 203,
133            PacketType::ApplicationDefined => 204,
134            PacketType::TransportSpecificFeedback => 205,
135            PacketType::PayloadSpecificFeedback => 206,
136            PacketType::ExtendedReport => 207,
137            PacketType::Other(other) => other,
138        }
139    }
140}
141
142/// The RTP/RTCP version this crate speaks.
143pub const RTP_VERSION: u8 = 2;
144/// Bit offset of the version field in the first header octet.
145pub const VERSION_SHIFT: u8 = 6;
146/// Bit mask of the version field once shifted.
147pub const VERSION_MASK: u8 = 0x3;
148/// Bit offset of the padding flag.
149pub const PADDING_SHIFT: u8 = 5;
150/// Bit mask of the padding flag once shifted.
151pub const PADDING_MASK: u8 = 0x1;
152/// Bit offset of the report/source count field.
153pub const COUNT_SHIFT: u8 = 0;
154/// Bit mask of the report/source count field.
155pub const COUNT_MASK: u8 = 0x1f;
156
157/// Length of the RTCP header in bytes.
158pub const HEADER_LENGTH: usize = 4;
159/// The largest report count the 5-bit field can hold.
160pub const COUNT_MAX: usize = (1 << 5) - 1;
161/// Length of an SSRC in bytes.
162pub const SSRC_LENGTH: usize = 4;
163/// The longest SDES item value, bounded by its one-byte length field.
164pub const SDES_MAX_OCTET_COUNT: usize = (1 << 8) - 1;
165
166// https://datatracker.ietf.org/doc/html/rfc5104#section-4.3.1
167//
168// The FCI field MUST contain one or more FIR entries.
169//
170// https://datatracker.ietf.org/doc/html/rfc5104#section-4.3.1.1
171//
172// The length of the FIR feedback message MUST be set to
173//    2+2*N, where N is the number of FCI entries.
174/// The smallest valid FIR packet, in bytes.
175pub const FIR_MIN_OCTET_COUNT: usize = 20;
176
177/// A Header is the common header shared by all RTCP packets
178#[derive(Debug, PartialEq, Eq, Default, Clone)]
179pub struct Header {
180    /// If the padding bit is set, this individual RTCP packet contains
181    /// some additional padding octets at the end which are not part of
182    /// the control information but are included in the length field.
183    pub padding: bool,
184    /// The number of reception reports, sources contained or FMT in this packet (depending on the Type)
185    pub count: u8,
186    /// The RTCP packet type for this packet
187    pub packet_type: PacketType,
188    /// The length of this RTCP packet in 32-bit words minus one,
189    /// including the header and any padding.
190    pub length: u16,
191}
192
193/// Marshal encodes the Header in binary
194impl MarshalSize for Header {
195    fn marshal_size(&self) -> usize {
196        HEADER_LENGTH
197    }
198}
199
200impl Marshal for Header {
201    fn marshal_to(&self, mut buf: &mut [u8]) -> Result<usize> {
202        if self.count > 31 {
203            return Err(Error::InvalidHeader);
204        }
205        if buf.remaining_mut() < HEADER_LENGTH {
206            return Err(Error::BufferTooShort);
207        }
208
209        /*
210         *  0                   1                   2                   3
211         *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
212         * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
213         * |V=2|P|    RC   |   PT=SR=200   |             length            |
214         * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
215         */
216        let b0 = (RTP_VERSION << VERSION_SHIFT)
217            | ((self.padding as u8) << PADDING_SHIFT)
218            | (self.count << COUNT_SHIFT);
219
220        buf.put_u8(b0);
221        buf.put_u8(self.packet_type.into());
222        buf.put_u16(self.length);
223
224        Ok(HEADER_LENGTH)
225    }
226}
227
228impl Unmarshal for Header {
229    /// Unmarshal decodes the Header from binary
230    fn unmarshal<B>(raw_packet: &mut B) -> Result<Self>
231    where
232        Self: Sized,
233        B: Buf,
234    {
235        if raw_packet.remaining() < HEADER_LENGTH {
236            return Err(Error::PacketTooShort);
237        }
238
239        /*
240         *  0                   1                   2                   3
241         *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
242         * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
243         * |V=2|P|    RC   |      PT       |             length            |
244         * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
245         */
246        let b0 = raw_packet.get_u8();
247        let version = (b0 >> VERSION_SHIFT) & VERSION_MASK;
248        if version != RTP_VERSION {
249            return Err(Error::BadVersion);
250        }
251
252        let padding = ((b0 >> PADDING_SHIFT) & PADDING_MASK) > 0;
253        let count = (b0 >> COUNT_SHIFT) & COUNT_MASK;
254        let packet_type = PacketType::from(raw_packet.get_u8());
255        let length = raw_packet.get_u16();
256
257        Ok(Header {
258            padding,
259            count,
260            packet_type,
261            length,
262        })
263    }
264}
265
266/// Length of the part every feedback packet starts with after the header: the SSRC of the
267/// packet sender and the SSRC of the media source (RFC 4585 §6.1).
268pub(crate) const FEEDBACK_SSRCS_LENGTH: usize = 2 * SSRC_LENGTH;
269
270/// Reads one RTCP packet off `raw`: its header, and its body without the padding the P bit
271/// announces.
272///
273/// The body is exactly the `length` words the header declares; what follows them in `raw` is
274/// the next packet of the datagram and is left there. RFC 3550 §6.4.1: with the P bit set the
275/// last octet of the packet counts the padding octets, itself included, and those octets are
276/// not control information.
277pub(crate) fn read_packet<B>(raw: &mut B) -> Result<(Header, Bytes)>
278where
279    B: Buf,
280{
281    let header = Header::unmarshal(raw)?;
282    let length = header.length as usize * 4;
283    if raw.remaining() < length {
284        return Err(Error::PacketTooShort);
285    }
286    let mut body = raw.copy_to_bytes(length);
287    if header.padding {
288        let padding = body.last().copied().unwrap_or(0) as usize;
289        if padding == 0 || padding > body.len() {
290            return Err(Error::WrongPadding);
291        }
292        body.truncate(body.len() - padding);
293    }
294    Ok((header, body))
295}
296
297/// Reads one feedback packet (RFC 4585 §6.1) of the given type and FMT off `raw` and returns
298/// the SSRC of the packet sender, the SSRC of the media source and the FCI.
299pub(crate) fn read_feedback<B>(
300    raw: &mut B,
301    packet_type: PacketType,
302    format: u8,
303) -> Result<(u32, u32, Bytes)>
304where
305    B: Buf,
306{
307    let (header, mut body) = read_packet(raw)?;
308    if header.packet_type != packet_type || header.count != format {
309        return Err(Error::WrongType);
310    }
311    if body.len() < FEEDBACK_SSRCS_LENGTH {
312        return Err(Error::PacketTooShort);
313    }
314    let sender_ssrc = body.get_u32();
315    let media_ssrc = body.get_u32();
316    Ok((sender_ssrc, media_ssrc, body))
317}
318
319/// The header of a packet of `size` octets, `size` a multiple of four no larger than the 16-bit
320/// length field can describe.
321pub(crate) fn header_for(packet_type: PacketType, count: u8, size: usize) -> Result<Header> {
322    if !size.is_multiple_of(4) || size < HEADER_LENGTH {
323        return Err(Error::WrongMarshalSize);
324    }
325    let length = u16::try_from(size / 4 - 1).map_err(|_| Error::TooManyReports)?;
326    Ok(Header {
327        padding: false,
328        count,
329        packet_type,
330        length,
331    })
332}
333
334/// Writes the header and the two SSRCs of a feedback packet of `size` octets and returns the
335/// rest of `buf`, where the FCI goes.
336pub(crate) fn put_feedback_start(
337    buf: &mut [u8],
338    packet_type: PacketType,
339    format: u8,
340    size: usize,
341    sender_ssrc: u32,
342    media_ssrc: u32,
343) -> Result<&mut [u8]> {
344    if buf.len() < size {
345        return Err(Error::BufferTooShort);
346    }
347    let n = header_for(packet_type, format, size)?.marshal_to(buf)?;
348    let mut rest = &mut buf[n..];
349    rest.put_u32(sender_ssrc);
350    rest.put_u32(media_ssrc);
351    Ok(rest)
352}
353
354#[cfg(test)]
355mod test {
356    use super::*;
357    use bytes::Bytes;
358
359    #[test]
360    fn test_header_unmarshal() {
361        let tests = vec![
362            (
363                "valid",
364                Bytes::from_static(&[
365                    // v=2, p=0, count=1, RR, len=7
366                    0x81u8, 0xc9, 0x00, 0x07,
367                ]),
368                Header {
369                    padding: false,
370                    count: 1,
371                    packet_type: PacketType::ReceiverReport,
372                    length: 7,
373                },
374                None,
375            ),
376            (
377                "also valid",
378                Bytes::from_static(&[
379                    // v=2, p=1, count=1, BYE, len=7
380                    0xa1, 0xcc, 0x00, 0x07,
381                ]),
382                Header {
383                    padding: true,
384                    count: 1,
385                    packet_type: PacketType::ApplicationDefined,
386                    length: 7,
387                },
388                None,
389            ),
390            (
391                "bad version",
392                Bytes::from_static(&[
393                    // v=0, p=0, count=0, RR, len=4
394                    0x00, 0xc9, 0x00, 0x04,
395                ]),
396                Header {
397                    padding: false,
398                    count: 0,
399                    packet_type: PacketType::Unsupported,
400                    length: 0,
401                },
402                Some(Error::BadVersion),
403            ),
404        ];
405
406        for (name, data, want, want_error) in tests {
407            let buf = &mut data.clone();
408            let got = Header::unmarshal(buf);
409
410            assert_eq!(
411                got.is_err(),
412                want_error.is_some(),
413                "Unmarshal {name}: err = {got:?}, want {want_error:?}"
414            );
415
416            if let Some(want_error) = want_error {
417                let got_err = got.err().unwrap();
418                assert_eq!(
419                    want_error, got_err,
420                    "Unmarshal {name}: err = {got_err:?}, want {want_error:?}",
421                );
422            } else {
423                let actual = got.unwrap();
424                assert_eq!(
425                    actual, want,
426                    "Unmarshal {name}: got {actual:?}, want {want:?}"
427                );
428            }
429        }
430    }
431
432    #[test]
433    fn test_header_roundtrip() {
434        let tests = vec![
435            (
436                "valid",
437                Header {
438                    padding: true,
439                    count: 31,
440                    packet_type: PacketType::SenderReport,
441                    length: 4,
442                },
443                None,
444            ),
445            (
446                "also valid",
447                Header {
448                    padding: false,
449                    count: 28,
450                    packet_type: PacketType::ReceiverReport,
451                    length: 65535,
452                },
453                None,
454            ),
455            (
456                "invalid count",
457                Header {
458                    padding: false,
459                    count: 40,
460                    packet_type: PacketType::Unsupported,
461                    length: 0,
462                },
463                Some(Error::InvalidHeader),
464            ),
465        ];
466
467        for (name, want, want_error) in tests {
468            let got = want.marshal();
469
470            assert_eq!(
471                got.is_ok(),
472                want_error.is_none(),
473                "Marshal {name}: err = {got:?}, want {want_error:?}"
474            );
475
476            if let Some(err) = want_error {
477                let got_err = got.err().unwrap();
478                assert_eq!(
479                    err, got_err,
480                    "Unmarshal {name} rr: err = {got_err:?}, want {err:?}",
481                );
482            } else {
483                let data = got.ok().unwrap();
484                let buf = &mut data.clone();
485                let actual = Header::unmarshal(buf).unwrap_or_else(|_| panic!("Unmarshal {name}"));
486
487                assert_eq!(
488                    actual, want,
489                    "{name} round trip: got {actual:?}, want {want:?}"
490                )
491            }
492        }
493    }
494}