Skip to main content

o_sfu_rfc/
webrtc.rs

1//! RFC references for this module:
2//! - WebRTC RTP usage profile: <https://www.rfc-editor.org/rfc/rfc8834>
3//! - ICE protocol: <https://www.rfc-editor.org/rfc/rfc8445>
4//! - ICE candidate grammar (legacy, still interoperable in SDP): <https://www.rfc-editor.org/rfc/rfc5245>
5//! - DTLS-SRTP protection profiles: <https://www.rfc-editor.org/rfc/rfc5764>
6//! - BUNDLE and MID signaling: <https://www.rfc-editor.org/rfc/rfc9143>
7//! - RTP payload restrictions and RID signaling: <https://www.rfc-editor.org/rfc/rfc8851>
8//! - RTP stream ID header extensions: <https://www.rfc-editor.org/rfc/rfc8852>
9//! - SDP simulcast signaling: <https://www.rfc-editor.org/rfc/rfc8853>
10//! - RTCP multiplexing: <https://www.rfc-editor.org/rfc/rfc5761>
11//! - WebRTC datagram multiplexing: <https://www.rfc-editor.org/rfc/rfc7983>
12//! - RTCP feedback SDP signaling: <https://www.rfc-editor.org/rfc/rfc4585>
13//! - RTP retransmission SDP signaling: <https://www.rfc-editor.org/rfc/rfc4588>
14//! - SDP source attributes: <https://www.rfc-editor.org/rfc/rfc5576>
15//! - SDP grammar: <https://www.rfc-editor.org/rfc/rfc8866>
16//! - SDP offer/answer: <https://www.rfc-editor.org/rfc/rfc3264>
17//! - SDP `setup` roles for connection-oriented media: <https://www.rfc-editor.org/rfc/rfc4145>
18//! - DTLS-SRTP offer/answer usage of `setup`: <https://www.rfc-editor.org/rfc/rfc5763>
19//! - Video frame marking RTP header extension: <https://www.rfc-editor.org/rfc/rfc9626>
20//! - Layer Refresh Request feedback: <https://www.rfc-editor.org/rfc/rfc9627>
21
22use std::fmt;
23
24use crate::{dtls, rtp, stun};
25
26// First-octet ranges from RFC 7983 section 7:
27// <https://www.rfc-editor.org/rfc/rfc7983.html#section-7>
28/// Inclusive upper bound of the STUN first-octet range, which starts at zero.
29const STUN_MUX_FIRST_OCTET_END: u8 = 3;
30/// Inclusive lower bound of the multiplexed DTLS content-type range.
31const DTLS_MUX_FIRST_OCTET_START: u8 = 20;
32/// Inclusive upper bound of the multiplexed DTLS content-type range.
33const DTLS_MUX_FIRST_OCTET_END: u8 = 63;
34
35/// Protocol selected from a multiplexed WebRTC datagram's unencrypted headers.
36#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
37#[serde(rename_all = "lowercase")]
38pub enum DatagramKind {
39    Rtp,
40    Rtcp,
41    Stun,
42    Dtls,
43}
44
45/// Classifies STUN, DTLS 1.0/1.2, RTP/SRTP or RTCP/SRTCP by header shape.
46///
47/// Returns `None` for unsupported multiplexed protocols or truncated framing.
48/// STUN requires the RFC 8489 cookie and exact aligned message length. DTLS
49/// requires one complete initial record. RTP requires its fixed header, CSRC
50/// list and declared extension block. RTCP requires an initial packet header,
51/// sender SSRC and declared initial packet length, allowing compound packets
52/// and SRTCP trailers.
53///
54/// These shallow checks do not validate STUN attributes, subsequent DTLS/RTCP
55/// records, RTP payloads or padding. They do not authenticate or decrypt data
56/// and cannot distinguish protected packets from plaintext packets.
57///
58/// References:
59/// - <https://www.rfc-editor.org/rfc/rfc7983.html#section-7>
60/// - <https://www.rfc-editor.org/rfc/rfc8489.html#section-5>
61/// - <https://www.rfc-editor.org/rfc/rfc4347.html#section-4.1>
62/// - <https://www.rfc-editor.org/rfc/rfc6347.html#section-4.1>
63/// - <https://www.rfc-editor.org/rfc/rfc3550.html#section-5.1>
64/// - <https://www.rfc-editor.org/rfc/rfc3550.html#section-6.4.1>
65/// - <https://www.rfc-editor.org/rfc/rfc5761.html#section-4>
66/// - <https://www.rfc-editor.org/rfc/rfc3711.html#section-3.4>
67#[must_use]
68pub fn classify_datagram(packet: &[u8]) -> Option<DatagramKind> {
69    let first = *packet.first()?;
70    if first <= STUN_MUX_FIRST_OCTET_END {
71        return stun::has_datagram_shape(packet).then_some(DatagramKind::Stun);
72    }
73    if is_dtls_mux_packet(first) {
74        return dtls::has_datagram_shape(packet).then_some(DatagramKind::Dtls);
75    }
76    match rtp::classify_datagram(packet)? {
77        rtp::RtpRtcpMuxPacketKind::Rtp => Some(DatagramKind::Rtp),
78        rtp::RtpRtcpMuxPacketKind::Rtcp => Some(DatagramKind::Rtcp),
79    }
80}
81
82/// Returns whether a datagram first octet selects DTLS in WebRTC multiplexing.
83///
84/// Reference: <https://www.rfc-editor.org/rfc/rfc7983.html#section-7>
85#[must_use]
86pub const fn is_dtls_mux_packet(first_octet: u8) -> bool {
87    first_octet >= DTLS_MUX_FIRST_OCTET_START && first_octet <= DTLS_MUX_FIRST_OCTET_END
88}
89
90/// ICE portocol registries used by WebRTC signaling.
91pub mod ice {
92    /// Separator between the peer and sender username fragments in a
93    /// connectivity-check credential.
94    ///
95    /// Reference: <https://www.rfc-editor.org/rfc/rfc8445.html#section-7.2.2>
96    pub const USERNAME_FRAGMENT_SEPARATOR: char = ':';
97
98    /// ICE component IDs for RTP and RTCP.
99    ///
100    /// Reference: RFC 8445 section 5.1.1.
101    pub mod component {
102        pub const RTP: u16 = 1;
103        pub const RTCP: u16 = 2;
104    }
105
106    /// ICE candidate type literals used by SDP candidate attributes.
107    ///
108    /// References:
109    /// - RFC 5245 section 15.1 candidate grammar (`typ host|srflx|prflx|relay`)
110    /// - RFC 8445 (semantic model preserved by the updated ICE specification)
111    pub mod candidate_type {
112        pub const HOST: &str = "host";
113        pub const SERVER_REFLEXIVE: &str = "srflx";
114        pub const PEER_REFLEXIVE: &str = "prflx";
115        pub const RELAYED: &str = "relay";
116    }
117
118    /// ICE candidate attribute grammar tokens used by SDP candidate lines.
119    ///
120    /// Reference: RFC 5245 section 15.1.
121    pub mod candidate_attribute {
122        pub const PREFIX: &str = "candidate:";
123        pub const TYPE_LABEL: &str = "typ";
124    }
125
126    /// Recommended ICE type-preference values.
127    ///
128    /// Reference: RFC 8445 section 5.1.2.2.
129    pub mod type_preference {
130        pub const HOST: u8 = 126;
131        pub const PEER_REFLEXIVE: u8 = 110;
132        pub const SERVER_REFLEXIVE: u8 = 100;
133        pub const RELAYED: u8 = 0;
134    }
135
136    /// ICE transport token used in SDP candidate lines.
137    ///
138    /// Reference: RFC 8445 section 5.1.1 and candidate grammar inherited from RFC 5245.
139    pub mod transport {
140        pub const UDP: &str = "udp";
141        pub const TCP: &str = "tcp";
142    }
143}
144
145/// ICE transport tokens used in SDP candidate lines.
146#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
147pub enum IceTransport {
148    Udp,
149    Tcp,
150}
151
152impl IceTransport {
153    #[must_use]
154    pub const fn as_str(self) -> &'static str {
155        match self {
156            Self::Udp => ice::transport::UDP,
157            Self::Tcp => ice::transport::TCP,
158        }
159    }
160
161    #[must_use]
162    pub fn parse(token: &str) -> Option<Self> {
163        if token.eq_ignore_ascii_case(ice::transport::UDP) {
164            return Some(Self::Udp);
165        }
166        if token.eq_ignore_ascii_case(ice::transport::TCP) {
167            return Some(Self::Tcp);
168        }
169        None
170    }
171}
172
173impl AsRef<str> for IceTransport {
174    fn as_ref(&self) -> &str {
175        match self {
176            Self::Udp => ice::transport::UDP,
177            Self::Tcp => ice::transport::TCP,
178        }
179    }
180}
181
182impl fmt::Display for IceTransport {
183    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
184        f.write_str(self.as_ref())
185    }
186}
187
188/// ICE candidate type tokens used in SDP candidate attributes.
189#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
190pub enum IceCandidateType {
191    Host,
192    ServerReflexive,
193    PeerReflexive,
194    Relayed,
195}
196
197impl IceCandidateType {
198    #[must_use]
199    pub const fn as_str(self) -> &'static str {
200        match self {
201            Self::Host => ice::candidate_type::HOST,
202            Self::ServerReflexive => ice::candidate_type::SERVER_REFLEXIVE,
203            Self::PeerReflexive => ice::candidate_type::PEER_REFLEXIVE,
204            Self::Relayed => ice::candidate_type::RELAYED,
205        }
206    }
207
208    #[must_use]
209    pub fn parse(token: &str) -> Option<Self> {
210        match token {
211            ice::candidate_type::HOST => Some(Self::Host),
212            ice::candidate_type::SERVER_REFLEXIVE => Some(Self::ServerReflexive),
213            ice::candidate_type::PEER_REFLEXIVE => Some(Self::PeerReflexive),
214            ice::candidate_type::RELAYED => Some(Self::Relayed),
215            _ => None,
216        }
217    }
218}
219
220impl AsRef<str> for IceCandidateType {
221    fn as_ref(&self) -> &str {
222        match self {
223            Self::Host => ice::candidate_type::HOST,
224            Self::ServerReflexive => ice::candidate_type::SERVER_REFLEXIVE,
225            Self::PeerReflexive => ice::candidate_type::PEER_REFLEXIVE,
226            Self::Relayed => ice::candidate_type::RELAYED,
227        }
228    }
229}
230
231impl fmt::Display for IceCandidateType {
232    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
233        f.write_str(self.as_ref())
234    }
235}
236
237/// MIME top-level media kinds used by ORTC and SDP payloads
238/// same as on web stream/tracks APIs.
239pub mod media_kind {
240    pub const AUDIO: &str = "audio";
241    pub const VIDEO: &str = "video";
242    pub const APPLICATION: &str = "application";
243}
244
245/// Technical media kind shared by RTP, SDP, and signaling metadata.
246#[derive(
247    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize,
248)]
249#[serde(rename_all = "lowercase")]
250pub enum MediaKind {
251    Audio,
252    Video,
253}
254
255impl MediaKind {
256    #[must_use]
257    pub const fn as_str(self) -> &'static str {
258        match self {
259            Self::Audio => media_kind::AUDIO,
260            Self::Video => media_kind::VIDEO,
261        }
262    }
263
264    #[must_use]
265    pub const fn is_audio(self) -> bool {
266        matches!(self, Self::Audio)
267    }
268
269    #[must_use]
270    pub const fn is_video(self) -> bool {
271        matches!(self, Self::Video)
272    }
273}
274
275impl AsRef<str> for MediaKind {
276    fn as_ref(&self) -> &str {
277        self.as_str()
278    }
279}
280
281impl fmt::Display for MediaKind {
282    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
283        f.write_str(self.as_str())
284    }
285}
286
287/// RTCP feedback type and parameter tokens used by current WebRTC capability paylods.
288pub mod rtcp_feedback {
289    /// RTCP feedback kind tokens used in capability dictionnaries.
290    pub mod kind {
291        /// Generic NACK feedback type token.
292        ///
293        /// Reference: RFC 4585 section 6.2.1.
294        pub const NACK: &str = "nack";
295
296        /// Codec control message feedback type token.
297        ///
298        /// Reference: RFC 5104.
299        pub const CCM: &str = "ccm";
300
301        /// Google Receiver Estimated Maximum Bitrate token used by current browser stacks.
302        pub const GOOG_REMB: &str = "goog-remb";
303
304        /// Transport-wide congestion control feedback token.
305        ///
306        /// Reference:
307        /// <https://www.ietf.org/archive/id/draft-holmer-rmcat-transport-wide-cc-extensions-01.txt>
308        pub const TRANSPORT_CC: &str = "transport-cc";
309    }
310
311    /// RTCP feedback parameter tokens used by current WebRTC cpaability payloads.
312    pub mod parameter {
313        /// Picture loss indication parameter token.
314        ///
315        /// Reference: RFC 4585 section 6.3.1.
316        pub const PLI: &str = "pli";
317
318        /// Full intra request parameter token.
319        ///
320        /// Reference: RFC 5104 section 4.3.1.
321        pub const FIR: &str = "fir";
322
323        /// Layer Refresh Request parameter token.
324        ///
325        /// Reference: RFC 9627 section 6.
326        pub const LRR: &str = "lrr";
327    }
328}
329
330pub mod sdp {
331    /// Carriage-return line-feed SDP line ending.
332    ///
333    /// Reference: <https://www.rfc-editor.org/rfc/rfc8866.html#section-5>
334    pub const CRLF: &str = "\r\n";
335
336    /// Carriage-return octet stripped by line-oriented SDP parsers.
337    ///
338    /// Reference: <https://www.rfc-editor.org/rfc/rfc8866.html#section-5>
339    pub const CR: char = '\r';
340
341    /// Line-feed octet used to split SDP text while preserving line endings.
342    ///
343    /// Reference: <https://www.rfc-editor.org/rfc/rfc8866.html#section-5>
344    pub const LF: char = '\n';
345
346    /// ASCII space separating fields within an SDP value.
347    ///
348    /// Reference: <https://www.rfc-editor.org/rfc/rfc8866.html#section-5>
349    pub const SP: char = ' ';
350
351    /// Attribute field prefix.
352    ///
353    /// Reference: <https://www.rfc-editor.org/rfc/rfc8866.html#section-5.13>
354    pub const ATTR: &str = "a=";
355
356    /// Separator between an SDP attribute name and value.
357    ///
358    /// Reference: <https://www.rfc-editor.org/rfc/rfc8866.html#section-5.13>
359    pub const ATTR_SEP: char = ':';
360
361    /// Session-level end-of-candidates line.
362    ///
363    /// Reference: <https://www.rfc-editor.org/rfc/rfc8840.html#section-8>
364    pub const EOC_LINE: &str = "a=end-of-candidates\r\n";
365    /// Media description field prefix.
366    ///
367    /// Reference: <https://www.rfc-editor.org/rfc/rfc8866.html#section-5.14>
368    pub const MEDIA: &str = "m=";
369
370    /// `a=extmap` grammar tokens.
371    pub mod extmap {
372        /// Separator between an extension ID and direction.
373        ///
374        /// Reference: <https://www.rfc-editor.org/rfc/rfc8285.html#section-5>
375        pub const DIR_SEP: char = '/';
376    }
377
378    /// `a=rtpmap` grammar tokens.
379    pub mod rtpmap {
380        /// Separator between encoding name, clock rate and encoding parameters.
381        ///
382        /// Reference: <https://www.rfc-editor.org/rfc/rfc8866.html#section-6.6>
383        pub const ENC_SEP: char = '/';
384    }
385
386    pub mod group_semantics {
387        /// `a=group:BUNDLE ...`
388        ///
389        /// Reference: RFC 9143.
390        pub const BUNDLE: &str = "BUNDLE";
391    }
392
393    pub mod ssrc_group_semantics {
394        /// Flow Identification semantics for `a=ssrc-group`.
395        ///
396        /// Reference: <https://www.rfc-editor.org/rfc/rfc5576.html#section-4.2>
397        pub const FID: &str = "FID";
398    }
399
400    pub mod attribute {
401        /// `a=extmap:<id> <uri>`
402        ///
403        /// Reference: RFC 8285 section 5.
404        pub const EXTMAP: &str = "extmap";
405
406        /// `a=fmtp:<format> <format-specific-parameters>`
407        ///
408        /// Reference: <https://www.rfc-editor.org/rfc/rfc8866.html#section-6.15>
409        pub const FMTP: &str = "fmtp";
410
411        /// `a=rtcp-fb:<pt> <feedback-type> [<feedback-parameter>]`
412        ///
413        /// Reference: <https://www.rfc-editor.org/rfc/rfc4585.html#section-4.2>
414        pub const RTCP_FB: &str = "rtcp-fb";
415
416        /// `a=rtcp-mux`
417        ///
418        /// Reference: RFC 5761.
419        pub const RTCP_MUX: &str = "rtcp-mux";
420
421        /// `a=rtpmap:<payload-type> <encoding-name>/<clock-rate>`
422        ///
423        /// Reference: <https://www.rfc-editor.org/rfc/rfc8866.html#section-6.6>
424        pub const RTPMAP: &str = "rtpmap";
425
426        /// `a=rid:<rid-id> <direction> ...`
427        ///
428        /// Reference: RFC 8851 section 4.
429        pub const RID: &str = "rid";
430
431        /// `a=simulcast:<send-or-recv-list> ...`
432        ///
433        /// Reference: RFC 8853 section 5.1.
434        pub const SIMULCAST: &str = "simulcast";
435
436        /// `a=ssrc-group:<semantics> <ssrc-id> ...`
437        ///
438        /// Reference: <https://www.rfc-editor.org/rfc/rfc5576.html#section-4.2>
439        pub const SSRC_GROUP: &str = "ssrc-group";
440
441        /// `a=ssrc:<ssrc-id> <attribute>`
442        ///
443        /// Reference: <https://www.rfc-editor.org/rfc/rfc5576.html#section-4.1>
444        pub const SSRC: &str = "ssrc";
445
446        /// `a=setup:<role>`
447        ///
448        /// References: RFC 4145, RFC 5763.
449        pub const SETUP: &str = "setup";
450
451        /// `a=mid:<mid>`
452        ///
453        /// Reference: RFC 9143 section 9.
454        pub const MID: &str = "mid";
455    }
456
457    /// `a=rid` directions and validation helpers.
458    pub mod rid {
459        pub const DIRECTION_SEND: &str = "send";
460        pub const DIRECTION_RECV: &str = "recv";
461        pub const MAX_ID_OCTETS: usize = 255;
462
463        /// Returns whether `value` is a valid RTP stream identifier.
464        ///
465        /// RFC 8852 section 3 constrains `RtpStreamId` and
466        /// `RepairedRtpStreamId` to 1-255 ASCII alphanumeric octets. RFC
467        /// Editor errata 7132 applies the same bound to RFC 8851 `rid-id`.
468        #[must_use]
469        pub fn is_id(value: &str) -> bool {
470            (1..=MAX_ID_OCTETS).contains(&value.len())
471                && value.as_bytes().iter().all(|byte| is_id_byte(*byte))
472        }
473
474        #[must_use]
475        pub const fn is_id_byte(value: u8) -> bool {
476            matches!(value, b'0'..=b'9' | b'A'..=b'Z' | b'a'..=b'z')
477        }
478    }
479
480    /// `a=rid` restriction parameter names.
481    ///
482    /// Reference: RFC 8851 section 12.2.
483    pub mod rid_restriction {
484        /// Separator between RID restrictions.
485        ///
486        /// Reference: <https://www.rfc-editor.org/rfc/rfc8851.html#section-4>
487        pub const PARAMETER_SEPARATOR: char = ';';
488
489        /// Separator between a RID restriction name and value.
490        ///
491        /// Reference: <https://www.rfc-editor.org/rfc/rfc8851.html#section-4>
492        pub const NAME_VALUE_SEPARATOR: char = '=';
493
494        pub const PAYLOAD_TYPES: &str = "pt";
495        pub const MAX_WIDTH: &str = "max-width";
496        pub const MAX_HEIGHT: &str = "max-height";
497        pub const MAX_FPS: &str = "max-fps";
498        pub const MAX_FRAME_SIZE: &str = "max-fs";
499        pub const MAX_BITRATE: &str = "max-br";
500        pub const MAX_PIXEL_RATE: &str = "max-pps";
501        pub const MAX_BITS_PER_PIXEL: &str = "max-bpp";
502        pub const DEPENDS_ON: &str = "depend";
503    }
504
505    /// `a=simulcast` list delimiters and prefixes.
506    ///
507    /// Reference: RFC 8853 section 5.1.
508    pub mod simulcast {
509        pub const DIRECTION_SEND: &str = super::rid::DIRECTION_SEND;
510        pub const DIRECTION_RECV: &str = super::rid::DIRECTION_RECV;
511        pub const STREAM_SEPARATOR: char = ';';
512        pub const ALTERNATIVE_SEPARATOR: char = ',';
513        pub const INITIAL_PAUSE_PREFIX: char = '~';
514
515        #[must_use]
516        pub fn strip_initial_pause_prefix(value: &str) -> Option<&str> {
517            value.strip_prefix(INITIAL_PAUSE_PREFIX)
518        }
519    }
520
521    pub mod transport_protocol {
522        /// `m=<media> <port> UDP/TLS/RTP/SAVPF ...`
523        ///
524        /// Reference: RFC 8829 section 5.8.
525        pub const UDP_TLS_RTP_SAVPF: &str = "UDP/TLS/RTP/SAVPF";
526
527        /// `m=<media> <port> UDP/TLS/RTP/SAVP ...`
528        ///
529        /// Reference: RFC 8829 section 5.8.
530        pub const UDP_TLS_RTP_SAVP: &str = "UDP/TLS/RTP/SAVP";
531
532        /// `m=<media> <port> RTP/SAVPF ...`
533        ///
534        /// Reference: RFC 8829 section 5.8.
535        pub const RTP_SAVPF: &str = "RTP/SAVPF";
536
537        /// `m=<media> <port> RTP/SAVP ...`
538        ///
539        /// Reference: RFC 8829 section 5.8.
540        pub const RTP_SAVP: &str = "RTP/SAVP";
541
542        /// `m=<media> <port> UDP/DTLS/SCTP ...`
543        ///
544        /// Reference: RFC 8841.
545        pub const UDP_DTLS_SCTP: &str = "UDP/DTLS/SCTP";
546
547        /// `m=<media> <port> TCP/DTLS/SCTP ...`
548        ///
549        /// Reference: RFC 8841.
550        pub const TCP_DTLS_SCTP: &str = "TCP/DTLS/SCTP";
551    }
552
553    pub mod setup_role {
554        pub const ACTIVE: &str = "active";
555        pub const PASSIVE: &str = "passive";
556        pub const ACTPASS: &str = "actpass";
557        pub const HOLDCONN: &str = "holdconn";
558    }
559
560    pub mod direction {
561        /// `a=inactive`
562        ///
563        /// Reference: <https://www.rfc-editor.org/rfc/rfc8866.html#section-6.7.4>
564        pub const INACTIVE: &str = "inactive";
565
566        /// `a=recvonly`
567        ///
568        /// Reference: <https://www.rfc-editor.org/rfc/rfc8866.html#section-6.7.1>
569        pub const RECV_ONLY: &str = "recvonly";
570
571        /// `a=sendrecv`
572        ///
573        /// Reference: <https://www.rfc-editor.org/rfc/rfc8866.html#section-6.7.2>
574        pub const SEND_RECV: &str = "sendrecv";
575
576        /// `a=sendonly`
577        ///
578        /// Reference: <https://www.rfc-editor.org/rfc/rfc8866.html#section-6.7.3>
579        pub const SEND_ONLY: &str = "sendonly";
580    }
581}
582
583/// Direction tokens used by RFC 8851 RID and RFC 8853 simulcast attributes.
584///
585/// Parsing uses the case-sensitive RFC tokens.
586#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
587pub enum RtpStreamDirection {
588    Send,
589    Recv,
590}
591
592impl RtpStreamDirection {
593    #[must_use]
594    pub const fn as_str(self) -> &'static str {
595        match self {
596            Self::Send => sdp::rid::DIRECTION_SEND,
597            Self::Recv => sdp::rid::DIRECTION_RECV,
598        }
599    }
600
601    #[must_use]
602    pub fn parse(token: &str) -> Option<Self> {
603        match token {
604            sdp::rid::DIRECTION_SEND => Some(Self::Send),
605            sdp::rid::DIRECTION_RECV => Some(Self::Recv),
606            _ => None,
607        }
608    }
609}
610
611impl AsRef<str> for RtpStreamDirection {
612    fn as_ref(&self) -> &str {
613        match self {
614            Self::Send => sdp::rid::DIRECTION_SEND,
615            Self::Recv => sdp::rid::DIRECTION_RECV,
616        }
617    }
618}
619
620impl fmt::Display for RtpStreamDirection {
621    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
622        f.write_str(self.as_ref())
623    }
624}
625
626/// DTLS fingerprint algorithms currently supported by the runtime.
627#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
628pub enum DtlsFingerprintAlgorithm {
629    Sha256,
630}
631
632impl DtlsFingerprintAlgorithm {
633    #[must_use]
634    pub const fn as_str(self) -> &'static str {
635        match self {
636            Self::Sha256 => "sha-256",
637        }
638    }
639
640    #[must_use]
641    pub fn parse(token: &str) -> Option<Self> {
642        if token.eq_ignore_ascii_case("sha-256") {
643            return Some(Self::Sha256);
644        }
645        None
646    }
647}
648
649impl AsRef<str> for DtlsFingerprintAlgorithm {
650    fn as_ref(&self) -> &str {
651        match self {
652            Self::Sha256 => "sha-256",
653        }
654    }
655}
656
657impl fmt::Display for DtlsFingerprintAlgorithm {
658    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
659        f.write_str(self.as_ref())
660    }
661}
662
663/// RTP header-extension URIs commonly needed by WebRTC endpoints.
664pub mod rtp_header_extension_uri {
665    macro_rules! rtp_header_extension_urn {
666        ($suffix:literal) => {
667            concat!("urn:ietf:params:rtp-hdrext:", $suffix)
668        };
669    }
670
671    macro_rules! rtp_header_extension_sdes_urn {
672        ($suffix:literal) => {
673            concat!("urn:ietf:params:rtp-hdrext:sdes:", $suffix)
674        };
675    }
676
677    /// MID RTP header extension URI.
678    ///
679    /// Reference: RFC 9143 section 16.4.
680    pub const MID: &str = rtp_header_extension_sdes_urn!("mid");
681
682    /// Audio level RTP header extension URI.
683    ///
684    /// Reference: RFC 6464 section 3.
685    pub const SSRC_AUDIO_LEVEL: &str = rtp_header_extension_urn!("ssrc-audio-level");
686
687    /// Mixer-to-client audio level RTP header extension URI.
688    ///
689    /// Reference: RFC 6465 section 4.
690    pub const CSRC_AUDIO_LEVEL: &str = rtp_header_extension_urn!("csrc-audio-level");
691
692    /// RTP stream ID extension URI.
693    ///
694    /// Reference: RFC 8852.
695    pub const RTP_STREAM_ID: &str = rtp_header_extension_sdes_urn!("rtp-stream-id");
696
697    /// Repaired RTP stream ID extension URI.
698    ///
699    /// Reference: RFC 8852.
700    pub const REPAIRED_RTP_STREAM_ID: &str =
701        rtp_header_extension_sdes_urn!("repaired-rtp-stream-id");
702
703    /// Video Frame Marking RTP header extension URI.
704    ///
705    /// Reference: RFC 9626 section 3.4.
706    pub const FRAME_MARKING: &str = rtp_header_extension_urn!("framemarking");
707
708    /// Absolute send time RTP header extension URI.
709    ///
710    /// The RTP header-extension framework identify extensions by URI string,
711    /// and that URI is signaled verbatim in SDP `a=extmap` lines. Even though
712    /// this identifier looks like an HTTP URL, it just is a protocol name.
713    ///
714    /// Current WebRTC stacks use this exact literal, so we preserve it for interoperability.
715    ///
716    /// Reference: <https://www.webrtc.org/experiments/rtp-hdrext/abs-send-time>
717    pub const ABS_SEND_TIME: &str = "http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time";
718
719    /// Transport-wide sequence number RTP header extension URI.
720    ///
721    /// This value is likewise the negotiated wire identifier carried in SDP
722    /// `a=extmap` lines. It is not dereferenced as a network resource; the
723    /// exact string itself is the interoperability key used to match the
724    /// extension.
725    ///
726    /// Browsers and other rtc ecosystems commonly advertise the
727    /// historical `...-01` draft URI literal, so we keeps that deployed
728    /// identifier instead of normalizing it to a different name.
729    ///
730    /// Reference:
731    /// <https://www.ietf.org/archive/id/draft-holmer-rmcat-transport-wide-cc-extensions-01.txt>
732    pub const TRANSPORT_WIDE_CC_DRAFT_01: &str =
733        "http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01";
734}
735
736/// RTP header-extension URIs commonly needed by WebRTC endpoints.
737#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
738pub enum RtpHeaderExtensionUri {
739    Mid,
740    RtpStreamId,
741    RepairedRtpStreamId,
742    FrameMarking,
743    AbsSendTime,
744    TransportWideCcDraft01,
745    SsrcAudioLevel,
746    CsrcAudioLevel,
747    Other(String),
748}
749
750impl RtpHeaderExtensionUri {
751    #[must_use]
752    pub fn as_str(&self) -> &str {
753        match self {
754            Self::Mid => rtp_header_extension_uri::MID,
755            Self::RtpStreamId => rtp_header_extension_uri::RTP_STREAM_ID,
756            Self::RepairedRtpStreamId => rtp_header_extension_uri::REPAIRED_RTP_STREAM_ID,
757            Self::FrameMarking => rtp_header_extension_uri::FRAME_MARKING,
758            Self::AbsSendTime => rtp_header_extension_uri::ABS_SEND_TIME,
759            Self::TransportWideCcDraft01 => rtp_header_extension_uri::TRANSPORT_WIDE_CC_DRAFT_01,
760            Self::SsrcAudioLevel => rtp_header_extension_uri::SSRC_AUDIO_LEVEL,
761            Self::CsrcAudioLevel => rtp_header_extension_uri::CSRC_AUDIO_LEVEL,
762            Self::Other(uri) => uri.as_str(),
763        }
764    }
765}
766
767impl From<&str> for RtpHeaderExtensionUri {
768    fn from(value: &str) -> Self {
769        match value {
770            rtp_header_extension_uri::MID => Self::Mid,
771            rtp_header_extension_uri::RTP_STREAM_ID => Self::RtpStreamId,
772            rtp_header_extension_uri::REPAIRED_RTP_STREAM_ID => Self::RepairedRtpStreamId,
773            rtp_header_extension_uri::FRAME_MARKING => Self::FrameMarking,
774            rtp_header_extension_uri::ABS_SEND_TIME => Self::AbsSendTime,
775            rtp_header_extension_uri::TRANSPORT_WIDE_CC_DRAFT_01 => Self::TransportWideCcDraft01,
776            rtp_header_extension_uri::SSRC_AUDIO_LEVEL => Self::SsrcAudioLevel,
777            rtp_header_extension_uri::CSRC_AUDIO_LEVEL => Self::CsrcAudioLevel,
778            _ => Self::Other(value.to_owned()),
779        }
780    }
781}
782
783impl From<String> for RtpHeaderExtensionUri {
784    fn from(value: String) -> Self {
785        Self::from(value.as_str())
786    }
787}
788
789impl AsRef<str> for RtpHeaderExtensionUri {
790    fn as_ref(&self) -> &str {
791        self.as_str()
792    }
793}
794
795impl fmt::Display for RtpHeaderExtensionUri {
796    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
797        f.write_str(self.as_str())
798    }
799}
800
801/// RTCP SDES item type defined for MID.
802///
803/// Reference: RFC 9143 section 16.3.
804pub const RTCP_SDES_ITEM_MID: u8 = 15;
805
806#[cfg(test)]
807#[path = "TESTS/webrtc.rs"]
808mod tests;