Skip to main content

o_sfu_rfc/
rtp.rs

1//! RFC references covered:
2//! - RTP base protocol: <https://www.rfc-editor.org/rfc/rfc3550>
3//! - RTP A/V profile payload assignments: <https://www.rfc-editor.org/rfc/rfc3551>
4//! - RTP header extension framework: <https://www.rfc-editor.org/rfc/rfc8285>
5//! - RTCP feedback profile: <https://www.rfc-editor.org/rfc/rfc4585>
6//! - RTP retransmission payload format: <https://www.rfc-editor.org/rfc/rfc4588>
7//! - RTP stream identifier SDES items: <https://www.rfc-editor.org/rfc/rfc8852>
8//! - Video frame marking RTP header extension: <https://www.rfc-editor.org/rfc/rfc9626>
9//! - Layer Refresh Request feedback: <https://www.rfc-editor.org/rfc/rfc9627>
10//! - RTP payload format for VP8: <https://www.rfc-editor.org/rfc/rfc7741>
11//! - RTP payload format for H264: <https://www.rfc-editor.org/rfc/rfc6184>
12//!
13//! A complete RTP packet has this outer shape:
14//!
15//! ```text
16//!  0                   1                   2                   3
17//!  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
18//! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
19//! |V=2|P|X|  CC   |M|     PT      |       sequence number         |
20//! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
21//! |                           timestamp                           |
22//! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
23//! |                             SSRC                              |
24//! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
25//! |                         CSRC list ...                         |
26//! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
27//! |              extension block if X=1 ...                       |
28//! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
29//! |                         codec payload ...                     |
30//! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
31//! ```
32//!
33//! Generic NACK is RTCP feedback rather than a field in an RTP packet. One
34//! RTPFB packet can carry multiple `PID`/`BLP` entries:
35//!
36//! ```text
37//!  0                   1                   2                   3
38//!  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
39//! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
40//! |V=2|P| FMT=1 |    PT=205     |             length              |
41//! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
42//! |                    SSRC of feedback sender                    |
43//! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
44//! |                     SSRC of primary media                     |
45//! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
46//! |              PID              |              BLP              |
47//! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
48//! |                    more PID/BLP entries ...                   |
49//! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
50//! ```
51//!
52//! `PID` names one missing primary RTP sequence number. Zero-based BLP bit `i`
53//! reports `(PID + i + 1) mod 2^16` as missing. See
54//! [RFC 4585 section 6.1](https://www.rfc-editor.org/rfc/rfc4585.html#section-6.1)
55//! and
56//! [RFC 4585 section 6.2.1](https://www.rfc-editor.org/rfc/rfc4585.html#section-6.2.1).
57//!
58//! RTX is a new RTP packet in the repair stream. Its RTP header has the repair
59//! payload type, repair SSRC and an independent repair sequence number. The
60//! payload begins with the original sequence number:
61//!
62//! ```text
63//!  0                   1                   2                   3
64//!  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
65//! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
66//! |V=2|P|X|  CC   |M|   RTX PT    |    repair sequence number     |
67//! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
68//! |                    original RTP timestamp                     |
69//! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
70//! |                          repair SSRC                          |
71//! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
72//! |         optional CSRC list and RTP header extension ...       |
73//! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
74//! |              OSN              |                               |
75//! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+                               |
76//! |                 original RTP packet payload ...               |
77//! +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
78//! ```
79//!
80//! `apt` binds the RTX payload type to the primary payload type in SDP. It is
81//! not carried in either packet. See
82//! [RFC 4588 section 4](https://www.rfc-editor.org/rfc/rfc4588.html#section-4)
83//! and
84//! [RFC 4588 section 8.1](https://www.rfc-editor.org/rfc/rfc4588.html#section-8.1).
85
86use std::{fmt, iter, mem};
87
88use crate::webrtc::sdp;
89
90/// RTP version defined by RFC 3550 section 5.1.
91pub const RTP_VERSION: u8 = 2;
92
93/// RTP version bits in the first octet of RTP and RTCP packets.
94///
95/// References:
96/// - <https://www.rfc-editor.org/rfc/rfc3550.html#section-5.1>
97/// - <https://www.rfc-editor.org/rfc/rfc3550.html#section-6.4.1>
98const RTP_VERSION_HEADER_BITS: u8 = RTP_VERSION << RTP_VERSION_SHIFT;
99
100/// Fixed RTP header length in bytes with no CSRC and no extension.
101///
102/// Reference: RFC 3550 section 5.1.
103pub const RTP_FIXED_HEADER_BYTES: usize = 12;
104
105/// Number of values representable by the 7-bit RTP payload type field.
106///
107/// Reference: <https://www.rfc-editor.org/rfc/rfc3550.html#section-5.1>
108pub const RTP_PAYLOAD_TYPE_COUNT: usize = 1 << RTP_PAYLOAD_TYPE_BITS;
109
110/// Maximum number of CSRC identifiers in the RTP fixed header.
111///
112/// The CC field is 4 bits, so the valid range is 0..=15.
113/// Reference: RFC 3550 section 5.1.
114pub const RTP_MAX_CSRC_COUNT: u8 = 15;
115
116/// Sequence number rollover modulus for the 16-bit RTP sequence number.
117///
118/// Reference: RFC 3550 section 5.1.
119pub const RTP_SEQUENCE_NUMBER_MODULUS: u32 = 1_u32 << 16;
120
121/// Timestamp rollover modulus for the 32-bit RTP timestamp field.
122///
123/// Reference: RFC 3550 section 5.1.
124pub const RTP_TIMESTAMP_MODULUS: u64 = 1_u64 << 32;
125
126/// Maximum value representable by the 7-bit RTP payload type field.
127///
128/// Reference: RFC 3550 section 5.1.
129pub const RTP_PAYLOAD_TYPE_MAX: u8 = 127;
130
131/// Dynamic RTP payload type range in RTP/AVP.
132///
133/// Reference: RFC 3551 section 6.
134pub const RTP_DYNAMIC_PAYLOAD_TYPE_START: u8 = 96;
135pub const RTP_DYNAMIC_PAYLOAD_TYPE_END: u8 = 127;
136
137/// Payload type range disallowed when RTP and RTCP share one port.
138///
139/// RFC 5761 reserves the full 64 through 95 payload type range for muxed
140/// sessions so the second packet octet can unambiguously distinguish RTP from
141/// RTCP.
142///
143/// Reference: RFC 5761 section 4.
144pub const RTP_RTCP_MUX_FORBIDDEN_PAYLOAD_TYPE_START: u8 = 64;
145pub const RTP_RTCP_MUX_FORBIDDEN_PAYLOAD_TYPE_END: u8 = 95;
146
147const RTP_VERSION_SHIFT: u32 = 6;
148const RTP_VERSION_MASK: u8 = 0b1100_0000;
149const RTP_PAYLOAD_TYPE_BITS: u32 = 7;
150const RTP_PAYLOAD_TYPE_MASK: u8 = RTP_PAYLOAD_TYPE_MAX;
151const RTP_PADDING_MASK: u8 = 0b0010_0000;
152const RTP_EXTENSION_MASK: u8 = 0b0001_0000;
153const RTP_CSRC_COUNT_MASK: u8 = 0b0000_1111;
154const RTP_MARKER_MASK: u8 = 0b1000_0000;
155const RTP_SEQUENCE_NUMBER_OFFSET: usize = 2;
156const RTP_TIMESTAMP_OFFSET: usize = 4;
157const RTP_SSRC_OFFSET: usize = 8;
158const RTP_CSRC_BYTES: usize = 4;
159
160// RTCP header fields from RFC 3550 section 6.4.1:
161// <https://www.rfc-editor.org/rfc/rfc3550.html#section-6.4.1>
162/// RTCP common-header length in bytes.
163const RTCP_COMMON_HEADER_BYTES: usize = 4;
164/// RTCP length field follows the flags/count and packet-type octets.
165const RTCP_LENGTH_OFFSET: usize = 2;
166/// SSRC field length in an RTCP packet.
167const RTCP_SSRC_BYTES: usize = 4;
168
169/// Length of an RTCP Receiver Report with no report blocks.
170///
171/// Reference: <https://www.rfc-editor.org/rfc/rfc3550.html#section-6.4.2>
172pub const RTCP_RECEIVER_REPORT_WITHOUT_BLOCKS_BYTES: usize =
173    RTCP_COMMON_HEADER_BYTES + RTCP_SSRC_BYTES;
174
175const RTCP_RECEIVER_REPORT_WITHOUT_BLOCKS_LENGTH_WORDS_MINUS_ONE: u16 = 1;
176
177/// Number of octets prepended to an RTX payload for the original sequence
178/// number.
179///
180/// Reference: <https://www.rfc-editor.org/rfc/rfc4588.html#section-4>
181pub const RTX_ORIGINAL_SEQUENCE_NUMBER_BYTES: usize = 2;
182
183/// Number of sequence numbers represented by the Generic NACK BLP field after
184/// its PID.
185///
186/// Reference: <https://www.rfc-editor.org/rfc/rfc4585.html#section-6.2.1>
187const GENERIC_NACK_BITMASK_BITS: u16 = 16;
188
189/// Common static RTP/AVP payload type assignments.
190///
191/// Reference: RFC 3551 section 6, tables 4 and 5.
192#[derive(Debug, Clone, Copy, PartialEq, Eq)]
193#[repr(u8)]
194pub enum AvpStaticPayloadType {
195    Pcmu = 0,
196    Gsm = 3,
197    G723 = 4,
198    Dvi4_8000 = 5,
199    Dvi4_16000 = 6,
200    Lpc = 7,
201    Pcma = 8,
202    G722 = 9,
203    L16Stereo = 10,
204    L16Mono = 11,
205    Qcelp = 12,
206    ComfortNoise = 13,
207    Mpa = 14,
208    G728 = 15,
209    Dvi4_11025 = 16,
210    Dvi4_22050 = 17,
211    G729 = 18,
212    Celb = 25,
213    Jpeg = 26,
214    Nv = 28,
215    H261 = 31,
216    Mpv = 32,
217    Mp2t = 33,
218    H263 = 34,
219}
220
221impl AvpStaticPayloadType {
222    #[must_use]
223    #[expect(
224        clippy::as_conversions,
225        reason = "repr(u8) guarantees safe identity cast"
226    )]
227    pub const fn as_u8(self) -> u8 {
228        self as u8
229    }
230}
231
232/// 7-bit RTP payload type value usable in RTP/RTCP muxed sessions
233#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
234pub struct PayloadType(u8);
235
236#[derive(Debug, Clone, Copy, PartialEq, Eq)]
237pub struct InvalidPayloadType;
238
239impl PayloadType {
240    #[must_use]
241    pub const fn try_new(value: u8) -> Option<Self> {
242        if is_rtcp_mux_payload_type(value) {
243            Some(Self(value))
244        } else {
245            None
246        }
247    }
248
249    /// builds a payload type for the muxed RTP sessions used by `o-sfu`
250    ///
251    /// # Panics
252    ///
253    /// panics when `value` does not fit the RTP payload type field or is in the
254    /// RTP/RTCP mux forbidden range from RFC 5761 section 4
255    #[must_use]
256    pub const fn new(value: u8) -> Self {
257        assert!(is_rtcp_mux_payload_type(value));
258        Self(value)
259    }
260
261    #[must_use]
262    pub const fn value(self) -> u8 {
263        self.0
264    }
265}
266
267impl TryFrom<u8> for PayloadType {
268    type Error = InvalidPayloadType;
269
270    fn try_from(value: u8) -> Result<Self, Self::Error> {
271        Self::try_new(value).ok_or(InvalidPayloadType)
272    }
273}
274
275impl From<PayloadType> for u8 {
276    fn from(value: PayloadType) -> Self {
277        value.value()
278    }
279}
280
281/// RTP or RTCP candidate selected by the RFC 5761 second-octet split.
282///
283/// The result identifies only the mux candidate kind. It does not validate the
284/// complete packet body.
285///
286/// Reference: <https://www.rfc-editor.org/rfc/rfc5761.html#section-4>
287#[derive(Debug, Clone, Copy, PartialEq, Eq)]
288pub enum RtpRtcpMuxPacketKind {
289    Rtp,
290    Rtcp,
291}
292
293/// Parsed fields from an RTP fixed header in an RTP/RTCP muxed session.
294///
295/// Reference: <https://www.rfc-editor.org/rfc/rfc3550.html#section-5.1>
296#[derive(Debug, Clone, Copy, PartialEq, Eq)]
297pub struct RtpFixedHeader {
298    payload_type: u8,
299    sequence_number: u16,
300    timestamp: u32,
301    ssrc: Ssrc,
302    marker: bool,
303    has_padding: bool,
304    has_extension: bool,
305    csrc_count: u8,
306}
307
308impl RtpFixedHeader {
309    #[must_use]
310    pub const fn payload_type(self) -> u8 {
311        self.payload_type
312    }
313
314    #[must_use]
315    pub const fn sequence_number(self) -> u16 {
316        self.sequence_number
317    }
318
319    #[must_use]
320    pub const fn timestamp(self) -> u32 {
321        self.timestamp
322    }
323
324    #[must_use]
325    pub const fn ssrc(self) -> Ssrc {
326        self.ssrc
327    }
328
329    #[must_use]
330    pub const fn marker(self) -> bool {
331        self.marker
332    }
333
334    #[must_use]
335    pub const fn has_padding(self) -> bool {
336        self.has_padding
337    }
338
339    #[must_use]
340    const fn has_extension(self) -> bool {
341        self.has_extension
342    }
343
344    fn extension_offset(self) -> usize {
345        RTP_FIXED_HEADER_BYTES + usize::from(self.csrc_count) * RTP_CSRC_BYTES
346    }
347}
348
349/// Synchronization source identifier for a media stream (RFC 3550).
350///
351/// Every distinct stream of packets (e.g. one audio track, one camera layer)
352/// is assigned a random 32-bit SSRC. This allows multiple streams to be
353/// multiplexed over a single transport (e.g. one UDP port).
354#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
355pub struct Ssrc(u32);
356
357impl Ssrc {
358    #[must_use]
359    pub const fn new(value: u32) -> Self {
360        Self(value)
361    }
362
363    #[must_use]
364    pub const fn value(self) -> u32 {
365        self.0
366    }
367}
368
369impl From<u32> for Ssrc {
370    fn from(value: u32) -> Self {
371        Self::new(value)
372    }
373}
374
375impl From<Ssrc> for u32 {
376    fn from(value: Ssrc) -> Self {
377        value.value()
378    }
379}
380
381/// Restriction identifier (RFC 8851).
382///
383/// Used in "Simulcast" to label different encodings of the same source (e.g.
384/// "low" and "high" resolution). Unlike SSRC which is a random number that
385/// can change if a collision occurs, RID is a stable string label.
386#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
387pub struct Rid(String);
388
389impl Rid {
390    #[must_use]
391    pub fn try_new(value: impl Into<String>) -> Option<Self> {
392        let value = value.into();
393        sdp::rid::is_id(value.as_str()).then_some(Self(value))
394    }
395
396    /// Builds a RID using the RFC 8851 `rid-id` grammar corrected by RFC Editor errata 7132.
397    ///
398    /// # Panics
399    ///
400    /// Panics when `value` is empty, too long or contains a non-alphanumeric
401    /// byte.
402    #[must_use]
403    pub fn new(value: impl Into<String>) -> Self {
404        let value = value.into();
405        assert!(sdp::rid::is_id(value.as_str()));
406        Self(value)
407    }
408
409    #[must_use]
410    pub fn as_str(&self) -> &str {
411        self.0.as_str()
412    }
413}
414
415impl From<&str> for Rid {
416    fn from(value: &str) -> Self {
417        Self::new(value)
418    }
419}
420
421impl From<String> for Rid {
422    fn from(value: String) -> Self {
423        Self::new(value)
424    }
425}
426
427/// Media identification (RFC 9143).
428///
429/// Ties an RTP stream to a specific "m=" section in the SDP. This is
430/// critical for "BUNDLE" where multiple media sections share one transport,
431/// as it provides a stable way to route packets to the correct logical track.
432#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
433pub struct Mid(String);
434
435impl Mid {
436    #[must_use]
437    pub fn new(value: impl Into<String>) -> Self {
438        Self(value.into())
439    }
440
441    #[must_use]
442    pub fn as_str(&self) -> &str {
443        self.0.as_str()
444    }
445}
446
447impl From<&str> for Mid {
448    fn from(value: &str) -> Self {
449        Self::new(value)
450    }
451}
452
453impl From<String> for Mid {
454    fn from(value: String) -> Self {
455        Self::new(value)
456    }
457}
458
459/// Local 4-bit identifier for a header extension (RFC 8285).
460#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
461pub struct HeaderExtensionId(u8);
462
463impl HeaderExtensionId {
464    #[must_use]
465    pub const fn try_new(value: u8) -> Option<Self> {
466        if header_extension::is_one_byte_id(value) {
467            Some(Self(value))
468        } else {
469            None
470        }
471    }
472
473    /// Builds a one-byte RTP header-extension id.
474    ///
475    /// # Panics
476    ///
477    /// Panics when `value` is padding, reserved or outside the RFC 8285
478    /// one-byte element id range.
479    #[must_use]
480    pub const fn new(value: u8) -> Self {
481        assert!(header_extension::is_one_byte_id(value));
482        Self(value)
483    }
484
485    #[must_use]
486    pub const fn value(self) -> u8 {
487        self.0
488    }
489}
490
491impl From<u8> for HeaderExtensionId {
492    fn from(value: u8) -> Self {
493        Self::new(value)
494    }
495}
496
497impl From<HeaderExtensionId> for u8 {
498    fn from(value: HeaderExtensionId) -> Self {
499        value.value()
500    }
501}
502
503/// RTP clock rate used by the supported video payload formats
504///
505/// Reference: IANA RTP Payload Format Media Types registry
506pub const RTP_VIDEO_CLOCK_RATE_HZ: u32 = 90_000;
507
508/// RTP payload-format MIME subtype names commonly used by WebRTC endpoints.
509pub mod codec_name {
510    /// PCMU RTP payload-format subtype.
511    ///
512    /// Reference: RFC 3551.
513    pub const PCMU: &str = "PCMU";
514
515    /// PCMA RTP payload-format subtype.
516    ///
517    /// Reference: RFC 3551.
518    pub const PCMA: &str = "PCMA";
519
520    /// Opus RTP payload-format subtype.
521    ///
522    /// Reference: RFC 7587.
523    pub const OPUS: &str = "opus";
524
525    /// VP8 RTP payload-format subtype.
526    ///
527    /// Reference: RFC 7741.
528    pub const VP8: &str = "VP8";
529
530    /// H264 RTP payload-format subtype.
531    ///
532    /// Reference: RFC 6184.
533    pub const H264: &str = "H264";
534
535    /// H265 RTP payload-format subtype.
536    ///
537    /// Reference: RFC 7798.
538    pub const H265: &str = "H265";
539
540    /// VP9 RTP payload-format subtype.
541    ///
542    /// Reference: RFC 9628.
543    pub const VP9: &str = "VP9";
544
545    /// AV1 RTP payload-format subtype.
546    ///
547    /// Reference: IANA Media Types registry.
548    pub const AV1: &str = "AV1";
549
550    /// RTX retransmission RTP payload-format subtype.
551    ///
552    /// Reference: RFC 4588.
553    pub const RTX: &str = "rtx";
554}
555
556/// G.711 RTP payload-format constants
557pub mod g711 {
558    /// RTP clock rate for the static PCMU and PCMA RTP/AVP payload types
559    ///
560    /// Reference: RFC 3551 section 6
561    pub const RTP_CLOCK_RATE_HZ: u32 = 8_000;
562}
563
564/// Opus RTP payload-format constants.
565///
566/// Reference: RFC 7587 for the RTP payload format and RFC 6716 for the
567/// packet table-of-contents layout.
568pub mod opus {
569    /// RTP clock rate for Opus payloads.
570    ///
571    /// Reference: RFC 7587 section 4.1.
572    pub const RTP_CLOCK_RATE_HZ: u32 = 48_000;
573
574    /// Opus channel count signaled in SDP `rtpmap` attributes.
575    ///
576    /// Reference: RFC 7587 section 7.
577    pub const RTPMAP_CHANNEL_COUNT: u16 = 2;
578
579    /// Opus packet frame-count codes from the table-of-contents byte.
580    ///
581    /// Reference: RFC 6716 section 3.1.
582    pub mod frame_count_code {
583        /// One frame in the Opus packet.
584        pub const ONE_FRAME: u8 = 0;
585    }
586
587    /// Opus table-of-contents configuration numbers.
588    ///
589    /// Reference: RFC 6716 section 3.1.
590    pub mod toc_config {
591        /// SILK-only wideband packet with a 20 ms frame duration.
592        pub const SILK_WIDEBAND_20_MS: u8 = 9;
593    }
594}
595
596/// VP8 RTP payload helpers.
597///
598/// These helpers operate on the codec payload slice, not on the full RTP
599/// packet. In runtime forwarding that slice starts after the RTP fixed header,
600/// CSRC list and any RTP header-extension block.
601///
602/// RFC 7741 puts a VP8 payload descriptor in front of the VP8 payload header.
603/// The descriptor is also where simulcast and temporal-layer packet identity is
604/// carried. o-sfu keeps the RFC constants here, while the runtime uses str0m's
605/// descriptor parser and patch support for local egress.
606///
607/// ```text
608/// VP8 payload slice passed to this module
609///
610/// +------------------+----------------------+----------------------+
611/// | descriptor byte  | extension bytes      | VP8 payload header   |
612/// +------------------+----------------------+----------------------+
613/// | X R N S PartID   | I L T K fields       | P bit and VP8 data   |
614/// +------------------+----------------------+----------------------+
615///
616/// Extension bytes when X=1
617///
618/// +-------------+-------------------+-------------+----------------+
619/// | I L T K ... | PictureID if I=1  | TL0 if L=1  | T/K if present |
620/// +-------------+-------------------+-------------+----------------+
621/// |             | 1 or 2 bytes      | 1 byte      | 1 byte         |
622/// +-------------+-------------------+-------------+----------------+
623/// ```
624pub mod vp8 {
625    /// Extended control bits are present in the VP8 payload descriptor.
626    pub const X_BIT: u8 = 0b1000_0000;
627
628    /// Start of VP8 partition bit in the payload descriptor.
629    pub const S_BIT: u8 = 0b0001_0000;
630
631    const PARTITION_ID_MASK: u8 = 0b0000_0111;
632
633    /// `PictureID` present bit in the extended VP8 payload descriptor.
634    pub const I_BIT: u8 = 0b1000_0000;
635
636    /// TL0PICIDX present bit in the extended VP8 payload descriptor.
637    pub const L_BIT: u8 = 0b0100_0000;
638
639    /// TID/Y/KEYIDX present bit in the extended VP8 payload descriptor.
640    pub const T_BIT: u8 = 0b0010_0000;
641
642    const K_BIT: u8 = 0b0001_0000;
643
644    /// Long `PictureID` marker bit in the VP8 `PictureID` field.
645    pub const LONG_PICTURE_ID_BIT: u8 = 0b1000_0000;
646
647    /// VP8 payload-header P bit set for interframes.
648    pub const INTERFRAME_BIT: u8 = 0b0000_0001;
649
650    const VERSION_MASK: u8 = 0b0000_1110;
651    const VERSION_SHIFT: u32 = 1;
652    const MAX_DEFINED_VERSION: u8 = 3;
653    const DIMENSION_MASK: u16 = 0x3fff;
654    const KEYFRAME_SYNC_CODE: [u8; 3] = [0x9d, 0x01, 0x2a];
655
656    /// value mask for the 7-bit VP8 short `PictureID` field
657    pub const SHORT_PICTURE_ID_MASK: u16 = 0x7f;
658
659    /// Value mask for the 15-bit VP8 long `PictureID` field.
660    pub const LONG_PICTURE_ID_MASK: u16 = 0x7fff;
661
662    /// Modulus for the 15-bit VP8 long `PictureID` field.
663    pub const LONG_PICTURE_ID_MODULUS: u16 = 1 << 15;
664
665    /// Value mask for the two-bit VP8 temporal-layer identity.
666    pub const TEMPORAL_LAYER_ID_MASK: u8 = 0b0000_0011;
667
668    /// Detects a complete VP8 keyframe prefix in the first RTP packet.
669    ///
670    /// RFC 7741 section 4.2 defines the VP8 payload descriptor. A decodable
671    /// keyframe starts at partition 0 (`S=1`, `PartID=0`) and the VP8 payload
672    /// header starts with `P=0`. RFC 6386 section 9.1 defines the keyframe sync
673    /// code and dimensions. The input must be the RTP codec payload.
674    ///
675    /// Truncated descriptors, missing payload headers and non-start partitions
676    /// return `false`. The helper performs only the cheap
677    /// keyframe probe needed by packet gates and decoder-refresh detection.
678    #[must_use]
679    pub fn payload_starts_keyframe(payload: &[u8]) -> bool {
680        let Some((&descriptor, rest)) = payload.split_first() else {
681            return false;
682        };
683        if descriptor & S_BIT == 0 || descriptor & PARTITION_ID_MASK != 0 {
684            return false;
685        }
686        let frame = if descriptor & X_BIT == 0 {
687            rest
688        } else {
689            let Some(frame) = extended_frame_payload(rest) else {
690                return false;
691            };
692            frame
693        };
694        valid_keyframe_prefix(frame)
695    }
696
697    /// Locates the VP8 frame bytes after an extended descriptor.
698    ///
699    /// `None` means the extension-bit combination is malformed or an advertised
700    /// field is absent. The keyframe probe treats that as "not a keyframe".
701    fn extended_frame_payload(payload: &[u8]) -> Option<&[u8]> {
702        let (&extension, mut rest) = payload.split_first()?;
703        if extension & I_BIT != 0 {
704            let (&picture_id, remaining) = rest.split_first()?;
705            rest = if picture_id & LONG_PICTURE_ID_BIT != 0 {
706                remaining.get(1..)?
707            } else {
708                remaining
709            };
710        }
711        if extension & L_BIT != 0 {
712            if extension & T_BIT == 0 {
713                return None;
714            }
715            rest = rest.get(1..)?;
716        }
717        if extension & T_BIT != 0 || extension & K_BIT != 0 {
718            rest = rest.get(1..)?;
719        }
720        (!rest.is_empty()).then_some(rest)
721    }
722
723    fn valid_keyframe_prefix(frame: &[u8]) -> bool {
724        let &[
725            tag,
726            _,
727            _,
728            sync_0,
729            sync_1,
730            sync_2,
731            width_low,
732            width_high,
733            height_low,
734            height_high,
735            ..,
736        ] = frame
737        else {
738            return false;
739        };
740        let version = (tag & VERSION_MASK) >> VERSION_SHIFT;
741        let width = u16::from_le_bytes([width_low, width_high]) & DIMENSION_MASK;
742        let height = u16::from_le_bytes([height_low, height_high]) & DIMENSION_MASK;
743        tag & INTERFRAME_BIT == 0
744            && version <= MAX_DEFINED_VERSION
745            && [sync_0, sync_1, sync_2] == KEYFRAME_SYNC_CODE
746            && width != 0
747            && height != 0
748    }
749}
750
751/// VP9 profile identifier defined by RFC 9628 section 6
752#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
753pub struct Vp9ProfileId(u8);
754
755impl Vp9ProfileId {
756    /// VP9 Profile 0
757    pub const PROFILE_0: Self = Self(0);
758
759    /// VP9 Profile 1
760    pub const PROFILE_1: Self = Self(1);
761
762    /// VP9 Profile 2
763    pub const PROFILE_2: Self = Self(2);
764
765    /// VP9 Profile 3
766    pub const PROFILE_3: Self = Self(3);
767
768    #[must_use]
769    pub const fn try_new(value: u8) -> Option<Self> {
770        if value <= Self::PROFILE_3.value() {
771            Some(Self(value))
772        } else {
773            None
774        }
775    }
776
777    #[must_use]
778    pub const fn value(self) -> u8 {
779        self.0
780    }
781}
782
783/// RTP payload-format MIME subtype names commonly used by WebRTC endpoints.
784#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
785pub enum CodecName {
786    Pcmu,
787    Pcma,
788    Opus,
789    Vp8,
790    H264,
791    H265,
792    Vp9,
793    Av1,
794    Rtx,
795    Other(String),
796}
797
798impl CodecName {
799    #[must_use]
800    pub fn as_str(&self) -> &str {
801        match self {
802            Self::Pcmu => codec_name::PCMU,
803            Self::Pcma => codec_name::PCMA,
804            Self::Opus => codec_name::OPUS,
805            Self::Vp8 => codec_name::VP8,
806            Self::H264 => codec_name::H264,
807            Self::H265 => codec_name::H265,
808            Self::Vp9 => codec_name::VP9,
809            Self::Av1 => codec_name::AV1,
810            Self::Rtx => codec_name::RTX,
811            Self::Other(name) => name.as_str(),
812        }
813    }
814
815    #[must_use]
816    pub fn is_rtx(&self) -> bool {
817        matches!(self, Self::Rtx)
818    }
819}
820
821impl From<&str> for CodecName {
822    fn from(value: &str) -> Self {
823        match value {
824            s if s.eq_ignore_ascii_case(codec_name::PCMU) => Self::Pcmu,
825            s if s.eq_ignore_ascii_case(codec_name::PCMA) => Self::Pcma,
826            s if s.eq_ignore_ascii_case(codec_name::OPUS) => Self::Opus,
827            s if s.eq_ignore_ascii_case(codec_name::VP8) => Self::Vp8,
828            s if s.eq_ignore_ascii_case(codec_name::H264) => Self::H264,
829            s if s.eq_ignore_ascii_case(codec_name::H265) => Self::H265,
830            s if s.eq_ignore_ascii_case(codec_name::VP9) => Self::Vp9,
831            s if s.eq_ignore_ascii_case(codec_name::AV1) => Self::Av1,
832            s if s.eq_ignore_ascii_case(codec_name::RTX) => Self::Rtx,
833            _ => Self::Other(value.to_owned()),
834        }
835    }
836}
837
838impl From<String> for CodecName {
839    fn from(value: String) -> Self {
840        Self::from(value.as_str())
841    }
842}
843
844impl AsRef<str> for CodecName {
845    fn as_ref(&self) -> &str {
846        self.as_str()
847    }
848}
849
850impl fmt::Display for CodecName {
851    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
852        f.write_str(self.as_str())
853    }
854}
855
856/// Codec `fmtp` parameter names and canonical valuse
857pub mod fmtp {
858    /// Separator between format-specific parameters used by RTX `fmtp`.
859    ///
860    /// Reference: <https://www.rfc-editor.org/rfc/rfc4588.html#section-8.6>
861    pub const PARAMETER_SEPARATOR: char = ';';
862
863    /// Separator between an RTX `fmtp` parameter name and value.
864    ///
865    /// Reference: <https://www.rfc-editor.org/rfc/rfc4588.html#section-8.6>
866    pub const NAME_VALUE_SEPARATOR: char = '=';
867
868    /// RTX associated payload type parameter
869    ///
870    /// Reference: <https://www.rfc-editor.org/rfc/rfc4588.html#section-8.1>
871    pub const RTX_ASSOCIATION: &str = "apt";
872
873    /// H264 packetization mode parameter.
874    ///
875    /// Reference: RFC 6184 section 8.1.
876    pub const H264_PACKETIZATION_MODE: &str = "packetization-mode";
877
878    /// H264 profile-level-id parameter.
879    ///
880    /// Reference: RFC 6184 section 8.1
881    pub const H264_PROFILE_LEVEL_ID: &str = "profile-level-id";
882
883    /// Default H264 profile-level-id when the parameter is omitted.
884    ///
885    /// Reference: RFC 6184 section 8.1.
886    pub const H264_DEFAULT_PROFILE_LEVEL_ID: &str = "42000a";
887
888    /// Default H264 packetization mode when the parameter is omitted.
889    ///
890    /// Reference: RFC 6184 section 6.2.
891    pub const H264_DEFAULT_PACKETIZATION_MODE: u8 = 0;
892
893    /// VP9 profile-id parameter.
894    ///
895    /// Reference: RFC 9628 section 6.
896    pub const VP9_PROFILE_ID: &str = "profile-id";
897
898    /// Default VP9 profile when `profile-id` is omitted.
899    ///
900    /// Reference: RFC 9628 section 6.
901    pub const VP9_DEFAULT_PROFILE_ID: super::Vp9ProfileId = super::Vp9ProfileId::PROFILE_0;
902
903    /// Opus in-band FEC parameter
904    ///
905    /// Reference: RFC 7587 section 6.1.
906    pub const OPUS_USE_IN_BAND_FEC: &str = "useinbandfec";
907
908    /// Canonical numeric enabled flag used in WebRTC `fmtp` dictionaries.
909    pub const VALUE_ENABLED: &str = "1";
910
911    /// Canonical numeric disabled flag used in WebRTC `fmtp` dictionaries
912    pub const VALUE_DISABLED: &str = "0";
913
914    /// Textual enabled flag accepted by current ORTC/WebRTC capability payloads
915    pub const VALUE_TRUE: &str = "true";
916
917    /// Textual disabled flag accepted by current ORTC/WebRTC capability payloads
918    pub const VALUE_FALSE: &str = "false";
919}
920
921/// H264 SDP and payload-format helpers derived from RFC 6184.
922///
923/// Packet helpers in this module receive the H264 RTP payload slice. The first
924/// byte of that slice identifies the packetization mode used by the packet.
925/// Decoder-refresh detection needs to recognize IDR access units in all packet
926/// shapes that browsers commonly send.
927///
928/// ```text
929/// Single NAL unit packet
930///
931/// +-------------+----------------------+
932/// | NAL header  | NAL payload          |
933/// +-------------+----------------------+
934/// | F NRI Type  | ...                  |
935/// +-------------+----------------------+
936///
937/// STAP-A aggregation packet
938///
939/// +---------------+----------+-------------+----------+-------------+
940/// | STAP-A header | NAL size | NAL bytes   | NAL size | NAL bytes   |
941/// +---------------+----------+-------------+----------+-------------+
942/// | Type=24       | 16 bits  | starts with | 16 bits  | starts with |
943/// |               |          | NAL header  |          | NAL header  |
944/// +---------------+----------+-------------+----------+-------------+
945///
946/// FU-A fragmentation packet
947///
948/// +---------------+-------------+----------------------+
949/// | FU indicator  | FU header   | fragment payload     |
950/// +---------------+-------------+----------------------+
951/// | Type=28       | S E R Type  | first fragment if S=1 |
952/// +---------------+-------------+----------------------+
953/// ```
954///
955/// rfc 6184 maps `profile-level-id` to three bytes:
956///
957/// ```text
958/// profile_idc | profile-iop | level_idc
959///
960/// profile-iop bit layout:
961///  7   6   5   4   3   2   1   0
962/// +---+---+---+---+---+---+---+---+
963/// |c0 |c1 |c2 |c3 |c4 |c5 | r | r |
964/// +---+---+---+---+---+---+---+---+
965///
966/// cN = constraint_setN_flag
967/// r  = reserved_zero bit
968/// ```
969pub mod h264 {
970    /// Mask for the H264 NAL unit type field.
971    pub const NAL_UNIT_TYPE_MASK: u8 = 0x1f;
972
973    /// Highest NRI value for reference NAL units.
974    pub const NAL_REF_IDC_HIGH: u8 = 0b0110_0000;
975
976    /// H264 IDR slice NAL unit type.
977    pub const NAL_UNIT_TYPE_IDR: u8 = 5;
978
979    /// H264 STAP-A aggregation packet type.
980    pub const NAL_UNIT_TYPE_STAP_A: u8 = 24;
981
982    /// H264 FU-A fragmentation packet type.
983    pub const NAL_UNIT_TYPE_FU_A: u8 = 28;
984
985    /// FU-A start bit in the FU header.
986    pub const FU_START_BIT: u8 = 0x80;
987
988    /// FU-A end bit in the FU header.
989    pub const FU_END_BIT: u8 = 0x40;
990
991    /// H264 RTP packetization mode.
992    ///
993    /// Reference: RFC 6184 section 6.
994    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
995    pub enum PacketizationMode {
996        SingleNalUnit,
997        NonInterleaved,
998        Interleaved,
999    }
1000
1001    impl PacketizationMode {
1002        #[must_use]
1003        pub const fn from_fmtp_value(value: u8) -> Option<Self> {
1004            match value {
1005                0 => Some(Self::SingleNalUnit),
1006                1 => Some(Self::NonInterleaved),
1007                2 => Some(Self::Interleaved),
1008                _ => None,
1009            }
1010        }
1011
1012        #[must_use]
1013        pub const fn fmtp_value(self) -> u8 {
1014            match self {
1015                Self::SingleNalUnit => 0,
1016                Self::NonInterleaved => 1,
1017                Self::Interleaved => 2,
1018            }
1019        }
1020
1021        const fn allows_aggregation_and_fragmentation(self) -> bool {
1022            matches!(self, Self::NonInterleaved)
1023        }
1024    }
1025
1026    /// parsed H264 `profile-level-id` capability
1027    ///
1028    /// `profile_idc` names the broad H264 profile family, `profile-iop`
1029    /// carries constraint bits that narrow that family to a sub-profile and
1030    /// `level_idc` carries the decoder capability level. [`ProfileLevelId`]
1031    /// normalizes equivalent RFC 6184 profile encodings before router
1032    /// negotiation compares [`Profile`] and [`LevelIdc`]
1033    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1034    pub struct ProfileLevelId {
1035        profile: Profile,
1036        level: LevelIdc,
1037    }
1038
1039    impl ProfileLevelId {
1040        #[must_use]
1041        pub const fn new(profile: Profile, level: LevelIdc) -> Self {
1042            Self { profile, level }
1043        }
1044
1045        /// Parse the RFC 6184 `profile-level-id` hex token.
1046        #[must_use]
1047        pub fn parse(value: &str) -> Option<Self> {
1048            Self::parse_ascii_bytes(value.as_bytes())
1049        }
1050
1051        /// Parse the six-byte ASCII hex form of a `profile-level-id` token.
1052        #[must_use]
1053        pub fn parse_ascii_bytes(value: &[u8]) -> Option<Self> {
1054            let [profile_idc, profile_iop, level_idc] = parse_profile_level_id_bytes(value)?;
1055            let level = normalized_level_idc(profile_idc, profile_iop, level_idc)?;
1056            let profile = profile_from_bytes(profile_idc, profile_iop)?;
1057            Some(Self { profile, level })
1058        }
1059
1060        #[must_use]
1061        pub const fn profile(self) -> Profile {
1062            self.profile
1063        }
1064
1065        #[must_use]
1066        pub const fn level(self) -> LevelIdc {
1067            self.level
1068        }
1069
1070        #[must_use]
1071        pub const fn packed_value(self) -> u32 {
1072            let (profile_idc, profile_iop, level_idc) =
1073                profile_level_id_bytes(self.profile, self.level);
1074            pack_profile_level_id(profile_idc, profile_iop, level_idc)
1075        }
1076
1077        #[must_use]
1078        pub fn fmtp_value(self) -> String {
1079            let value = self.packed_value();
1080            format!("{value:06x}")
1081        }
1082    }
1083
1084    /// H264 sub-profile after equivalent RFC 6184 encodings are normalized
1085    ///
1086    /// the same sub-profile may be advertised through different
1087    /// `profile_idc` families when `profile-iop` constraints restrict them to
1088    /// the same coding tools
1089    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1090    pub enum Profile {
1091        Baseline,
1092        ConstrainedBaseline,
1093        Main,
1094        Extended,
1095        High,
1096        High10,
1097        High422,
1098        High444Predictive,
1099        High10Intra,
1100        High422Intra,
1101        High444Intra,
1102        Cavlc444Intra,
1103    }
1104
1105    /// H264 decoder capability level
1106    ///
1107    /// all levels except [`LevelIdc::Level1B`] map directly to `level_idc`
1108    /// level 1b was inserted between level 1 and level 1.1 after those byte
1109    /// values existed, so RFC 6184 gives it profile-dependent encodings
1110    ///
1111    /// the variant order is the negotiation order
1112    /// wire `level_idc` bytes are parsed and rendered explicitly because Level
1113    /// 1b is encoded specially
1114    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
1115    pub enum LevelIdc {
1116        Level1,
1117        Level1B,
1118        Level1_1,
1119        Level1_2,
1120        Level1_3,
1121        Level2,
1122        Level2_1,
1123        Level2_2,
1124        Level3,
1125        Level3_1,
1126        Level3_2,
1127        Level4,
1128        Level4_1,
1129        Level4_2,
1130        Level5,
1131        Level5_1,
1132        Level5_2,
1133    }
1134
1135    /// Detects an H264 RTP packet that starts an IDR access unit.
1136    ///
1137    /// RFC 6184 carries IDR frames either as a single NAL unit, inside a STAP-A
1138    /// aggregation packet or as the first fragment of a FU-A packet.
1139    ///
1140    /// The input must be the RTP codec payload, not a complete RTP packet.
1141    /// Truncated aggregation packets and incomplete FU-A packets return
1142    /// `false`. The helper does not parse a full access unit. It only answers
1143    /// whether this packet can refresh a decoder if forwarded.
1144    #[must_use]
1145    pub fn payload_starts_idr(payload: &[u8], packetization_mode: PacketizationMode) -> bool {
1146        let Some((&nal_header, rest)) = payload.split_first() else {
1147            return false;
1148        };
1149        match nal_header & NAL_UNIT_TYPE_MASK {
1150            NAL_UNIT_TYPE_IDR => true,
1151            NAL_UNIT_TYPE_STAP_A if packetization_mode.allows_aggregation_and_fragmentation() => {
1152                stap_a_contains_idr(rest)
1153            }
1154            NAL_UNIT_TYPE_FU_A if packetization_mode.allows_aggregation_and_fragmentation() => {
1155                fu_a_starts_idr(rest)
1156            }
1157            _ => false,
1158        }
1159    }
1160
1161    /// Scans a STAP-A payload for any contained IDR NAL unit.
1162    ///
1163    /// each aggregate entry is length-prefixed and must use a single NAL unit type
1164    /// malformed lengths fail closed because the caller cannot safely trust later
1165    /// bytes as NAL boundaries
1166    fn stap_a_contains_idr(mut payload: &[u8]) -> bool {
1167        let mut contains_idr = false;
1168        while !payload.is_empty() {
1169            let Some((len, rest)) = payload.split_first_chunk::<2>() else {
1170                return false;
1171            };
1172            let nal_len = usize::from(u16::from_be_bytes(*len));
1173            let Some((nal, remaining_payload)) = rest.split_at_checked(nal_len) else {
1174                return false;
1175            };
1176            let Some(&nal_header) = nal.first() else {
1177                return false;
1178            };
1179            let nal_type = nal_header & NAL_UNIT_TYPE_MASK;
1180            if !(1..NAL_UNIT_TYPE_STAP_A).contains(&nal_type) {
1181                return false;
1182            }
1183            contains_idr |= nal_type == NAL_UNIT_TYPE_IDR;
1184            payload = remaining_payload;
1185        }
1186        contains_idr
1187    }
1188
1189    /// Detects whether a FU-A packet is the first fragment of an IDR NAL unit.
1190    fn fu_a_starts_idr(payload: &[u8]) -> bool {
1191        let Some((&fu_header, _fragment)) = payload.split_first() else {
1192            return false;
1193        };
1194        fu_header & FU_START_BIT != 0
1195            && fu_header & FU_END_BIT == 0
1196            && fu_header & NAL_UNIT_TYPE_MASK == NAL_UNIT_TYPE_IDR
1197    }
1198
1199    impl TryFrom<u8> for LevelIdc {
1200        type Error = ();
1201
1202        fn try_from(value: u8) -> Result<Self, Self::Error> {
1203            match value {
1204                9 => Ok(Self::Level1B),
1205                10 => Ok(Self::Level1),
1206                11 => Ok(Self::Level1_1),
1207                12 => Ok(Self::Level1_2),
1208                13 => Ok(Self::Level1_3),
1209                20 => Ok(Self::Level2),
1210                21 => Ok(Self::Level2_1),
1211                22 => Ok(Self::Level2_2),
1212                30 => Ok(Self::Level3),
1213                31 => Ok(Self::Level3_1),
1214                32 => Ok(Self::Level3_2),
1215                40 => Ok(Self::Level4),
1216                41 => Ok(Self::Level4_1),
1217                42 => Ok(Self::Level4_2),
1218                50 => Ok(Self::Level5),
1219                51 => Ok(Self::Level5_1),
1220                52 => Ok(Self::Level5_2),
1221                _ => Err(()),
1222            }
1223        }
1224    }
1225
1226    const BASELINE_IDC: u8 = 0x42;
1227    const MAIN_IDC: u8 = 0x4d;
1228    const EXTENDED_IDC: u8 = 0x58;
1229    const HIGH_IDC: u8 = 0x64;
1230    const HIGH_10_IDC: u8 = 0x6e;
1231    const HIGH_422_IDC: u8 = 0x7a;
1232    const HIGH_444_IDC: u8 = 0xf4;
1233    const CAVLC_444_IDC: u8 = 0x2c;
1234
1235    // `profile-iop` is the middle byte of `profile-level-id`
1236    // constraint flags are H264 compatibility bits that refine `profile_idc`
1237    // into the sub-profile used for offer or answer matching
1238    //
1239    // bit 7 -> constraint_set0_flag -> `IOP_CONSTRAINT_SET0`
1240    // bit 6 -> constraint_set1_flag -> `IOP_CONSTRAINT_SET1`
1241    // bit 5 -> constraint_set2_flag -> `IOP_CONSTRAINT_SET2`
1242    // bit 4 -> constraint_set3_flag -> `IOP_CONSTRAINT_SET3`
1243    // bit 3 -> constraint_set4_flag -> fixed to 0 by profile-equivalence rows
1244    // bit 2 -> constraint_set5_flag -> fixed to 0 by profile-equivalence rows
1245    // bit 1..0 -> reserved_zero_2bits -> fixed to 0 by H264
1246    const IOP_NONE: u8 = 0x00;
1247    const IOP_CONSTRAINT_SET0: u8 = 0x80;
1248    const IOP_CONSTRAINT_SET1: u8 = 0x40;
1249    const IOP_CONSTRAINT_SET2: u8 = 0x20;
1250    const IOP_CONSTRAINT_SET3: u8 = 0x10;
1251    const IOP_PROFILE_PATTERN_LOW_ZERO_MASK: u8 =
1252        !(IOP_CONSTRAINT_SET0 | IOP_CONSTRAINT_SET1 | IOP_CONSTRAINT_SET2 | IOP_CONSTRAINT_SET3);
1253    const IOP_CONSTRAINED_BASELINE: u8 =
1254        IOP_CONSTRAINT_SET0 | IOP_CONSTRAINT_SET1 | IOP_CONSTRAINT_SET2;
1255
1256    const LEVEL_1B_IDCS: [u8; 3] = [BASELINE_IDC, MAIN_IDC, EXTENDED_IDC];
1257    const LEVEL_1B_OTHER_IDC: u8 = 9;
1258    const LEVEL_1_1_IDC: u8 = 11;
1259
1260    /// one accepted RFC 6184 profile-equivalence row
1261    ///
1262    /// a row maps one concrete `profile_idc` family and one wildcarded
1263    /// `profile-iop` bit pattern to the normalized [`Profile`] used by
1264    /// negotiation
1265    #[derive(Clone, Copy)]
1266    struct ProfilePattern {
1267        profile: Profile,
1268        profile_idc: u8,
1269        iop: ProfileIopPattern,
1270    }
1271
1272    impl ProfilePattern {
1273        const fn masked(profile: Profile, profile_idc: u8, iop: ProfileIopPattern) -> Self {
1274            Self {
1275                profile,
1276                profile_idc,
1277                iop,
1278            }
1279        }
1280
1281        const fn exact(profile: Profile, profile_idc: u8, value: u8) -> Self {
1282            Self {
1283                profile,
1284                profile_idc,
1285                iop: ProfileIopPattern::exact(value),
1286            }
1287        }
1288
1289        const fn matches(self, profile_idc: u8, profile_iop: u8) -> bool {
1290            self.profile_idc == profile_idc && self.iop.matches(profile_iop)
1291        }
1292    }
1293
1294    /// masked `profile-iop` matcher for profile-equivalence wildcard bits
1295    ///
1296    /// `mask` selects bits that must equal `value`. unmasked bits are RFC
1297    /// wildcards such as the `x` bits in `x1xx0000`
1298    #[derive(Clone, Copy)]
1299    struct ProfileIopPattern {
1300        mask: u8,
1301        value: u8,
1302    }
1303
1304    impl ProfileIopPattern {
1305        /// starts with the low four bits fixed to zero and high bits wildcarded
1306        const fn wildcarded() -> Self {
1307            Self {
1308                mask: IOP_PROFILE_PATTERN_LOW_ZERO_MASK,
1309                value: IOP_NONE,
1310            }
1311        }
1312
1313        const fn exact(value: u8) -> Self {
1314            Self {
1315                mask: u8::MAX,
1316                value,
1317            }
1318        }
1319
1320        const fn one(self, bit: u8) -> Self {
1321            Self {
1322                mask: self.mask | bit,
1323                value: self.value | bit,
1324            }
1325        }
1326
1327        const fn zero(self, bit: u8) -> Self {
1328            Self {
1329                mask: self.mask | bit,
1330                value: self.value & !bit,
1331            }
1332        }
1333
1334        const fn matches(self, value: u8) -> bool {
1335            value & self.mask == self.value
1336        }
1337    }
1338
1339    // rfc 6184 lists equivalent sub-profile encodings rather than one canonical byte
1340    // example: `42 x1xx0000`, `4d 1xxx0000` and `58 11xx0000` all mean
1341    // constrained baseline, so `x` bits must be ignored during matching
1342    const PROFILE_PATTERNS: &[ProfilePattern] = &[
1343        ProfilePattern::masked(
1344            Profile::ConstrainedBaseline,
1345            BASELINE_IDC,
1346            ProfileIopPattern::wildcarded().one(IOP_CONSTRAINT_SET1),
1347        ),
1348        ProfilePattern::masked(
1349            Profile::ConstrainedBaseline,
1350            MAIN_IDC,
1351            ProfileIopPattern::wildcarded().one(IOP_CONSTRAINT_SET0),
1352        ),
1353        ProfilePattern::masked(
1354            Profile::ConstrainedBaseline,
1355            EXTENDED_IDC,
1356            ProfileIopPattern::wildcarded()
1357                .one(IOP_CONSTRAINT_SET0)
1358                .one(IOP_CONSTRAINT_SET1),
1359        ),
1360        ProfilePattern::masked(
1361            Profile::Baseline,
1362            BASELINE_IDC,
1363            ProfileIopPattern::wildcarded().zero(IOP_CONSTRAINT_SET1),
1364        ),
1365        ProfilePattern::masked(
1366            Profile::Baseline,
1367            EXTENDED_IDC,
1368            ProfileIopPattern::wildcarded()
1369                .one(IOP_CONSTRAINT_SET0)
1370                .zero(IOP_CONSTRAINT_SET1),
1371        ),
1372        ProfilePattern::masked(
1373            Profile::Main,
1374            MAIN_IDC,
1375            ProfileIopPattern::wildcarded()
1376                .zero(IOP_CONSTRAINT_SET0)
1377                .zero(IOP_CONSTRAINT_SET2),
1378        ),
1379        ProfilePattern::masked(
1380            Profile::Extended,
1381            EXTENDED_IDC,
1382            ProfileIopPattern::wildcarded()
1383                .zero(IOP_CONSTRAINT_SET0)
1384                .zero(IOP_CONSTRAINT_SET1),
1385        ),
1386        ProfilePattern::exact(Profile::High, HIGH_IDC, IOP_NONE),
1387        ProfilePattern::exact(Profile::High10, HIGH_10_IDC, IOP_NONE),
1388        ProfilePattern::exact(Profile::High422, HIGH_422_IDC, IOP_NONE),
1389        ProfilePattern::exact(Profile::High444Predictive, HIGH_444_IDC, IOP_NONE),
1390        ProfilePattern::exact(Profile::High10Intra, HIGH_10_IDC, IOP_CONSTRAINT_SET3),
1391        ProfilePattern::exact(Profile::High422Intra, HIGH_422_IDC, IOP_CONSTRAINT_SET3),
1392        ProfilePattern::exact(Profile::High444Intra, HIGH_444_IDC, IOP_CONSTRAINT_SET3),
1393        ProfilePattern::exact(Profile::Cavlc444Intra, CAVLC_444_IDC, IOP_CONSTRAINT_SET3),
1394    ];
1395
1396    const fn profile_level_id_bytes(profile: Profile, level: LevelIdc) -> (u8, u8, u8) {
1397        let (profile_idc, profile_iop) = profile_bytes(profile);
1398        match level {
1399            LevelIdc::Level1B => level_1b_profile_level_id_bytes(profile_idc, profile_iop),
1400            _ => (profile_idc, profile_iop, level_idc_value(level)),
1401        }
1402    }
1403
1404    const fn profile_bytes(profile: Profile) -> (u8, u8) {
1405        match profile {
1406            Profile::Baseline => (BASELINE_IDC, IOP_NONE),
1407            Profile::ConstrainedBaseline => (BASELINE_IDC, IOP_CONSTRAINED_BASELINE),
1408            Profile::Main => (MAIN_IDC, IOP_NONE),
1409            Profile::Extended => (EXTENDED_IDC, IOP_NONE),
1410            Profile::High => (HIGH_IDC, IOP_NONE),
1411            Profile::High10 => (HIGH_10_IDC, IOP_NONE),
1412            Profile::High422 => (HIGH_422_IDC, IOP_NONE),
1413            Profile::High444Predictive => (HIGH_444_IDC, IOP_NONE),
1414            Profile::High10Intra => (HIGH_10_IDC, IOP_CONSTRAINT_SET3),
1415            Profile::High422Intra => (HIGH_422_IDC, IOP_CONSTRAINT_SET3),
1416            Profile::High444Intra => (HIGH_444_IDC, IOP_CONSTRAINT_SET3),
1417            Profile::Cavlc444Intra => (CAVLC_444_IDC, IOP_CONSTRAINT_SET3),
1418        }
1419    }
1420
1421    // level 1b has no single `level_idc` byte
1422    // baseline, main and extended borrow level 1.1's `level_idc=11` and set
1423    // constraint_set3_flag, while other profiles use `level_idc=9`
1424    const fn level_1b_profile_level_id_bytes(profile_idc: u8, profile_iop: u8) -> (u8, u8, u8) {
1425        match profile_idc {
1426            BASELINE_IDC | MAIN_IDC | EXTENDED_IDC => (
1427                profile_idc,
1428                profile_iop | IOP_CONSTRAINT_SET3,
1429                LEVEL_1_1_IDC,
1430            ),
1431            _ => (profile_idc, profile_iop, LEVEL_1B_OTHER_IDC),
1432        }
1433    }
1434
1435    const fn level_idc_value(level: LevelIdc) -> u8 {
1436        match level {
1437            LevelIdc::Level1 => 10,
1438            LevelIdc::Level1B => LEVEL_1B_OTHER_IDC,
1439            LevelIdc::Level1_1 => 11,
1440            LevelIdc::Level1_2 => 12,
1441            LevelIdc::Level1_3 => 13,
1442            LevelIdc::Level2 => 20,
1443            LevelIdc::Level2_1 => 21,
1444            LevelIdc::Level2_2 => 22,
1445            LevelIdc::Level3 => 30,
1446            LevelIdc::Level3_1 => 31,
1447            LevelIdc::Level3_2 => 32,
1448            LevelIdc::Level4 => 40,
1449            LevelIdc::Level4_1 => 41,
1450            LevelIdc::Level4_2 => 42,
1451            LevelIdc::Level5 => 50,
1452            LevelIdc::Level5_1 => 51,
1453            LevelIdc::Level5_2 => 52,
1454        }
1455    }
1456
1457    #[expect(clippy::as_conversions, reason = "u8 to u32 widening is lossless")]
1458    const fn pack_profile_level_id(profile_idc: u8, profile_iop: u8, level_idc: u8) -> u32 {
1459        ((profile_idc as u32) << 16) | ((profile_iop as u32) << 8) | level_idc as u32
1460    }
1461
1462    fn normalized_level_idc(profile_idc: u8, profile_iop: u8, level_idc: u8) -> Option<LevelIdc> {
1463        // reject the non-canonical level 1b form for baseline, main and extended
1464        // those profile families must use `level_idc=11` plus constraint_set3_flag
1465        if LEVEL_1B_IDCS.contains(&profile_idc) {
1466            if level_idc == LEVEL_1B_OTHER_IDC {
1467                return None;
1468            }
1469            if level_idc == LEVEL_1_1_IDC {
1470                return if (profile_iop & IOP_CONSTRAINT_SET3) != 0 {
1471                    Some(LevelIdc::Level1B)
1472                } else {
1473                    Some(LevelIdc::Level1_1)
1474                };
1475            }
1476        }
1477        LevelIdc::try_from(level_idc).ok()
1478    }
1479
1480    fn profile_from_bytes(profile_idc: u8, profile_iop: u8) -> Option<Profile> {
1481        PROFILE_PATTERNS.iter().copied().find_map(|pattern| {
1482            pattern
1483                .matches(profile_idc, profile_iop)
1484                .then_some(pattern.profile)
1485        })
1486    }
1487
1488    fn parse_profile_level_id_bytes(value: &[u8]) -> Option<[u8; 3]> {
1489        let [
1490            first_high,
1491            first_low,
1492            second_high,
1493            second_low,
1494            third_high,
1495            third_low,
1496        ] = value
1497        else {
1498            return None;
1499        };
1500        Some([
1501            decode_hex_byte(*first_high, *first_low)?,
1502            decode_hex_byte(*second_high, *second_low)?,
1503            decode_hex_byte(*third_high, *third_low)?,
1504        ])
1505    }
1506
1507    fn decode_hex_byte(high: u8, low: u8) -> Option<u8> {
1508        Some((decode_hex_nibble(high)? << 4) | decode_hex_nibble(low)?)
1509    }
1510
1511    fn decode_hex_nibble(value: u8) -> Option<u8> {
1512        match value {
1513            b'0'..=b'9' => Some(value - b'0'),
1514            b'a'..=b'f' => Some(value - b'a' + 10),
1515            b'A'..=b'F' => Some(value - b'A' + 10),
1516            _ => None,
1517        }
1518    }
1519}
1520
1521/// Returns `true` if `payload_type` is an RTP/AVP dynamic payload type.
1522///
1523/// Use this for the `PT` field from the RTP fixed header. It does not validate
1524/// whether a signaling layer actually negotiated that payload type.
1525///
1526/// Reference: RFC 3551 section 6.
1527#[must_use]
1528pub const fn is_dynamic_payload_type(payload_type: u8) -> bool {
1529    payload_type >= RTP_DYNAMIC_PAYLOAD_TYPE_START && payload_type <= RTP_DYNAMIC_PAYLOAD_TYPE_END
1530}
1531
1532/// Returns `true` if `payload_type` fits in the RTP fixed-header PT field.
1533///
1534/// Reference: RFC 3550 section 5.1.
1535#[must_use]
1536pub const fn is_payload_type(payload_type: u8) -> bool {
1537    payload_type <= RTP_PAYLOAD_TYPE_MAX
1538}
1539
1540/// Returns `true` if `payload_type` can be used with RTP/RTCP mux.
1541///
1542/// Reference: RFC 5761 section 4.
1543#[must_use]
1544pub const fn is_rtcp_mux_payload_type(payload_type: u8) -> bool {
1545    is_payload_type(payload_type)
1546        && (payload_type < RTP_RTCP_MUX_FORBIDDEN_PAYLOAD_TYPE_START
1547            || payload_type > RTP_RTCP_MUX_FORBIDDEN_PAYLOAD_TYPE_END)
1548}
1549
1550/// Returns whether `payload_type` can be assigned dynamically in an RTP/RTCP
1551/// muxed RTP/AVP session.
1552///
1553/// RFC 3551 reserves 96 through 127 for dynamic assignment and leaves several
1554/// lower ranges unassigned. RFC 5761 permits muxed RTP to use values below 64
1555/// while excluding 64 through 95 from RTP assignment.
1556///
1557/// References:
1558/// - <https://www.rfc-editor.org/rfc/rfc3551.html#section-6>
1559/// - <https://www.rfc-editor.org/rfc/rfc5761.html#section-4>
1560#[must_use]
1561pub const fn is_rtcp_mux_dynamic_payload_type(payload_type: u8) -> bool {
1562    is_dynamic_payload_type(payload_type)
1563        || matches!(payload_type, 20..=24 | 27 | 29..=30 | 35..=63)
1564}
1565
1566/// Classifies an RTP or RTCP candidate in an RTP/RTCP muxed datagram.
1567///
1568/// The packet must contain the first two header octets plus one body octet,
1569/// matching the minimum boundary used before complete RTP or RTCP parsing.
1570/// Both marker-bit values for payload types 64 through 95 select RTCP.
1571/// This candidate check does not validate complete datagram framing.
1572///
1573/// Reference: <https://www.rfc-editor.org/rfc/rfc5761.html#section-4>
1574#[must_use]
1575pub fn classify_rtp_rtcp_mux(packet: &[u8]) -> Option<RtpRtcpMuxPacketKind> {
1576    let [first, second, _, ..] = packet else {
1577        return None;
1578    };
1579    if first & RTP_VERSION_MASK != RTP_VERSION_HEADER_BITS {
1580        return None;
1581    }
1582    let payload_type = second & RTP_PAYLOAD_TYPE_MASK;
1583    if (RTP_RTCP_MUX_FORBIDDEN_PAYLOAD_TYPE_START..=RTP_RTCP_MUX_FORBIDDEN_PAYLOAD_TYPE_END)
1584        .contains(&payload_type)
1585    {
1586        Some(RtpRtcpMuxPacketKind::Rtcp)
1587    } else {
1588        Some(RtpRtcpMuxPacketKind::Rtp)
1589    }
1590}
1591
1592/// Parses the fixed RTP header of an RTP candidate in a muxed session.
1593///
1594/// The parser rejects RTCP candidates, non-RTP versions and packets truncated
1595/// within the fixed header or declared CSRC list. Codec payload and padding
1596/// validation belong to the payload parser.
1597///
1598/// References:
1599/// - <https://www.rfc-editor.org/rfc/rfc3550.html#section-5.1>
1600/// - <https://www.rfc-editor.org/rfc/rfc5761.html#section-4>
1601#[must_use]
1602pub fn parse_muxed_rtp_fixed_header(packet: &[u8]) -> Option<RtpFixedHeader> {
1603    if classify_rtp_rtcp_mux(packet) != Some(RtpRtcpMuxPacketKind::Rtp) {
1604        return None;
1605    }
1606    parse_rtp_fixed_header(packet)
1607}
1608
1609fn parse_rtp_fixed_header(packet: &[u8]) -> Option<RtpFixedHeader> {
1610    let first = *packet.first()?;
1611    let second = *packet.get(1)?;
1612    let header = RtpFixedHeader {
1613        payload_type: second & RTP_PAYLOAD_TYPE_MASK,
1614        sequence_number: read_u16(packet, RTP_SEQUENCE_NUMBER_OFFSET)?,
1615        timestamp: read_u32(packet, RTP_TIMESTAMP_OFFSET)?,
1616        ssrc: Ssrc::new(read_u32(packet, RTP_SSRC_OFFSET)?),
1617        marker: second & RTP_MARKER_MASK != 0,
1618        has_padding: first & RTP_PADDING_MASK != 0,
1619        has_extension: first & RTP_EXTENSION_MASK != 0,
1620        csrc_count: first & RTP_CSRC_COUNT_MASK,
1621    };
1622    packet.get(..header.extension_offset())?;
1623    Some(header)
1624}
1625
1626pub(crate) fn classify_datagram(packet: &[u8]) -> Option<RtpRtcpMuxPacketKind> {
1627    let first = *packet.first()?;
1628    if first & RTP_VERSION_MASK != RTP_VERSION_HEADER_BITS {
1629        return None;
1630    }
1631    let second = *packet.get(1)?;
1632    // Inspect the full octet here. The looser ingress candidate helper also
1633    // reserves unmarked payload types 64..=95 and has a different contract.
1634    let rtcp_start = RTP_MARKER_MASK | RTP_RTCP_MUX_FORBIDDEN_PAYLOAD_TYPE_START;
1635    let rtcp_end = RTP_MARKER_MASK | RTP_RTCP_MUX_FORBIDDEN_PAYLOAD_TYPE_END;
1636    if (rtcp_start..=rtcp_end).contains(&second) {
1637        let words = read_u16(packet, RTCP_LENGTH_OFFSET)?;
1638        let bytes = (usize::from(words) + 1) * mem::size_of::<u32>();
1639        // SRTCP encrypts after the sender SSRC and adds a trailer, so only
1640        // the initial RTCP packet can be sized without the security context.
1641        return (bytes >= RTCP_COMMON_HEADER_BYTES + RTCP_SSRC_BYTES && packet.len() >= bytes)
1642            .then_some(RtpRtcpMuxPacketKind::Rtcp);
1643    }
1644    let header = parse_rtp_fixed_header(packet)?;
1645    if header.has_extension() {
1646        header_extension::block(packet, header.extension_offset())?;
1647    }
1648    Some(RtpRtcpMuxPacketKind::Rtp)
1649}
1650
1651/// Expands one Generic NACK PID and bitmask into requested RTP sequence
1652/// numbers.
1653///
1654/// The PID is yielded first. Each set BLP bit yields PID + bit index + 1 with
1655/// 16-bit RTP sequence-number rollover.
1656///
1657/// Reference: <https://www.rfc-editor.org/rfc/rfc4585.html#section-6.2.1>
1658pub fn generic_nack_sequence_numbers(pid: u16, blp: u16) -> impl Iterator<Item = u16> {
1659    iter::once(pid).chain(
1660        (0_u16..GENERIC_NACK_BITMASK_BITS)
1661            .filter(move |bit| blp & (1_u16 << bit) != 0)
1662            .map(move |bit| pid.wrapping_add(bit + 1)),
1663    )
1664}
1665
1666/// Extracts the original RTP sequence number from an RTX payload.
1667///
1668/// Reference: <https://www.rfc-editor.org/rfc/rfc4588.html#section-4>
1669#[must_use]
1670pub fn rtx_original_sequence_number(payload: &[u8]) -> Option<u16> {
1671    read_u16(payload, 0)
1672}
1673
1674/// Builds an RTCP Receiver Report with no reception report blocks.
1675///
1676/// Reference: <https://www.rfc-editor.org/rfc/rfc3550.html#section-6.4.2>
1677#[must_use]
1678pub fn rtcp_receiver_report_without_report_blocks(
1679    sender_ssrc: Ssrc,
1680) -> [u8; RTCP_RECEIVER_REPORT_WITHOUT_BLOCKS_BYTES] {
1681    let [length_high, length_low] =
1682        RTCP_RECEIVER_REPORT_WITHOUT_BLOCKS_LENGTH_WORDS_MINUS_ONE.to_be_bytes();
1683    let [ssrc_0, ssrc_1, ssrc_2, ssrc_3] = sender_ssrc.value().to_be_bytes();
1684    [
1685        RTP_VERSION_HEADER_BITS,
1686        rtcp_packet_type::RR,
1687        length_high,
1688        length_low,
1689        ssrc_0,
1690        ssrc_1,
1691        ssrc_2,
1692        ssrc_3,
1693    ]
1694}
1695
1696fn read_u16(bytes: &[u8], offset: usize) -> Option<u16> {
1697    bytes
1698        .get(offset..offset.checked_add(mem::size_of::<u16>())?)?
1699        .try_into()
1700        .ok()
1701        .map(u16::from_be_bytes)
1702}
1703
1704fn read_u32(bytes: &[u8], offset: usize) -> Option<u32> {
1705    bytes
1706        .get(offset..offset.checked_add(mem::size_of::<u32>())?)?
1707        .try_into()
1708        .ok()
1709        .map(u32::from_be_bytes)
1710}
1711
1712/// rtcp common-header `PT` value namespace
1713///
1714/// reference: RFC 3550 section 12.1 and RFC 4585 section 6.1
1715pub mod rtcp_packet_type {
1716    /// sender report packet
1717    pub const SR: u8 = 200;
1718    /// receiver report packet
1719    pub const RR: u8 = 201;
1720    /// source description packet
1721    pub const SDES: u8 = 202;
1722    /// goodbye packet
1723    pub const BYE: u8 = 203;
1724    /// application-defined packet
1725    pub const APP: u8 = 204;
1726
1727    /// transport-layer feedback packet
1728    pub const RTPFB: u8 = 205;
1729    /// payload-specific feedback packet
1730    pub const PSFB: u8 = 206;
1731}
1732
1733/// rtcp SDES item `type` value namespace
1734///
1735/// reference: RFC 3550 section 12.2 and RFC 8852 section 4
1736pub mod rtcp_sdes_item {
1737    /// canonical end-point identifier
1738    pub const CNAME: u8 = 1;
1739    /// user name
1740    pub const NAME: u8 = 2;
1741    /// email address
1742    pub const EMAIL: u8 = 3;
1743    /// phone number
1744    pub const PHONE: u8 = 4;
1745    /// geographic location
1746    pub const LOC: u8 = 5;
1747    /// application or tool name
1748    pub const TOOL: u8 = 6;
1749    /// transient note
1750    pub const NOTE: u8 = 7;
1751    /// private extension item
1752    pub const PRIV: u8 = 8;
1753
1754    /// RTP stream identifier carried in an SDES packet
1755    pub const RTP_STREAM_ID: u8 = 12;
1756    /// RTP stream repaired by a redundancy stream
1757    pub const REPAIRED_RTP_STREAM_ID: u8 = 13;
1758}
1759
1760/// RTCP feedback FMT values.
1761pub mod rtcp_feedback_format {
1762    /// Generic NACK FMT value for RTPFB packets.
1763    ///
1764    /// Reference: RFC 4585 section 6.2.1.
1765    pub const RTPFB_GENERIC_NACK: u8 = 1;
1766
1767    /// Picture Loss Indication FMT value for PSFB packets.
1768    ///
1769    /// Reference: RFC 4585 section 6.3.1.
1770    pub const PSFB_PLI: u8 = 1;
1771
1772    /// Full Intra Request FMT value for PSFB packets.
1773    ///
1774    /// Reference: RFC 5104 section 4.3.1.
1775    pub const PSFB_FIR: u8 = 4;
1776
1777    /// Layer Refresh Request FMT value for PSFB packets.
1778    ///
1779    /// Reference: RFC 9627 section 8.
1780    pub const PSFB_LRR: u8 = 10;
1781}
1782
1783/// RTP header-extension profile IDs from RFC 8285.
1784///
1785/// RTP packets carry an extension block only when the fixed-header `X` bit is
1786/// set. The 16-bit profile ID then decides whether extension elements use the
1787/// one-byte or two-byte element header shape.
1788///
1789/// ```text
1790/// RTP extension block
1791///
1792/// +----------------+----------------+-----------------------------+
1793/// | profile ID     | length in u32  | extension elements          |
1794/// +----------------+----------------+-----------------------------+
1795/// | 16 bits        | 16 bits        | padded to 32-bit boundary   |
1796/// +----------------+----------------+-----------------------------+
1797///
1798/// One-byte element, profile 0xBEDE
1799///
1800/// +---------+---------+----------------------+
1801/// | ID      | len-1   | data                 |
1802/// +---------+---------+----------------------+
1803/// | 4 bits  | 4 bits  | 1 to 16 bytes        |
1804/// +---------+---------+----------------------+
1805///
1806/// Two-byte element, profile 0x1000 through 0x100F
1807///
1808/// +---------+---------+----------------------+
1809/// | ID      | len     | data                 |
1810/// +---------+---------+----------------------+
1811/// | 8 bits  | 8 bits  | 0 to 255 bytes       |
1812/// +---------+---------+----------------------+
1813/// ```
1814pub mod header_extension {
1815    const HEADER_BYTES: usize = 4;
1816    const WORD_BYTES: usize = 4;
1817    const ONE_BYTE_ID_SHIFT: u32 = 4;
1818    const ONE_BYTE_LENGTH_MASK: u8 = 0b0000_1111;
1819    const ONE_BYTE_LENGTH_OFFSET: usize = 1;
1820
1821    /// RFC 8285 one-byte header extension profile ID.
1822    pub const ONE_BYTE_PROFILE_ID: u16 = 0xBEDE;
1823
1824    /// Base value for the RFC 8285 two-byte header profile with appbits set to 0.
1825    pub const TWO_BYTE_PROFILE_ID_BASE: u16 = 0x1000;
1826
1827    /// Mask for the fixed 12-bit prefix (`0x100`) in the two-byte profile ID.
1828    pub const TWO_BYTE_PROFILE_PREFIX_MASK: u16 = 0xFFF0;
1829
1830    /// One-byte header extension identifier values.
1831    pub const ONE_BYTE_ID_PAD: u8 = 0;
1832    pub const ONE_BYTE_ID_MIN: u8 = 1;
1833    pub const ONE_BYTE_ID_MAX: u8 = 14;
1834    pub const ONE_BYTE_ID_RESERVED: u8 = 15;
1835
1836    /// One-byte header extension data size bounds from RFC 8285 section 4.2.
1837    pub const ONE_BYTE_DATA_LEN_MIN: u8 = 1;
1838    pub const ONE_BYTE_DATA_LEN_MAX: u8 = 16;
1839
1840    /// Two-byte header extension data size bounds from RFC 8285 section 4.3.
1841    pub const TWO_BYTE_DATA_LEN_MIN: u8 = 0;
1842    pub const TWO_BYTE_DATA_LEN_MAX: u8 = u8::MAX;
1843
1844    /// Returns whether `id` is usable as an RFC 8285 one-byte element ID.
1845    ///
1846    /// ID 0 is padding and ID 15 is reserved, so only 1 through 14 can identify
1847    /// negotiated extension values.
1848    #[must_use]
1849    pub const fn is_one_byte_id(id: u8) -> bool {
1850        id >= ONE_BYTE_ID_MIN && id <= ONE_BYTE_ID_MAX
1851    }
1852
1853    /// Builds an RFC 8285 two-byte profile ID from the 4-bit appbits value.
1854    ///
1855    /// Returns `None` when `appbits` cannot fit in the low nibble of the
1856    /// profile ID.
1857    #[must_use]
1858    pub fn two_byte_profile_id(appbits: u8) -> Option<u16> {
1859        if appbits > 0x0F {
1860            return None;
1861        }
1862        Some(TWO_BYTE_PROFILE_ID_BASE | u16::from(appbits))
1863    }
1864
1865    /// Finds an RFC 8285 one-byte extension element in a complete muxed RTP
1866    /// packet.
1867    ///
1868    /// Zero octets are padding. A nonzero element with ID 0 is malformed and
1869    /// ID 15 terminates processing, so neither can expose a later element.
1870    /// Packets without the one-byte extension profile return `None`.
1871    ///
1872    /// References:
1873    /// - <https://www.rfc-editor.org/rfc/rfc8285.html#section-4.1.2>
1874    /// - <https://www.rfc-editor.org/rfc/rfc8285.html#section-4.2>
1875    #[must_use]
1876    pub fn find_one_byte_element(packet: &[u8], target_id: u8) -> Option<&[u8]> {
1877        if !is_one_byte_id(target_id) {
1878            return None;
1879        }
1880        let header = super::parse_muxed_rtp_fixed_header(packet)?;
1881        if !header.has_extension() {
1882            return None;
1883        }
1884        let (profile, mut elements) = block(packet, header.extension_offset())?;
1885        if profile != ONE_BYTE_PROFILE_ID {
1886            return None;
1887        }
1888        while let Some((&element_header, rest)) = elements.split_first() {
1889            elements = rest;
1890            if element_header == ONE_BYTE_ID_PAD {
1891                continue;
1892            }
1893            let id = element_header >> ONE_BYTE_ID_SHIFT;
1894            if id == ONE_BYTE_ID_PAD || id == ONE_BYTE_ID_RESERVED {
1895                return None;
1896            }
1897            let length = usize::from(element_header & ONE_BYTE_LENGTH_MASK)
1898                .checked_add(ONE_BYTE_LENGTH_OFFSET)?;
1899            let value = elements.get(..length)?;
1900            elements = elements.get(length..)?;
1901            if id == target_id {
1902                return Some(value);
1903            }
1904        }
1905        None
1906    }
1907
1908    pub(super) fn block(packet: &[u8], offset: usize) -> Option<(u16, &[u8])> {
1909        let profile = super::read_u16(packet, offset)?;
1910        let word_count =
1911            super::read_u16(packet, offset.checked_add(super::mem::size_of::<u16>())?)?;
1912        let elements_offset = offset.checked_add(HEADER_BYTES)?;
1913        let elements_bytes = usize::from(word_count).checked_mul(WORD_BYTES)?;
1914        let elements = packet.get(elements_offset..elements_offset.checked_add(elements_bytes)?)?;
1915        Some((profile, elements))
1916    }
1917}
1918
1919/// Video Frame Marking RTP header-extension payload values.
1920///
1921/// Frame marking is carried as one negotiated RTP header extension
1922///
1923/// These helpers retain temporal-layer fields for future negotiated SVC
1924/// selection while current packet gates match simulcast RIDs
1925///
1926/// ```text
1927/// Short form, non-scalable stream
1928///
1929/// +---+---+---+---+---------------+
1930/// | S | E | I | D | reserved      |
1931/// +---+---+---+---+---------------+
1932///
1933/// Long form, scalable stream
1934///
1935/// +---+---+---+---+---+-----------+---------------+---------------+
1936/// | S | E | I | D | B | TID       | LID           | TL0PICIDX     |
1937/// +---+---+---+---+---+-----------+---------------+---------------+
1938/// | first octet                    | optional      | optional      |
1939/// +---+---+---+---+---+-----------+---------------+---------------+
1940/// ```
1941///
1942/// Reference: RFC 9626 section 3.
1943pub mod frame_marking {
1944    /// Full long-form frame-marking payload length.
1945    pub const LONG_DATA_LEN_WITH_TL0PICIDX: u8 = 3;
1946
1947    /// Long-form payload length when `TL0PICIDX` is omitted.
1948    pub const LONG_DATA_LEN_WITHOUT_TL0PICIDX: u8 = 2;
1949
1950    /// Long-form payload length when both `LID` and `TL0PICIDX` are omitted.
1951    pub const LONG_DATA_LEN_FLAGS_ONLY: u8 = 1;
1952
1953    /// Short-form non-scalable frame-marking payload length.
1954    pub const SHORT_DATA_LEN: u8 = 1;
1955
1956    /// Start-of-frame flag in the first frame-marking octet.
1957    pub const START_OF_FRAME_MASK: u8 = 0b1000_0000;
1958
1959    /// End-of-frame flag in the first frame-marking octet.
1960    pub const END_OF_FRAME_MASK: u8 = 0b0100_0000;
1961
1962    /// Independent-frame flag in the first frame-marking octet.
1963    pub const INDEPENDENT_FRAME_MASK: u8 = 0b0010_0000;
1964
1965    /// Discardable-frame flag in the first frame-marking octet.
1966    pub const DISCARDABLE_FRAME_MASK: u8 = 0b0001_0000;
1967
1968    /// Base-layer-sync flag in the long-form first octet.
1969    pub const BASE_LAYER_SYNC_MASK: u8 = 0b0000_1000;
1970
1971    /// Temporal-layer identifier bits in the long-form first octet.
1972    pub const TEMPORAL_LAYER_ID_MASK: u8 = 0b0000_0111;
1973
1974    /// Maximum temporal-layer identifier representable by the 3-bit TID field.
1975    pub const TEMPORAL_LAYER_ID_MAX: u8 = 7;
1976
1977    /// Base layer identifier used for TID and LID.
1978    pub const BASE_LAYER_ID: u8 = 0;
1979
1980    /// Extracts the temporal-layer ID from the first long-form frame-marking
1981    /// octet.
1982    ///
1983    /// Callers must only use this value as temporal metadata when signaling or
1984    /// negotiated extension state proves the packet carries frame marking.
1985    #[must_use]
1986    pub const fn temporal_layer_id(first_octet: u8) -> u8 {
1987        first_octet & TEMPORAL_LAYER_ID_MASK
1988    }
1989
1990    /// Returns whether `value` fits in the RFC 9626 three-bit temporal-layer
1991    /// field.
1992    #[must_use]
1993    pub const fn is_valid_temporal_layer_id(value: u8) -> bool {
1994        value <= TEMPORAL_LAYER_ID_MAX
1995    }
1996}
1997
1998#[cfg(test)]
1999#[path = "TESTS/rtp.rs"]
2000mod tests;