Skip to main content

rtci_rtp/header/
mod.rs

1//! The RTP header and its extensions.
2//!
3//! [`Header`] is the fixed 12-byte header plus the optional CSRC list and header-extension
4//! block. The `*_SHIFT`/`*_MASK` constants describe how the flag fields pack into the first two
5//! octets, and the `*_OFFSET`/`*_LENGTH` constants give the byte positions a caller can patch in
6//! place without re-encoding.
7//!
8//! Header extensions ([RFC 8285]) come in two forms, selected by
9//! [`Header::extension_profile`](crate::header::Header::extension_profile): one-byte ids ([`EXTENSION_PROFILE_ONE_BYTE`]) or two-byte ids
10//! ([`EXTENSION_PROFILE_TWO_BYTE`]) when an id above 14 is needed. Use
11//! [`Header::set_extension`](crate::header::Header::set_extension) and [`Header::get_extension`](crate::header::Header::get_extension) rather than touching
12//! [`Header::extensions`](crate::header::Header::extensions) directly — they keep [`Header::extensions_padding`](crate::header::Header::extensions_padding) and the extension
13//! flag consistent, which marshalling depends on.
14//!
15//! [RFC 8285]: https://datatracker.ietf.org/doc/html/rfc8285
16
17use shared::{
18    error::{Error, Result},
19    marshal::{Marshal, MarshalSize, Unmarshal},
20};
21
22use bytes::{Buf, BufMut, Bytes};
23
24/// The RTP header validity checks of RFC 3550 Appendix A.1, on raw bytes.
25pub mod validity;
26
27/// The length of the extension-profile and length fields that precede header extensions.
28pub const HEADER_LENGTH: usize = 4;
29/// Bit offset of the version field in the first header octet.
30pub const VERSION_SHIFT: u8 = 6;
31/// Bit mask of the version field once shifted.
32pub const VERSION_MASK: u8 = 0x3;
33/// Bit offset of the padding flag.
34pub const PADDING_SHIFT: u8 = 5;
35/// Bit mask of the padding flag once shifted.
36pub const PADDING_MASK: u8 = 0x1;
37/// Bit offset of the extension flag.
38pub const EXTENSION_SHIFT: u8 = 4;
39/// Bit mask of the extension flag once shifted.
40pub const EXTENSION_MASK: u8 = 0x1;
41/// Extension profile `0xBEDE`, which selects one-byte header extension ids ([RFC 8285]).
42pub const EXTENSION_PROFILE_ONE_BYTE: u16 = 0xBEDE;
43/// Extension profile `0x1000`, which selects two-byte header extension ids, allowing ids
44/// above 14.
45pub const EXTENSION_PROFILE_TWO_BYTE: u16 = 0x1000;
46/// The bits of "defined by profile" that select the two-byte form. The low four bits are
47/// `appbits`, which a receiver ignores ([RFC 8285] section 4.3).
48///
49/// [RFC 8285]: https://datatracker.ietf.org/doc/html/rfc8285
50pub const EXTENSION_PROFILE_TWO_BYTE_MASK: u16 = 0xFFF0;
51/// Extension id 15, reserved by the RFC and never assigned.
52pub const EXTENSION_ID_RESERVED: u8 = 0xF;
53/// The RTP version this crate reads and writes (RFC 3550 section 5.1).
54pub const RTP_VERSION: u8 = 2;
55/// The highest id the one-byte form can carry (RFC 8285 section 4.2).
56pub const ONE_BYTE_EXTENSION_MAX_ID: u8 = 14;
57/// The longest element the one-byte form can carry, in bytes.
58pub const ONE_BYTE_EXTENSION_MAX_LEN: usize = 16;
59/// The longest element the two-byte form can carry, in bytes.
60pub const TWO_BYTE_EXTENSION_MAX_LEN: usize = 255;
61
62/// The form of a header-extension block, as its "defined by profile" field selects it.
63#[derive(Debug, Copy, Clone, PartialEq, Eq)]
64pub enum ExtensionForm {
65    /// RFC 8285 one-byte form (`0xBEDE`): ids 1 to 14, 1 to 16 bytes each.
66    OneByte,
67    /// RFC 8285 two-byte form (`0x100` and four `appbits`): ids 1 to 255, 0 to 255 bytes each.
68    TwoByte,
69    /// Any other profile: one opaque RFC 3550 section 5.3.1 extension, kept under id 0.
70    Rfc3550,
71}
72
73impl ExtensionForm {
74    /// The form a "defined by profile" value selects. The two-byte form is recognised whatever
75    /// its `appbits` are (RFC 8285 section 4.3: the receiver ignores them).
76    pub fn of_profile(extension_profile: u16) -> Self {
77        if extension_profile == EXTENSION_PROFILE_ONE_BYTE {
78            ExtensionForm::OneByte
79        } else if extension_profile & EXTENSION_PROFILE_TWO_BYTE_MASK == EXTENSION_PROFILE_TWO_BYTE
80        {
81            ExtensionForm::TwoByte
82        } else {
83            ExtensionForm::Rfc3550
84        }
85    }
86
87    /// Bytes of element header in this form: the id / length byte or bytes.
88    fn element_header_len(self) -> usize {
89        match self {
90            ExtensionForm::OneByte => 1,
91            ExtensionForm::TwoByte => 2,
92            ExtensionForm::Rfc3550 => 0,
93        }
94    }
95
96    /// Whether an element with this id and length can be written in the one-byte form.
97    fn one_byte_fits(id: u8, payload_len: usize) -> bool {
98        (1..=ONE_BYTE_EXTENSION_MAX_ID).contains(&id)
99            && (1..=ONE_BYTE_EXTENSION_MAX_LEN).contains(&payload_len)
100    }
101}
102/// Bit mask of the CSRC count field.
103pub const CC_MASK: u8 = 0xF;
104/// Bit offset of the marker bit.
105pub const MARKER_SHIFT: u8 = 7;
106/// Bit mask of the marker bit once shifted.
107pub const MARKER_MASK: u8 = 0x1;
108/// Bit mask of the payload-type field.
109pub const PT_MASK: u8 = 0x7F;
110/// Byte offset of the sequence number within the header.
111pub const SEQ_NUM_OFFSET: usize = 2;
112/// Length of the sequence number in bytes.
113pub const SEQ_NUM_LENGTH: usize = 2;
114/// Byte offset of the timestamp within the header.
115pub const TIMESTAMP_OFFSET: usize = 4;
116/// Length of the timestamp in bytes.
117pub const TIMESTAMP_LENGTH: usize = 4;
118/// Byte offset of the SSRC within the header.
119pub const SSRC_OFFSET: usize = 8;
120/// Length of the SSRC in bytes.
121pub const SSRC_LENGTH: usize = 4;
122/// Byte offset of the first CSRC within the header.
123pub const CSRC_OFFSET: usize = 12;
124/// Length of each CSRC in bytes.
125pub const CSRC_LENGTH: usize = 4;
126
127#[derive(Debug, Eq, PartialEq, Default, Clone)]
128/// One RTP header extension: an id and its payload bytes.
129pub struct Extension {
130    /// The extension id, as negotiated by `a=extmap`.
131    pub id: u8,
132    /// The extension's value.
133    pub payload: Bytes,
134}
135
136/// Header represents an RTP packet header
137/// NOTE: PayloadOffset is populated by Marshal/Unmarshal and should not be modified
138#[derive(Debug, Eq, PartialEq, Clone)]
139pub struct Header {
140    /// The RTP version, always 2. [`Header::default`] sets it; marshal and unmarshal refuse any
141    /// other value (RFC 3550 section 5.1).
142    pub version: u8,
143    /// Whether the payload is followed by padding octets, the last giving the padding length.
144    pub padding: bool,
145    /// Whether a header-extension block follows the fixed header.
146    pub extension: bool,
147    /// The marker bit: the last packet of a video frame, or the start of a talk spurt for audio.
148    pub marker: bool,
149    /// The payload type, which identifies the codec as negotiated in SDP.
150    pub payload_type: u8,
151    /// Increments by one per packet sent; used to detect loss and restore order.
152    pub sequence_number: u16,
153    /// The sampling instant of the first octet, in the codec's clock rate.
154    pub timestamp: u32,
155    /// The synchronization source — the identifier of the stream this packet belongs to.
156    pub ssrc: u32,
157    /// The contributing sources, listed when a mixer combined several streams.
158    pub csrc: Vec<u32>,
159    /// Which header-extension form is in use: [`EXTENSION_PROFILE_ONE_BYTE`] or
160    /// [`EXTENSION_PROFILE_TWO_BYTE`].
161    pub extension_profile: u16,
162    /// The header extensions present on this packet.
163    pub extensions: Vec<Extension>,
164    /// Padding bytes appended to the extension block so it ends on a 32-bit boundary.
165    pub extensions_padding: usize,
166    /// How many padding octets follow the payload when `padding` is set, the count octet
167    /// included (RFC 3550 5.1). Filled in by [`Packet`](crate::packet::Packet) unmarshal so a
168    /// packet re-marshals with the padding it arrived with; 0 lets marshal pad to the next
169    /// 32-bit boundary, as it always did.
170    pub padding_size: u8,
171}
172
173impl Default for Header {
174    /// A header of version 2 with every other field zero or empty.
175    fn default() -> Self {
176        Header {
177            version: RTP_VERSION,
178            padding: false,
179            extension: false,
180            marker: false,
181            payload_type: 0,
182            sequence_number: 0,
183            timestamp: 0,
184            ssrc: 0,
185            csrc: Vec::new(),
186            extension_profile: 0,
187            extensions: Vec::new(),
188            extensions_padding: 0,
189            padding_size: 0,
190        }
191    }
192}
193
194impl Unmarshal for Header {
195    /// Unmarshal parses the passed byte slice and stores the result in the Header this method is called upon
196    fn unmarshal<B>(raw_packet: &mut B) -> Result<Self>
197    where
198        Self: Sized,
199        B: Buf,
200    {
201        let raw_packet_len = raw_packet.remaining();
202        if raw_packet_len < HEADER_LENGTH {
203            return Err(Error::ErrHeaderSizeInsufficient);
204        }
205        /*
206         *  0                   1                   2                   3
207         *  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
208         * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
209         * |V=2|P|X|  CC   |M|     PT      |       sequence number         |
210         * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
211         * |                           timestamp                           |
212         * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
213         * |           synchronization source (SSRC) identifier            |
214         * +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
215         * |            contributing source (CSRC) identifiers             |
216         * |                             ....                              |
217         * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
218         */
219        let b0 = raw_packet.get_u8();
220        let version = b0 >> VERSION_SHIFT & VERSION_MASK;
221        if version != RTP_VERSION {
222            // RFC 3550 section 5.1 and Appendix A.1: anything else is not an RTP packet.
223            return Err(Error::BadVersion);
224        }
225        let padding = (b0 >> PADDING_SHIFT & PADDING_MASK) > 0;
226        let extension = (b0 >> EXTENSION_SHIFT & EXTENSION_MASK) > 0;
227        let cc = (b0 & CC_MASK) as usize;
228
229        let mut curr_offset = CSRC_OFFSET + (cc * CSRC_LENGTH);
230        if raw_packet_len < curr_offset {
231            return Err(Error::ErrHeaderSizeInsufficient);
232        }
233
234        let b1 = raw_packet.get_u8();
235        let marker = (b1 >> MARKER_SHIFT & MARKER_MASK) > 0;
236        let payload_type = b1 & PT_MASK;
237
238        let sequence_number = raw_packet.get_u16();
239        let timestamp = raw_packet.get_u32();
240        let ssrc = raw_packet.get_u32();
241
242        let mut csrc = Vec::with_capacity(cc);
243        for _ in 0..cc {
244            csrc.push(raw_packet.get_u32());
245        }
246        let mut extensions_padding: usize = 0;
247        let (extension_profile, extensions) = if extension {
248            let expected = curr_offset + 4;
249            if raw_packet_len < expected {
250                return Err(Error::ErrHeaderSizeInsufficientForExtension);
251            }
252            let extension_profile = raw_packet.get_u16();
253            curr_offset += 2;
254            let extension_length = raw_packet.get_u16() as usize * 4;
255            curr_offset += 2;
256
257            let expected = curr_offset + extension_length;
258            if raw_packet_len < expected {
259                return Err(Error::ErrHeaderSizeInsufficientForExtension);
260            }
261
262            // The whole extension block is consumed here, whatever its items say, so the
263            // payload starts where the header says it does and `marshal_size()` matches the
264            // wire: each item is bounded by the block, not by the rest of the packet.
265            let mut block = raw_packet.copy_to_bytes(extension_length);
266            let mut extensions = vec![];
267            match ExtensionForm::of_profile(extension_profile) {
268                // RFC 8285 RTP One Byte Header Extension
269                ExtensionForm::OneByte => {
270                    while block.has_remaining() {
271                        let b = block.get_u8();
272                        if b == 0x00 {
273                            // padding
274                            extensions_padding += 1;
275                            continue;
276                        }
277
278                        let extid = b >> 4;
279                        let len = ((b & (0xFF ^ 0xF0)) + 1) as usize;
280
281                        if extid == EXTENSION_ID_RESERVED || extid == 0 {
282                            // RFC 8285 section 4.2: processing stops at ID 15 and the rest of
283                            // the block is ignored. Section 4.1.2: the same for ID 0 with a
284                            // non-zero length, whose length is ignored. The elements before it
285                            // are kept, and the rest is still part of the header.
286                            extensions_padding += 1 + block.remaining();
287                            break;
288                        }
289
290                        if len > block.remaining() {
291                            return Err(Error::ErrHeaderSizeInsufficientForExtension);
292                        }
293
294                        extensions.push(Extension {
295                            id: extid,
296                            payload: block.copy_to_bytes(len),
297                        });
298                    }
299                }
300                // RFC 8285 RTP Two Byte Header Extension, whatever its appbits (section 4.3)
301                ExtensionForm::TwoByte => {
302                    while block.has_remaining() {
303                        let b = block.get_u8();
304                        if b == 0x00 {
305                            // padding
306                            extensions_padding += 1;
307                            continue;
308                        }
309
310                        let extid = b;
311
312                        if !block.has_remaining() {
313                            return Err(Error::ErrHeaderSizeInsufficientForExtension);
314                        }
315
316                        let len = block.get_u8() as usize;
317
318                        if len > block.remaining() {
319                            return Err(Error::ErrHeaderSizeInsufficientForExtension);
320                        }
321
322                        extensions.push(Extension {
323                            id: extid,
324                            payload: block.copy_to_bytes(len),
325                        });
326                    }
327                }
328                // RFC3550 Extension
329                ExtensionForm::Rfc3550 => {
330                    extensions.push(Extension {
331                        id: 0,
332                        payload: block,
333                    });
334                }
335            };
336
337            (extension_profile, extensions)
338        } else {
339            (0, vec![])
340        };
341
342        Ok(Header {
343            version,
344            padding,
345            extension,
346            marker,
347            payload_type,
348            sequence_number,
349            timestamp,
350            ssrc,
351            csrc,
352            extension_profile,
353            extensions,
354            extensions_padding,
355            padding_size: 0,
356        })
357    }
358}
359
360impl Header {
361    /// Marshaled header size given an already-computed extension payload length
362    /// (see [`Header::get_extension_payload_len`]). Lets `marshal_to` size the
363    /// buffer and write the extension length field from a single scan of the
364    /// extensions instead of walking them via `marshal_size` and again directly.
365    fn marshal_size_for(&self, extension_payload_len: usize) -> usize {
366        let mut head_size = 12 + (self.csrc.len() * CSRC_LENGTH);
367        if self.extension {
368            let padded = extension_payload_len + self.extensions_padding;
369            head_size += 4 + padded.div_ceil(4) * 4;
370        }
371        head_size
372    }
373}
374
375impl MarshalSize for Header {
376    /// MarshalSize returns the size of the packet once marshaled.
377    fn marshal_size(&self) -> usize {
378        let extension_payload_len = if self.extension {
379            self.get_extension_payload_len()
380        } else {
381            0
382        };
383        self.marshal_size_for(extension_payload_len)
384    }
385}
386
387impl Marshal for Header {
388    /// Marshal serializes the header and writes to the buffer.
389    fn marshal_to(&self, mut buf: &mut [u8]) -> Result<usize> {
390        /*
391         *  0                   1                   2                   3
392         *  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
393         * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
394         * |V=2|P|X|  CC   |M|     PT      |       sequence number         |
395         * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
396         * |                           timestamp                           |
397         * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
398         * |           synchronization source (SSRC) identifier            |
399         * +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
400         * |            contributing source (CSRC) identifiers             |
401         * |                             ....                              |
402         * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
403         */
404        let remaining_before = buf.remaining_mut();
405        // Scan the extensions once here; reused for the bounds check, the
406        // extension length field, and the trailing padding below (previously
407        // walked three times: marshal_size() here plus twice in the body).
408        let extension_payload_len = if self.extension {
409            self.get_extension_payload_len()
410        } else {
411            0
412        };
413        if remaining_before < self.marshal_size_for(extension_payload_len) {
414            return Err(Error::ErrBufferTooSmall);
415        }
416
417        // The first byte contains the version, padding bit, extension bit, and csrc size.
418        // RFC 3550 §5.1: CC is a 4-bit field, so at most 15 contributing sources are allowed.
419        if self.csrc.len() > 15 {
420            return Err(Error::TooManyCSRCs(self.csrc.len())); // reject early to avoid truncating CC
421        }
422        // RFC 3550 section 5.1: the version is 2. Any other value would be read by the peer as
423        // STUN or DTLS (RFC 7983), and a value above 3 does not fit the field.
424        if self.version != RTP_VERSION {
425            return Err(Error::BadVersion);
426        }
427        // The payload type is a 7-bit field; a larger value would set the marker bit.
428        if self.payload_type > PT_MASK {
429            return Err(Error::WrongPayloadType);
430        }
431        let mut b0 = (self.version << VERSION_SHIFT) | self.csrc.len() as u8;
432        if self.padding {
433            b0 |= 1 << PADDING_SHIFT;
434        }
435
436        if self.extension {
437            b0 |= 1 << EXTENSION_SHIFT;
438        }
439        buf.put_u8(b0);
440
441        // The second byte contains the marker bit and payload type.
442        let mut b1 = self.payload_type;
443        if self.marker {
444            b1 |= 1 << MARKER_SHIFT;
445        }
446        buf.put_u8(b1);
447
448        buf.put_u16(self.sequence_number);
449        buf.put_u32(self.timestamp);
450        buf.put_u32(self.ssrc);
451
452        for csrc in &self.csrc {
453            buf.put_u32(*csrc);
454        }
455
456        if self.extension {
457            buf.put_u16(self.extension_profile);
458
459            // extension_payload_len computed once at the top of this function. The block is
460            // as long as `marshal_size` says: the elements, then `extensions_padding` (what a
461            // parsed block had after its elements, an ignored tail after ID 0 or 15 included),
462            // rounded up to 32-bit words. A block over 65535 bytes fits no datagram and is
463            // refused, as it always was.
464            let padded_len = extension_payload_len + self.extensions_padding;
465            if padded_len > u16::MAX as usize {
466                return Err(Error::ExtensionPayloadTotalOverflow(padded_len));
467            }
468            let form = ExtensionForm::of_profile(self.extension_profile);
469            if form == ExtensionForm::Rfc3550 && !extension_payload_len.is_multiple_of(4) {
470                //the payload must be in 32-bit words.
471                return Err(Error::HeaderExtensionPayloadNot32BitWords);
472            }
473            let extension_payload_size = padded_len.div_ceil(4) as u16;
474            buf.put_u16(extension_payload_size);
475
476            match form {
477                // RFC 8285 RTP One Byte Header Extension
478                ExtensionForm::OneByte => {
479                    for extension in &self.extensions {
480                        // validate each extension before writing
481                        // RFC 8285 §4.2: IDs 0 and 15 are reserved.
482                        if !(1..=14).contains(&extension.id) {
483                            return Err(Error::ErrRfc8285oneByteHeaderIdrange);
484                        }
485                        // RFC 8285 §4.2: payload must be 1-16 bytes; the 4-bit length field
486                        // encodes (len-1), so 0 is invalid and >16 cannot be represented.
487                        let ext_payload_len = extension.payload.len();
488                        if ext_payload_len == 0 || ext_payload_len > 16 {
489                            return Err(Error::OneByteHeaderExtensionPayloadOutOfRange(
490                                ext_payload_len,
491                            ));
492                        }
493                        // Upper nibble = extension ID, lower nibble = (length - 1)
494                        buf.put_u8((extension.id << 4) | (ext_payload_len as u8 - 1));
495                        buf.put(&*extension.payload); // write validated extension payload
496                    }
497                }
498                // RFC 8285 RTP Two Byte Header Extension
499                ExtensionForm::TwoByte => {
500                    for extension in &self.extensions {
501                        // RFC 8285 §4.3: ID 0 is padding in two-byte format;
502                        // marshaling it as an extension would confuse receivers.
503                        if extension.id == 0 {
504                            return Err(Error::ErrRfc8285twoByteHeaderIdrange);
505                        }
506                        // RFC 8285 §4.3: the length field is a single byte, capping
507                        // the maximum extension payload at 255 bytes.
508                        let ext_payload_len = extension.payload.len();
509                        if ext_payload_len > 255 {
510                            return Err(Error::TwoByteHeaderExtensionPayloadTooLarge(
511                                ext_payload_len,
512                            ));
513                        }
514                        buf.put_u8(extension.id); // two-byte format: ID occupies a full byte
515                        buf.put_u8(ext_payload_len as u8);
516                        buf.put(&*extension.payload);
517                    }
518                }
519                // RFC3550 Extension
520                ExtensionForm::Rfc3550 => {
521                    if self.extensions.len() != 1 {
522                        return Err(Error::ErrRfc3550headerIdrange);
523                    }
524
525                    if let Some(extension) = self.extensions.first() {
526                        let ext_len = extension.payload.len();
527                        if ext_len % 4 != 0 {
528                            return Err(Error::HeaderExtensionPayloadNot32BitWords);
529                        }
530                        buf.put(&*extension.payload);
531                    }
532                }
533            };
534
535            // add padding to reach 4 bytes boundaries
536            for _ in extension_payload_len..extension_payload_size as usize * 4 {
537                buf.put_u8(0);
538            }
539        }
540
541        let remaining_after = buf.remaining_mut();
542        Ok(remaining_before - remaining_after)
543    }
544}
545
546impl Header {
547    /// The total encoded length of the extension payloads, padding excluded.
548    pub fn get_extension_payload_len(&self) -> usize {
549        let payload_len: usize = self
550            .extensions
551            .iter()
552            .map(|extension| extension.payload.len())
553            .sum();
554
555        let profile_len = self.extensions.len()
556            * ExtensionForm::of_profile(self.extension_profile).element_header_len();
557
558        payload_len + profile_len
559    }
560
561    /// The form of this header's extension block, or `None` when it has none.
562    pub fn extension_form(&self) -> Option<ExtensionForm> {
563        self.extension
564            .then(|| ExtensionForm::of_profile(self.extension_profile))
565    }
566
567    /// The padding that brings the extension block to a 32-bit boundary.
568    fn canonical_extensions_padding(&self) -> usize {
569        match ExtensionForm::of_profile(self.extension_profile) {
570            ExtensionForm::Rfc3550 => 0,
571            _ => (4 - self.get_extension_payload_len() % 4) % 4,
572        }
573    }
574
575    /// Sets an RTP header extension, keeping the form the header already has.
576    ///
577    /// A header that has no extension yet takes the one-byte form when the element fits it
578    /// (id 1 to 14, 1 to 16 bytes) and the two-byte form otherwise (RFC 8285 section 4.2: an
579    /// id above 14 is never sent in the one-byte form; section 4.1.2: the two-byte form is not
580    /// used when everything fits the one-byte form).
581    ///
582    /// A header that already has extensions keeps its form, because a stream carries one form
583    /// only unless `a=extmap-allow-mixed` was negotiated (RFC 8285 sections 4.1.2 and 6). Use
584    /// [`Header::set_extension_upgrading`] when mixing is allowed, or
585    /// [`Header::upgrade_to_two_byte`] on every packet of a stream that is two-byte throughout.
586    ///
587    /// # Errors
588    ///
589    /// Fails when the id or the length does not fit the header's form, or no RFC 8285 form at
590    /// all (id 0 on a header without extensions, more than 255 bytes).
591    pub fn set_extension(&mut self, id: u8, payload: Bytes) -> Result<()> {
592        self.set_extension_in(id, payload, false)
593    }
594
595    /// Sets an RTP header extension, converting a one-byte header to the two-byte form when the
596    /// element needs it (an id above 14, an empty element or one over 16 bytes).
597    ///
598    /// The conversion changes the form of this packet only. RFC 8285 section 4.1.2 lets a
599    /// stream mix the forms only when `a=extmap-allow-mixed` was negotiated (section 6), so
600    /// call this when it was, or when the element is set on every packet of the stream (the
601    /// stream is then two-byte throughout).
602    ///
603    /// # Errors
604    ///
605    /// Fails when the element fits neither form (id 0, more than 255 bytes), or the header
606    /// carries an RFC 3550 extension that is not RFC 8285.
607    pub fn set_extension_upgrading(&mut self, id: u8, payload: Bytes) -> Result<()> {
608        self.set_extension_in(id, payload, true)
609    }
610
611    /// Converts a one-byte extension block to the two-byte form, with `appbits` 0. Every
612    /// one-byte element is valid in the two-byte form (RFC 8285 section 4.3: one id space).
613    /// A header without extensions, or already two-byte, is left as it is.
614    ///
615    /// # Errors
616    ///
617    /// Fails for a header whose extension is not RFC 8285.
618    pub fn upgrade_to_two_byte(&mut self) -> Result<()> {
619        match self.extension_form() {
620            None | Some(ExtensionForm::TwoByte) => Ok(()),
621            Some(ExtensionForm::OneByte) => {
622                self.extension_profile = EXTENSION_PROFILE_TWO_BYTE;
623                self.extensions_padding = self.canonical_extensions_padding();
624                Ok(())
625            }
626            Some(ExtensionForm::Rfc3550) => Err(Error::ErrRfc3550headerIdrange),
627        }
628    }
629
630    fn set_extension_in(&mut self, id: u8, payload: Bytes, upgrade: bool) -> Result<()> {
631        let payload_len = payload.len();
632        let form = match self.extension_form() {
633            Some(ExtensionForm::OneByte) => {
634                if ExtensionForm::one_byte_fits(id, payload_len) {
635                    ExtensionForm::OneByte
636                } else if upgrade && id != 0 && payload_len <= TWO_BYTE_EXTENSION_MAX_LEN {
637                    self.extension_profile = EXTENSION_PROFILE_TWO_BYTE;
638                    ExtensionForm::TwoByte
639                } else if !(1..=ONE_BYTE_EXTENSION_MAX_ID).contains(&id) {
640                    return Err(Error::ErrRfc8285oneByteHeaderIdrange);
641                } else {
642                    // RFC 8285 section 4.2: the element is 1 to 16 bytes.
643                    return Err(Error::ErrRfc8285oneByteHeaderSize);
644                }
645            }
646            Some(ExtensionForm::TwoByte) => {
647                if id < 1 {
648                    return Err(Error::ErrRfc8285twoByteHeaderIdrange);
649                }
650                if payload_len > TWO_BYTE_EXTENSION_MAX_LEN {
651                    return Err(Error::ErrRfc8285twoByteHeaderSize);
652                }
653                ExtensionForm::TwoByte
654            }
655            Some(ExtensionForm::Rfc3550) => {
656                if id != 0 {
657                    return Err(Error::ErrRfc3550headerIdrange);
658                }
659                ExtensionForm::Rfc3550
660            }
661            None => {
662                // No extension yet: the smallest form the element fits (RFC 8285 sections
663                // 4.1.2 and 4.2).
664                if id == 0 {
665                    return Err(Error::ErrRfc8285oneByteHeaderIdrange);
666                }
667                if payload_len > TWO_BYTE_EXTENSION_MAX_LEN {
668                    return Err(Error::ErrRfc8285twoByteHeaderSize);
669                }
670                self.extensions.clear();
671                self.extension = true;
672                if ExtensionForm::one_byte_fits(id, payload_len) {
673                    self.extension_profile = EXTENSION_PROFILE_ONE_BYTE;
674                    ExtensionForm::OneByte
675                } else {
676                    self.extension_profile = EXTENSION_PROFILE_TWO_BYTE;
677                    ExtensionForm::TwoByte
678                }
679            }
680        };
681
682        // Update the element if it exists, else add it.
683        if let Some(extension) = self
684            .extensions
685            .iter_mut()
686            .find(|extension| extension.id == id)
687        {
688            extension.payload = payload;
689        } else {
690            self.extensions.push(Extension { id, payload });
691        }
692        debug_assert_eq!(form, ExtensionForm::of_profile(self.extension_profile));
693        self.extensions_padding = self.canonical_extensions_padding();
694        Ok(())
695    }
696
697    /// returns an extension id array
698    pub fn get_extension_ids(&self) -> Vec<u8> {
699        if self.extension {
700            self.extensions.iter().map(|e| e.id).collect()
701        } else {
702            vec![]
703        }
704    }
705
706    /// returns an RTP header extension
707    pub fn get_extension(&self, id: u8) -> Option<Bytes> {
708        if self.extension {
709            self.extensions
710                .iter()
711                .find(|extension| extension.id == id)
712                .map(|extension| extension.payload.clone())
713        } else {
714            None
715        }
716    }
717
718    /// Removes an RTP Header extension.
719    ///
720    /// Removing the last element removes the extension block too: the X bit is cleared, since
721    /// the block is present only when the packet carries at least one element (RFC 8285
722    /// section 4.1.1).
723    pub fn del_extension(&mut self, id: u8) -> Result<()> {
724        if self.extension {
725            if let Some(index) = self
726                .extensions
727                .iter()
728                .position(|extension| extension.id == id)
729            {
730                self.extensions.remove(index);
731                if self.extensions.is_empty() {
732                    self.extension = false;
733                    self.extensions_padding = 0;
734                } else {
735                    self.extensions_padding = self.canonical_extensions_padding();
736                }
737
738                Ok(())
739            } else {
740                Err(Error::ErrHeaderExtensionNotFound)
741            }
742        } else {
743            Err(Error::ErrHeaderExtensionsNotEnabled)
744        }
745    }
746}
747
748#[cfg(test)]
749mod header_test;
750#[cfg(test)]
751mod rfc8285_test;