Skip to main content

rtci/rtp_transceiver/rtp_sender/
rtp_codec.rs

1use crate::peer_connection::configuration::UNSPECIFIED_STR;
2use crate::peer_connection::configuration::media_engine::*;
3use crate::rtp_transceiver::rtp_sender::rtcp_parameters::{
4    RTCP_FB_ACK_CCFB, RTCP_FB_NACK_ECN, RTCPFeedback, TYPE_RTCP_FB_ACK, TYPE_RTCP_FB_CCM,
5    TYPE_RTCP_FB_NACK, TYPE_RTCP_FB_TRANSPORT_CC,
6};
7use crate::rtp_transceiver::rtp_sender::rtp_codec_parameters::RTCRtpCodecParameters;
8use crate::rtp_transceiver::rtp_sender::rtp_encoding_parameters::RTCRtpEncodingParameters;
9use crate::rtp_transceiver::{PayloadType, fmtp};
10use serde::{Deserialize, Serialize};
11use shared::error::{Error, Result};
12use std::fmt;
13
14/// Codec kind identifying the media type.
15#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
16#[non_exhaustive]
17pub enum RtpCodecKind {
18    /// Unspecified or unknown codec type
19    #[default]
20    Unspecified = 0,
21
22    /// Audio codec
23    #[serde(rename = "audio")]
24    Audio = 1,
25
26    /// Video codec
27    #[serde(rename = "video")]
28    Video = 2,
29
30    /// Non-audio/video RTP-carried application data
31    #[serde(rename = "application")]
32    Application = 3,
33}
34
35impl From<&str> for RtpCodecKind {
36    fn from(raw: &str) -> Self {
37        match raw {
38            "audio" => RtpCodecKind::Audio,
39            "video" => RtpCodecKind::Video,
40            "application" => RtpCodecKind::Application,
41            _ => RtpCodecKind::Unspecified,
42        }
43    }
44}
45
46impl From<u8> for RtpCodecKind {
47    fn from(v: u8) -> Self {
48        match v {
49            1 => RtpCodecKind::Audio,
50            2 => RtpCodecKind::Video,
51            3 => RtpCodecKind::Application,
52            _ => RtpCodecKind::Unspecified,
53        }
54    }
55}
56
57impl fmt::Display for RtpCodecKind {
58    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59        let s = match *self {
60            RtpCodecKind::Audio => "audio",
61            RtpCodecKind::Video => "video",
62            RtpCodecKind::Application => "application",
63            RtpCodecKind::Unspecified => UNSPECIFIED_STR,
64        };
65        write!(f, "{s}")
66    }
67}
68
69/// RTP codec capability providing information about supported codecs.
70///
71/// ## Specifications
72///
73/// * [W3C](https://www.w3.org/TR/webrtc/#dictionary-rtcrtpcodec-members)
74#[derive(Default, Debug, Clone, PartialEq, Eq)]
75pub struct RTCRtpCodec {
76    /// MIME type of the codec (e.g., "video/VP8", "audio/opus")
77    pub mime_type: String,
78    /// Codec clock rate in Hz
79    pub clock_rate: u32,
80    /// Number of audio channels (0 for video codecs)
81    pub channels: u16,
82    /// Format-specific parameters as SDP fmtp line
83    pub sdp_fmtp_line: String,
84    /// RTCP feedback mechanisms supported by this codec (deprecated, will be removed)
85    pub rtcp_feedback: Vec<RTCPFeedback>, //TODO: to be removed
86}
87
88impl RTCRtpCodec {
89    /// Creates an RTP payloader for this codec.
90    ///
91    /// Returns a boxed trait object implementing the Payloader interface
92    /// for packetizing media frames into RTP packets.
93    ///
94    /// # Errors
95    ///
96    /// Returns `Error::ErrNoPayloaderForCodec` if the codec is not supported.
97    pub fn payloader(&self) -> Result<Box<dyn rtp::packetizer::Payloader>> {
98        let mime_type = self.mime_type.to_lowercase();
99        if mime_type == MIME_TYPE_H264.to_lowercase() {
100            // RFC 6184 6.2: the negotiated packetization mode decides whether STAP-A and FU-A
101            // may be sent at all; an absent parameter means mode 0, mode 2 is interleaved
102            // (section 6.4), and a value above 2 is no mode (section 8.1).
103            Ok(Box::new(
104                rtp::codec::h264::H264Payloader::try_with_packetization_mode(
105                    h264_packetization_mode(&self.sdp_fmtp_line),
106                )?,
107            ))
108        } else if mime_type == MIME_TYPE_HEVC.to_lowercase() {
109            Ok(Box::<rtp::codec::h265::HevcPayloader>::default())
110        } else if mime_type == MIME_TYPE_VP8.to_lowercase() {
111            let mut vp8_payloader = rtp::codec::vp8::Vp8Payloader::default();
112            vp8_payloader.enable_picture_id = true;
113            Ok(Box::new(vp8_payloader))
114        } else if mime_type == MIME_TYPE_VP9.to_lowercase() {
115            Ok(Box::<rtp::codec::vp9::Vp9Payloader>::default())
116        } else if mime_type == MIME_TYPE_OPUS.to_lowercase() {
117            Ok(Box::<rtp::codec::opus::OpusPayloader>::default())
118        } else if mime_type == MIME_TYPE_G722.to_lowercase()
119            || mime_type == MIME_TYPE_PCMU.to_lowercase()
120            || mime_type == MIME_TYPE_PCMA.to_lowercase()
121            || mime_type == MIME_TYPE_TELEPHONE_EVENT.to_lowercase()
122        {
123            Ok(Box::<rtp::codec::g7xx::G7xxPayloader>::default())
124        } else if mime_type == MIME_TYPE_CN.to_lowercase() {
125            Ok(Box::<rtp::codec::comfort_noise::ComfortNoisePayloader>::default())
126        } else if mime_type == MIME_TYPE_AV1.to_lowercase() {
127            Ok(Box::<rtp::codec::av1::Av1Payloader>::default())
128        } else if mime_type == MIME_TYPE_SMPTE336M.to_lowercase() {
129            Ok(Box::<rtp::codec::smpte336m::Smpte336mPayloader>::default())
130        } else {
131            Err(Error::ErrNoPayloaderForCodec)
132        }
133    }
134
135    /// Creates an H.264 depacketizer for a stream received with this codec, configured from
136    /// the sender's stream properties in its fmtp line: with `packetization-mode=2` NAL units
137    /// leave in decoding order through a de-interleaving buffer sized by
138    /// `sprop-interleaving-depth` and `sprop-max-don-diff` (RFC 6184 sections 7.2.2, 8.1),
139    /// whose initial buffering also ends after `sprop-init-buf-time` when the packets are
140    /// given with their arrival time (`H264Packet::depacketize_at`,
141    /// `H264Packet::is_initial_buffering`).
142    ///
143    /// Use it on a remote track's codec: its fmtp line is the one the sender described.
144    ///
145    /// **This default does not follow RFC 6184 section 7.2.** The RFC initialises PDON to 0,
146    /// so a NAL unit whose DON is 0 is at the largest DON distance (65536) and a stream
147    /// numbered from DON 0 has its first NAL unit passed on last; here, until a NAL unit has
148    /// been passed on, PDON is the DON just before the earliest one buffered (a choice of rtci's
149    /// default, with its ground in `docs/conformance.md`, "Standing departures from a MUST").
150    /// [`MediaEngine::h264_depacketizer`] with [`MediaEngine::set_h264_literal_pdon`]`(true)`,
151    /// which the `StrictRfc` behaviour profile sets, gives the RFC's form
152    /// ([`H264DeinterleavingBuffer::with_literal_pdon`]).
153    ///
154    /// [`MediaEngine::h264_depacketizer`]: crate::peer_connection::configuration::media_engine::MediaEngine::h264_depacketizer
155    /// [`MediaEngine::set_h264_literal_pdon`]: crate::peer_connection::configuration::media_engine::MediaEngine::set_h264_literal_pdon
156    /// [`H264DeinterleavingBuffer::with_literal_pdon`]: rtp::codec::h264::H264DeinterleavingBuffer::with_literal_pdon
157    ///
158    /// # Errors
159    ///
160    /// `Error::ErrNoPayloaderForCodec` for a codec other than H.264; an error for a
161    /// `packetization-mode` other than 0, 1 or 2.
162    pub fn h264_depacketizer(&self) -> Result<rtp::codec::h264::H264Packet> {
163        self.h264_depacketizer_with(false)
164    }
165
166    /// [`Self::h264_depacketizer`], with RFC 6184 section 7.2.2's PDON initialised to 0 when
167    /// `literal_pdon` is set.
168    pub(crate) fn h264_depacketizer_with(
169        &self,
170        literal_pdon: bool,
171    ) -> Result<rtp::codec::h264::H264Packet> {
172        if !self.mime_type.eq_ignore_ascii_case(MIME_TYPE_H264) {
173            return Err(Error::ErrNoPayloaderForCodec);
174        }
175        let packet = rtp::codec::h264::H264Packet::default();
176        match h264_packetization_mode(&self.sdp_fmtp_line) {
177            0 | 1 => Ok(packet),
178            2 => {
179                let mut buffer = rtp::codec::h264::H264DeinterleavingBuffer::new(
180                    fmtp_number(&self.sdp_fmtp_line, "sprop-interleaving-depth").unwrap_or(0),
181                    fmtp_number(&self.sdp_fmtp_line, "sprop-max-don-diff"),
182                )
183                .with_literal_pdon(literal_pdon);
184                // RFC 6184 section 7.2.2: initial buffering also ends once it has lasted
185                // sprop-init-buf-time (90 kHz ticks, section 8.1); read by `depacketize_at`
186                // and `is_initial_buffering`.
187                if let Some(ticks) = fmtp_number(&self.sdp_fmtp_line, "sprop-init-buf-time") {
188                    buffer = buffer.with_init_buf_time(ticks);
189                }
190                Ok(packet.with_deinterleaving(buffer))
191            }
192            other => Err(Error::Other(format!(
193                "H.264 packetization-mode is 0, 1 or 2, not {other}"
194            ))),
195        }
196    }
197
198    /// Creates an H.265 depacketizer for a stream received with this codec, configured from
199    /// the sender's stream properties in its fmtp line: with `sprop-max-don-diff` above 0
200    /// the DONL and DOND fields are read and NAL units leave in decoding order through a
201    /// de-packetization buffer of `sprop-depack-buf-nalus` (RFC 7798 sections 6, 7.1).
202    ///
203    /// # Errors
204    ///
205    /// `Error::ErrNoPayloaderForCodec` for a codec other than H.265; an error for a `tx-mode`
206    /// other than SRST, which the depacketizer does not do (RFC 7798 section 7.1: "If the
207    /// value is equal to "MRST", MRST MUST be in use").
208    pub fn h265_depacketizer(&self) -> Result<rtp::codec::h265::H265Packet> {
209        if !self.mime_type.eq_ignore_ascii_case(MIME_TYPE_HEVC) {
210            return Err(Error::ErrNoPayloaderForCodec);
211        }
212        let tx_mode = fmtp_value(&self.sdp_fmtp_line, "tx-mode");
213        if tx_mode.is_some_and(|mode| !mode.eq_ignore_ascii_case("SRST")) {
214            return Err(Error::Other(format!(
215                "H.265 tx-mode {} is not supported, only SRST",
216                tx_mode.unwrap_or_default()
217            )));
218        }
219        let mut packet = rtp::codec::h265::H265Packet::default();
220        let max_don_diff = fmtp_number(&self.sdp_fmtp_line, "sprop-max-don-diff").unwrap_or(0);
221        if max_don_diff > 0 {
222            packet.with_depacketization_buffer(rtp::codec::h265::H265DepacketizationBuffer::new(
223                max_don_diff,
224                fmtp_number(&self.sdp_fmtp_line, "sprop-depack-buf-nalus").unwrap_or(0),
225            ));
226        }
227        Ok(packet)
228    }
229
230    /// The out-of-band parameter sets of the sender's stream, in the order the fmtp line
231    /// gives them: H.264 `sprop-parameter-sets` (RFC 6184 section 8.1, base64 NAL units
232    /// separated by commas) and the parameter set lists (`PSL`) of `sprop-level-parameter-sets`
233    /// (`PLId:PSL` pairs), H.265 `sprop-vps`, `sprop-sps`, `sprop-pps` and `sprop-sei`
234    /// (RFC 7798 section 7.1). A decoder takes them before the first NAL unit of the stream
235    /// (RFC 6184 section 8.2.2, RFC 7798 section 7.2.2). Empty for another codec or a line
236    /// without them.
237    ///
238    /// The codec of a received H.264 stream (a receiver's parameters, a remote track's codec)
239    /// carries the peer's line with the sets RFC 6184 section 8.2.2 has this endpoint ignore
240    /// already left out: `sprop-parameter-sets` only when the level to use is the peer's
241    /// default level, `sprop-level-parameter-sets` only for the level to use and only when
242    /// this endpoint's own line says `use-level-src-parameter-sets=1`, neither when it says
243    /// `in-band-parameter-sets=1`. A codec built by hand is read as it is.
244    ///
245    /// # Errors
246    ///
247    /// A value that is not base64.
248    pub fn sprop_parameter_sets(&self) -> Result<Vec<bytes::Bytes>> {
249        use base64::Engine as _;
250        let keys: &[&str] = if self.mime_type.eq_ignore_ascii_case(MIME_TYPE_H264) {
251            &["sprop-parameter-sets", "sprop-level-parameter-sets"]
252        } else if self.mime_type.eq_ignore_ascii_case(MIME_TYPE_HEVC) {
253            &["sprop-vps", "sprop-sps", "sprop-pps", "sprop-sei"]
254        } else {
255            &[]
256        };
257        let mut sets = vec![];
258        for key in keys {
259            let Some(value) = fmtp_value(&self.sdp_fmtp_line, key) else {
260                continue;
261            };
262            // `PLId:PSL:PLId:PSL...`: every second field is a list of sets.
263            let lists: Vec<&str> = if *key == "sprop-level-parameter-sets" {
264                value.split(':').skip(1).step_by(2).collect()
265            } else {
266                vec![value]
267            };
268            for set in lists
269                .into_iter()
270                .flat_map(|list| list.split(','))
271                .map(str::trim)
272                .filter(|s| !s.is_empty())
273            {
274                let nal_unit = base64::engine::general_purpose::STANDARD
275                    .decode(set)
276                    .map_err(|e| Error::Other(format!("{key}: {e}")))?;
277                sets.push(bytes::Bytes::from(nal_unit));
278            }
279        }
280        Ok(sets)
281    }
282}
283
284/// The value of an fmtp parameter, trimmed; parameter names compare without regard to case.
285fn fmtp_value<'a>(sdp_fmtp_line: &'a str, key: &str) -> Option<&'a str> {
286    sdp_fmtp_line
287        .split(';')
288        .filter_map(|parameter| parameter.trim().split_once('='))
289        .find(|(k, _)| k.trim().eq_ignore_ascii_case(key))
290        .map(|(_, value)| value.trim())
291}
292
293fn fmtp_number<T: std::str::FromStr>(sdp_fmtp_line: &str, key: &str) -> Option<T> {
294    fmtp_value(sdp_fmtp_line, key)?.parse().ok()
295}
296
297/// The `packetization-mode` an H.264 fmtp line names, 0 when it names none (RFC 6184 8.1).
298pub(crate) fn h264_packetization_mode(sdp_fmtp_line: &str) -> u8 {
299    fmtp_number::<u32>(sdp_fmtp_line, "packetization-mode")
300        .map_or(0, |mode| u8::try_from(mode).unwrap_or(u8::MAX))
301}
302
303/// Codec match quality result from fuzzy search.
304#[derive(Default, Debug, Copy, Clone, PartialEq)]
305pub(crate) enum CodecMatch {
306    /// No match found
307    #[default]
308    None = 0,
309    /// Partial match (MIME type matches)
310    Partial = 1,
311    /// Exact match (MIME type and format parameters match)
312    Exact = 2,
313}
314
315/// Performs fuzzy search for a codec in a list of available codecs.
316///
317/// First attempts an exact match on both MIME type and format parameters,
318/// then falls back to matching only the MIME type.
319///
320/// # Parameters
321///
322/// * `needle_rtp_codec` - The codec to search for
323/// * `haystack` - List of available codecs to search in
324///
325/// # Returns
326///
327/// A tuple of (matched codec parameters, match quality)
328pub(crate) fn codec_parameters_fuzzy_search(
329    needle_rtp_codec: &RTCRtpCodec,
330    haystack: &[RTCRtpCodecParameters],
331) -> (RTCRtpCodecParameters, CodecMatch) {
332    let needle_fmtp = fmtp::parse(&needle_rtp_codec.mime_type, &needle_rtp_codec.sdp_fmtp_line);
333    // A format is its encoding name and its clock rate (RFC 8866 section 6.6, `a=rtpmap`):
334    // `telephone-event/8000` and `telephone-event/48000` are two formats. A needle that
335    // states no clock rate (an encoding that leaves its codec to negotiation) matches any.
336    // So are its encoding parameters, the channel count of an audio format (`opus/48000/2`;
337    // RFC 7587 section 7: Opus "MUST" be `opus/48000/2`): two formats that state different
338    // counts are different formats. One that states none matches any.
339    let same_clock_rate = |c: &RTCRtpCodecParameters| {
340        (needle_rtp_codec.clock_rate == 0
341            || c.rtp_codec.clock_rate == 0
342            || c.rtp_codec.clock_rate == needle_rtp_codec.clock_rate)
343            && (needle_rtp_codec.channels == 0
344                || c.rtp_codec.channels == 0
345                || c.rtp_codec.channels == needle_rtp_codec.channels)
346    };
347
348    // First attempt to match on mime_type + sdpfmtp_line
349    for c in haystack.iter().filter(|c| same_clock_rate(c)) {
350        let cfmpt = fmtp::parse(&c.rtp_codec.mime_type, &c.rtp_codec.sdp_fmtp_line);
351        if needle_fmtp.match_fmtp(&*cfmpt) {
352            return (c.clone(), CodecMatch::Exact);
353        }
354    }
355
356    // Fallback to just mime_type
357    for c in haystack.iter().filter(|c| same_clock_rate(c)) {
358        // MIME types are ASCII-only; eq_ignore_ascii_case is sufficient and allocation-free.
359        if c.rtp_codec
360            .mime_type
361            .eq_ignore_ascii_case(&needle_rtp_codec.mime_type)
362        {
363            return (c.clone(), CodecMatch::Partial);
364        }
365    }
366
367    (RTCRtpCodecParameters::default(), CodecMatch::None)
368}
369
370/// [`codec_parameters_fuzzy_search`], taking among the formats of `haystack` it matches
371/// exactly the one that is the needle's own.
372///
373/// The exact match of the fuzzy search compares a format's configuration only (H.264 profile
374/// and `packetization-mode`, RFC 6184 section 8.2.2, where the level may differ; VP9
375/// `profile-id`; AV1 `profile`; H.265 profile and tier), so several registered formats of one
376/// configuration that differ in level or in another parameter all match, and the first
377/// one would stand for all of them (an offer gave the payload types of H.264 High levels 4.0
378/// to 5.1 the line of Level 5.0). Among the exact matches this takes, in order:
379///
380/// 1. one with the same parameters (W3C webrtc 5.4 codec dictionary match, asymmetrical
381///    parameters included) and the payload type `payload_type`,
382/// 2. one with the same parameters,
383/// 3. one with the payload type `payload_type`,
384/// 4. the first, as [`codec_parameters_fuzzy_search`] does.
385///
386/// A partial match or none is the fuzzy search's.
387pub(crate) fn codec_parameters_search(
388    needle_rtp_codec: &RTCRtpCodec,
389    payload_type: Option<PayloadType>,
390    haystack: &[RTCRtpCodecParameters],
391) -> (RTCRtpCodecParameters, CodecMatch) {
392    let (first, matched) = codec_parameters_fuzzy_search(needle_rtp_codec, haystack);
393    if matched != CodecMatch::Exact {
394        return (first, matched);
395    }
396    let exact: Vec<&RTCRtpCodecParameters> = haystack
397        .iter()
398        .filter(|c| {
399            codec_parameters_fuzzy_search(needle_rtp_codec, std::slice::from_ref(*c)).1
400                == CodecMatch::Exact
401        })
402        .collect();
403    let same_payload_type = |c: &&&RTCRtpCodecParameters| Some(c.payload_type) == payload_type;
404    let same_parameters =
405        |c: &&&RTCRtpCodecParameters| codec_dictionary_match(needle_rtp_codec, &c.rtp_codec);
406    let own = exact
407        .iter()
408        .find(|c| same_parameters(c) && same_payload_type(c))
409        .or_else(|| exact.iter().find(same_parameters))
410        .or_else(|| exact.iter().find(same_payload_type));
411    match own {
412        Some(own) => ((*own).clone(), CodecMatch::Exact),
413        None => (first, matched),
414    }
415}
416
417/// W3C webrtc 5.4 "codec dictionary match" with `ignoreAsymmetricalParameters` false (its
418/// default): see [`codec_dictionary_match_with`].
419pub(crate) fn codec_dictionary_match(first: &RTCRtpCodec, second: &RTCRtpCodec) -> bool {
420    codec_dictionary_match_with(first, second, false)
421}
422
423/// W3C webrtc 5.4 "codec dictionary match": whether two codec dictionaries name the same
424/// codec. The MIME types are equal without regard to case, the clock rates equal, the
425/// channels both absent (0) or equal, and the `sdpFmtpLine`s both absent (empty) or
426/// matching. Lines that are not in key-value format are compared as strings. Key-value
427/// lines must agree on the format's symmetrical parameters (`fmtp::match_fmtp`: H.264
428/// profile and packetization mode, H.265 profile, VP9 profile, AV1 nothing, and so on); with
429/// `ignore_asymmetrical_parameters` false every parameter must be equal too, a parameter
430/// left out counting as its default where the format infers one ("In some cases a parameter
431/// can be omitted and still be inferred").
432pub(crate) fn codec_dictionary_match_with(
433    first: &RTCRtpCodec,
434    second: &RTCRtpCodec,
435    ignore_asymmetrical_parameters: bool,
436) -> bool {
437    if !first.mime_type.eq_ignore_ascii_case(&second.mime_type)
438        || first.clock_rate != second.clock_rate
439        || first.channels != second.channels
440    {
441        return false;
442    }
443    let (first_fmtp, second_fmtp) = (first.sdp_fmtp_line.trim(), second.sdp_fmtp_line.trim());
444    if first_fmtp.is_empty() != second_fmtp.is_empty() {
445        return false;
446    }
447    if first_fmtp.is_empty() {
448        return true;
449    }
450    if !first_fmtp.contains('=') || !second_fmtp.contains('=') {
451        return first_fmtp == second_fmtp;
452    }
453    if !fmtp::parse(&first.mime_type, first_fmtp)
454        .match_fmtp(&*fmtp::parse(&second.mime_type, second_fmtp))
455    {
456        return false;
457    }
458    ignore_asymmetrical_parameters
459        || media_format(&first.mime_type, first_fmtp)
460            == media_format(&second.mime_type, second_fmtp)
461}
462
463/// The media format of a key-value `sdpFmtpLine` (W3C webrtc 5.4): each parameter by its
464/// lower-case name, with the defaults the format infers for one left out.
465fn media_format(mime_type: &str, fmtp: &str) -> std::collections::BTreeMap<String, String> {
466    let mut parameters: std::collections::BTreeMap<String, String> = fmtp
467        .split(';')
468        .filter_map(|p| {
469            let (key, value) = p.split_once('=')?;
470            Some((key.trim().to_ascii_lowercase(), value.trim().to_owned()))
471        })
472        .collect();
473    let defaults: &[(&str, &str)] = match mime_type.to_ascii_lowercase().as_str() {
474        // RFC 6184 section 8.1.
475        "video/h264" => &[
476            ("packetization-mode", "0"),
477            ("level-asymmetry-allowed", "0"),
478        ],
479        // RFC 7798 section 7.1.
480        "video/h265" => &[("profile-id", "1"), ("tier-flag", "0"), ("level-id", "93")],
481        // RTP payload format for VP9, section 6.
482        "video/vp9" => &[("profile-id", "0")],
483        // AV1 RTP payload format, section 7.2.
484        "video/av1" => &[("profile", "0"), ("level-idx", "5"), ("tier", "0")],
485        _ => &[],
486    };
487    for (key, value) in defaults {
488        parameters
489            .entry((*key).to_owned())
490            .or_insert_with(|| (*value).to_owned());
491    }
492    parameters
493}
494
495/// The negotiated codec an encoding is sent with.
496///
497/// An encoding that names a codec is sent with the negotiated codec matching it
498/// ([`codec_parameters_fuzzy_search`]). One that names none (an empty `codec`, the
499/// `RTCRtpCodec` default: W3C `addTransceiver` lets `sendEncodings` leave the codec to
500/// negotiation) is sent with the first media codec of the negotiated list, the codec the
501/// sender's parameters prefer; repair formats (RTX, RED, ULPFEC, FlexFEC) only accompany
502/// a media codec and are never it.
503///
504/// # Returns
505///
506/// `None` when the encoding names a codec that was not negotiated, or names none and the
507/// negotiated list has no media codec.
508pub(crate) fn encoding_send_codec(
509    codec: &RTCRtpCodec,
510    negotiated: &[RTCRtpCodecParameters],
511) -> Option<RTCRtpCodecParameters> {
512    if codec.mime_type.is_empty() {
513        return negotiated
514            .iter()
515            .find(|c| !c.rtp_codec.mime_type.is_empty() && !is_repair_codec(&c.rtp_codec))
516            .cloned();
517    }
518    // W3C webrtc 4.4.1.6: an encoding's codec is the negotiated one it matches by the codec
519    // dictionary match with `ignoreAsymmetricalParameters` true (no mime-type-only match).
520    negotiated
521        .iter()
522        .find(|c| codec_dictionary_match_with(codec, &c.rtp_codec, true))
523        .cloned()
524}
525
526/// Searches for a matching encoding in available codecs.
527///
528/// Iterates through encodings looking for the best codec match, preferring exact matches.
529///
530/// # Parameters
531///
532/// * `encodings` - List of encoding parameters to search through
533/// * `haystack` - List of available codec parameters
534///
535/// # Returns
536///
537/// A tuple of (matched encoding, match quality)
538pub(crate) fn encoding_parameters_fuzzy_search(
539    encodings: &[RTCRtpEncodingParameters],
540    haystack: &[RTCRtpCodecParameters],
541) -> (RTCRtpEncodingParameters, CodecMatch) {
542    let mut result = None;
543    for encoding in encodings {
544        let (_, codec_match_type) = codec_parameters_fuzzy_search(&encoding.codec, haystack);
545        if codec_match_type == CodecMatch::Exact {
546            return (encoding.clone(), codec_match_type);
547        } else if result.is_none() {
548            result = Some((encoding.clone(), CodecMatch::Partial));
549        }
550    }
551
552    if let Some((encoding, code_match_type)) = result {
553        (encoding, code_match_type)
554    } else {
555        (RTCRtpEncodingParameters::default(), CodecMatch::None)
556    }
557}
558
559/// Finds the RTX payload type associated with a given payload type.
560///
561/// Searches for an RTX codec with the matching APT (Associated Payload Type) parameter.
562///
563/// # Parameters
564///
565/// * `needle` - The primary payload type to find RTX for
566/// * `haystack` - List of codec parameters to search
567///
568/// # Returns
569///
570/// The RTX payload type if found, None otherwise
571pub(crate) fn find_rtx_payload_type(
572    needle: PayloadType,
573    haystack: &[RTCRtpCodecParameters],
574) -> Option<PayloadType> {
575    for c in haystack {
576        // Match on the parsed `apt` value rather than the whole fmtp line, so an
577        // RTX codec carrying extra parameters (e.g. `apt=96;rtx-time=3000`, RFC
578        // 4588 §8.1) is still associated with its primary.
579        if parse_rtx_apt(&c.rtp_codec.sdp_fmtp_line) == Some(needle) {
580            return Some(c.payload_type);
581        }
582    }
583
584    None
585}
586
587/// Parses the associated payload type (`apt`) from an RTX codec's fmtp line.
588///
589/// RFC 4588 §8.1 defines the `apt` parameter, which maps a retransmission
590/// payload type to the payload type of the stream it repairs. The fmtp line may
591/// carry additional parameters (e.g. `apt=96;rtx-time=3000`), so the value is
592/// extracted from the `apt=` token rather than compared against the whole line.
593///
594/// # Parameters
595///
596/// * `sdp_fmtp_line` - The RTX codec's fmtp line, e.g. `"apt=96"`
597///
598/// # Returns
599///
600/// The associated (primary) payload type if an `apt=` token is present, else None.
601pub(crate) fn parse_rtx_apt(sdp_fmtp_line: &str) -> Option<PayloadType> {
602    sdp_fmtp_line
603        .split(';')
604        .filter_map(|param| param.trim().strip_prefix("apt="))
605        .find_map(|value| value.trim().parse::<PayloadType>().ok())
606}
607
608/// The `rtx-time` of a retransmission format's fmtp line (RFC 4588 section 8.1: "the time in
609/// milliseconds (measured from the time a packet was first sent) that the sender keeps an RTP
610/// packet in its buffers available for retransmission"), e.g. of `"apt=96;rtx-time=3000"`.
611pub(crate) fn parse_rtx_time(sdp_fmtp_line: &str) -> Option<std::time::Duration> {
612    sdp_fmtp_line
613        .split(';')
614        .filter_map(|param| param.trim().strip_prefix("rtx-time="))
615        .find_map(|value| value.trim().parse::<u64>().ok())
616        .map(std::time::Duration::from_millis)
617}
618
619/// Whether `mime_type` is a retransmission format (`audio/rtx`, `video/rtx`; RFC 4588
620/// section 8).
621pub(crate) fn is_rtx_mime_type(mime_type: &str) -> bool {
622    mime_type
623        .split_once('/')
624        .is_some_and(|(_, subtype)| subtype.eq_ignore_ascii_case("rtx"))
625}
626
627/// Whether `codec` repairs another stream rather than carrying media of its own.
628///
629/// Covers retransmission (RTX, RFC 4588) and forward error correction (FlexFEC, ULPFEC, RED).
630/// These are not alternative media formats a peer chooses between — they accompany whichever
631/// primary codec was chosen — which is why codec preferences leave them in place. See
632/// [setCodecPreferences](https://www.w3.org/TR/webrtc/#dom-rtcrtptransceiver-setcodecpreferences):
633///
634/// > Codecs of type RTX, RED and FEC are always supported […] and are not affected by this method.
635pub(crate) fn is_repair_codec(codec: &RTCRtpCodec) -> bool {
636    let mime_type = codec.mime_type.to_lowercase();
637    let subtype = mime_type
638        .split_once('/')
639        .map_or(mime_type.as_str(), |(_, subtype)| subtype);
640
641    matches!(subtype, "rtx" | "ulpfec" | "red") || subtype.starts_with("flexfec")
642}
643
644/// The kind of a repair format: `"rtx"`, `"ulpfec"`, `"red"` or `"flexfec"` (any FlexFEC
645/// draft); `""` for a media codec.
646pub(crate) fn repair_family(codec: &RTCRtpCodec) -> &'static str {
647    let mime_type = codec.mime_type.to_lowercase();
648    let subtype = mime_type
649        .split_once('/')
650        .map_or(mime_type.as_str(), |(_, subtype)| subtype);
651    match subtype {
652        "rtx" => "rtx",
653        "ulpfec" => "ulpfec",
654        "red" => "red",
655        s if s.starts_with("flexfec") => "flexfec",
656        _ => "",
657    }
658}
659
660/// Whether `mime_type` names FlexFEC draft-ietf-payload-flexible-fec-scheme-03
661/// (`video/flexfec-03`), matched exactly.
662///
663/// RFC 8627's `video/flexfec` is a different wire format (its own header layout and masks), so a
664/// substring match, which also took `video/flexfec`, handed RFC 8627 packets to the draft-03
665/// coder.
666pub(crate) fn is_flexfec03_mime_type(mime_type: &str) -> bool {
667    mime_type.eq_ignore_ascii_case(MIME_TYPE_FLEX_FEC03)
668}
669
670/// Whether `mime_type` names RFC 8627 FlexFEC (`video/flexfec`), matched exactly: never
671/// `video/flexfec-03`, which is the draft-03 coder's.
672pub(crate) fn is_flexfec_mime_type(mime_type: &str) -> bool {
673    mime_type.eq_ignore_ascii_case(MIME_TYPE_FLEX_FEC)
674}
675
676/// Whether `mime_type` names a FEC format the engine has a coder for: FlexFEC draft-03
677/// (`video/flexfec-03`) or RFC 8627 (`video/flexfec`).
678pub(crate) fn is_fec_mime_type(mime_type: &str) -> bool {
679    is_flexfec03_mime_type(mime_type) || is_flexfec_mime_type(mime_type)
680}
681
682/// The FEC format a stream's repair flow uses: its payload type and what selects and
683/// configures the coder (the interceptors read the MIME type and the `a=fmtp` line).
684#[derive(Debug, Clone, PartialEq, Eq)]
685pub(crate) struct FecFormat {
686    pub(crate) payload_type: PayloadType,
687    pub(crate) mime_type: String,
688    pub(crate) sdp_fmtp_line: String,
689}
690
691/// The FEC format of `haystack`: FlexFEC draft-03 when it is there (what browsers send), else
692/// RFC 8627 FlexFEC.
693pub(crate) fn find_fec_format(haystack: &[RTCRtpCodecParameters]) -> Option<FecFormat> {
694    haystack
695        .iter()
696        .find(|c| is_flexfec03_mime_type(&c.rtp_codec.mime_type))
697        .or_else(|| {
698            haystack
699                .iter()
700                .find(|c| is_flexfec_mime_type(&c.rtp_codec.mime_type))
701        })
702        .map(|c| FecFormat {
703            payload_type: c.payload_type,
704            mime_type: c.rtp_codec.mime_type.clone(),
705            sdp_fmtp_line: c.rtp_codec.sdp_fmtp_line.clone(),
706        })
707}
708
709/// The FEC format of a remote stream's `FEC-FR` repair flow in `haystack`: as
710/// [`find_fec_format`], and else ULPFEC (`video/ulpfec`) as a stream of its own (RFC 5109
711/// section 14.1, SSRC-multiplexed in the session as RFC 5956 section 4.3 groups it). Only the
712/// receive side reads it: the engine sends ULPFEC in RED unless the application builds the
713/// separate stream itself, so a local ULPFEC registration mints no repair SSRC.
714pub(crate) fn find_receive_fec_format(haystack: &[RTCRtpCodecParameters]) -> Option<FecFormat> {
715    find_fec_format(haystack).or_else(|| {
716        haystack
717            .iter()
718            .find(|c| {
719                c.rtp_codec.mime_type.eq_ignore_ascii_case(
720                    crate::peer_connection::configuration::media_engine::MIME_TYPE_ULP_FEC,
721                )
722            })
723            .map(|c| FecFormat {
724                payload_type: c.payload_type,
725                mime_type: c.rtp_codec.mime_type.clone(),
726                sdp_fmtp_line: c.rtp_codec.sdp_fmtp_line.clone(),
727            })
728    })
729}
730
731/// The payload type of the FEC format in `haystack` ([`find_fec_format`]).
732#[cfg(test)]
733pub(crate) fn find_fec_payload_type(haystack: &[RTCRtpCodecParameters]) -> Option<PayloadType> {
734    find_fec_format(haystack).map(|format| format.payload_type)
735}
736
737/// The RTCP feedback a packet is, as the `a=rtcp-fb` entry (type, first word of the
738/// parameter) that negotiates it: NACK, PLI, SLI, RPSI (RFC 4585), FIR, TMMBR / TMMBN, TSTR /
739/// TSTN, VBCM (RFC 5104), LRR (`ccm lrr`), REMB (`goog-remb`), transport-wide congestion
740/// control (`transport-cc`), RFC 8888 (`ack ccfb`) and the RFC 6679 ECN feedback (`nack ecn`).
741/// `None` for what is not feedback (SR, RR, SDES, BYE, APP, XR) and for feedback this endpoint
742/// has no negotiation rule for.
743pub(crate) fn feedback_negotiating(
744    packet: &dyn rtcp::Packet,
745) -> Option<(&'static str, &'static str)> {
746    use rtcp::payload_feedbacks::{
747        full_intra_request::FullIntraRequest,
748        layer_refresh_request::LayerRefreshRequest,
749        picture_loss_indication::PictureLossIndication,
750        receiver_estimated_maximum_bitrate::ReceiverEstimatedMaximumBitrate,
751        reference_picture_selection_indication::ReferencePictureSelectionIndication,
752        slice_loss_indication::SliceLossIndication,
753        temporal_spatial_tradeoff::{
754            TemporalSpatialTradeoffNotification, TemporalSpatialTradeoffRequest,
755        },
756        video_back_channel_message::VideoBackChannelMessage,
757    };
758    use rtcp::transport_feedbacks::{
759        cc_feedback_report::CcFeedbackReport,
760        ecn_feedback::EcnFeedback,
761        tmmb::{TemporaryMaximumBitrateNotification, TemporaryMaximumBitrateRequest},
762        transport_layer_cc::TransportLayerCc,
763        transport_layer_nack::TransportLayerNack,
764    };
765    let any = packet.as_any();
766    Some(if any.is::<TransportLayerNack>() {
767        ("nack", "")
768    } else if any.is::<PictureLossIndication>() {
769        ("nack", "pli")
770    } else if any.is::<SliceLossIndication>() {
771        ("nack", "sli")
772    } else if any.is::<ReferencePictureSelectionIndication>() {
773        ("nack", "rpsi")
774    } else if any.is::<EcnFeedback>() {
775        ("nack", "ecn")
776    } else if any.is::<FullIntraRequest>() {
777        ("ccm", "fir")
778    } else if any.is::<TemporaryMaximumBitrateRequest>()
779        || any.is::<TemporaryMaximumBitrateNotification>()
780    {
781        ("ccm", "tmmbr")
782    } else if any.is::<TemporalSpatialTradeoffRequest>()
783        || any.is::<TemporalSpatialTradeoffNotification>()
784    {
785        ("ccm", "tstr")
786    } else if any.is::<VideoBackChannelMessage>() {
787        ("ccm", "vbcm")
788    } else if any.is::<LayerRefreshRequest>() {
789        ("ccm", "lrr")
790    } else if any.is::<ReceiverEstimatedMaximumBitrate>() {
791        ("goog-remb", "")
792    } else if any.is::<TransportLayerCc>() {
793        ("transport-cc", "")
794    } else if any.is::<CcFeedbackReport>() {
795        ("ack", "ccfb")
796    } else {
797        return None;
798    })
799}
800
801/// RFC 4585 section 4.2 ("no feedback messages other than those listed ... MUST be used") and
802/// RFC 5104 section 7.2 ("MUST NOT use other CCM messages than those indicated"): the first
803/// of `packets` whose feedback type `negotiated` (the feedback of a section's negotiated
804/// codecs) does not list, as its `a=rtcp-fb` type and parameter.
805pub(crate) fn unnegotiated_feedback(
806    packets: &[Box<dyn rtcp::Packet>],
807    negotiated: &[RTCRtpCodecParameters],
808) -> Option<(&'static str, &'static str)> {
809    packets
810        .iter()
811        .filter_map(|packet| feedback_negotiating(packet.as_ref()))
812        .find(|(typ, parameter)| {
813            !negotiated
814                .iter()
815                .flat_map(|codec| &codec.rtp_codec.rtcp_feedback)
816                .any(|f| {
817                    f.typ.eq_ignore_ascii_case(typ)
818                        && f.parameter
819                            .split_whitespace()
820                            .next()
821                            .unwrap_or("")
822                            .eq_ignore_ascii_case(parameter)
823                })
824        })
825}
826
827/// Computes the intersection of two RTCP feedback lists.
828///
829/// Returns feedback mechanisms that are supported by both lists,
830/// matching on both type and parameter fields.
831///
832/// `trr-int` matches on the type alone and keeps the parameter of `a`: its number is each
833/// endpoint's own minimum interval between regular RTCP packets (RFC 4585 section 4.2), not
834/// a capability the two have to agree on, so an answer states its own.
835///
836/// # Parameters
837///
838/// * `a` - First feedback list
839/// * `b` - Second feedback list
840///
841/// # Returns
842///
843/// Vector of common feedback mechanisms
844/// `ccm tmmbr` of both lists, whatever their `smaxpr` (RFC 5104 section 7.1: "tmmbr
845/// smaxpr=<n>", the session maximum packet rate). Section 7.2: "the highest value from offer
846/// and answer SHALL be used. If the session maximum packet rate parameter is not present in an
847/// offer, it SHALL NOT be included by the answerer": `b` is the remote side's list, and
848/// without its `smaxpr` the result has none. `None` when the two are not both `ccm tmmbr`.
849fn tmmbr_intersection(a: &RTCPFeedback, b: &RTCPFeedback) -> Option<RTCPFeedback> {
850    let smaxpr = |f: &RTCPFeedback| -> Option<Option<u64>> {
851        if f.typ != TYPE_RTCP_FB_CCM {
852            return None;
853        }
854        let mut tokens = f.parameter.split_whitespace();
855        if tokens.next() != Some("tmmbr") {
856            return None;
857        }
858        Some(tokens.find_map(|t| t.strip_prefix("smaxpr=")?.parse().ok()))
859    };
860    let (ours, theirs) = (smaxpr(a)?, smaxpr(b)?);
861    Some(RTCPFeedback {
862        typ: TYPE_RTCP_FB_CCM.to_owned(),
863        parameter: match theirs {
864            Some(theirs) => format!("tmmbr smaxpr={}", ours.unwrap_or(0).max(theirs)),
865            None => "tmmbr".to_owned(),
866        },
867    })
868}
869
870/// `Some` when `a` (this endpoint's) and `b` (the peer's) are both `ccm pause` lines: the
871/// negotiated line (RFC 7728 section 9.1), or `None` when the peer's cannot be answered.
872fn pause_intersection(a: &RTCPFeedback, b: &RTCPFeedback) -> Option<Option<RTCPFeedback>> {
873    if a.typ != TYPE_RTCP_FB_CCM || b.typ != TYPE_RTCP_FB_CCM {
874        return None;
875    }
876    let (ours, theirs) = (
877        interceptor::PauseCapability::parse(&a.parameter)?,
878        interceptor::PauseCapability::parse(&b.parameter),
879    );
880    let Some(theirs) = theirs else {
881        return b
882            .parameter
883            .split_whitespace()
884            .next()
885            .is_some_and(|word| word.eq_ignore_ascii_case(interceptor::RTCP_FB_CCM_PAUSE))
886            .then_some(None);
887    };
888    Some(
889        interceptor::PauseCapability::negotiate(&ours, &theirs).map(|negotiated| RTCPFeedback {
890            typ: TYPE_RTCP_FB_CCM.to_owned(),
891            parameter: negotiated.parameter(),
892        }),
893    )
894}
895
896/// Whether an `xr-format` of `a=rtcp-xr` is one of the unilateral formats the engine's XR
897/// generator writes blocks for (RFC 3611 section 5.1: `pkt-loss-rle`, `pkt-dup-rle`,
898/// `pkt-rcpt-times`, `stat-summary`, `voip-metrics`, each with or without its value).
899pub(crate) fn is_unilateral_xr_format(format: &str) -> bool {
900    let name = format.split_once('=').map_or(format, |(name, _)| name);
901    matches!(
902        name,
903        "pkt-loss-rle" | "pkt-dup-rle" | "pkt-rcpt-times" | "stat-summary" | "voip-metrics"
904    )
905}
906
907pub(crate) fn rtcp_feedback_intersection(
908    a: &[RTCPFeedback],
909    b: &[RTCPFeedback],
910) -> Vec<RTCPFeedback> {
911    let mut out = vec![];
912    for a_feedback in a {
913        for b_feeback in b {
914            // RFC 7728 section 9.1: `ccm pause` is answered with the complementary `config`
915            // and `nowait` only when both sides have it; a `config` the section does not
916            // define removes the line.
917            if let Some(pause) = pause_intersection(a_feedback, b_feeback) {
918                if let Some(pause) = pause {
919                    out.push(pause);
920                }
921                break;
922            }
923            if a_feedback.typ == b_feeback.typ
924                && (a_feedback.parameter == b_feeback.parameter || a_feedback.typ == "trr-int")
925            {
926                out.push(a_feedback.clone());
927                break;
928            }
929            // Receiver reference times, from an `a=rtcp-fb ... rrtr` line or from
930            // `a=rtcp-xr:rcvr-rtt` (RFC 3611 section 5.1): the remote side's form is kept, so
931            // that an answer repeats the form the offer used.
932            if a_feedback.typ == interceptor::RTCP_FB_RRTR && b_feeback.typ == a_feedback.typ {
933                out.push(b_feeback.clone());
934                break;
935            }
936            if let Some(tmmbr) = tmmbr_intersection(a_feedback, b_feeback) {
937                out.push(tmmbr);
938                break;
939            }
940        }
941    }
942    // RFC 3611 section 5.2: "For "sendonly" and "sendrecv" media stream offers that specify
943    // unilateral "rtcp-xr" attribute parameters, the answerer SHOULD send the corresponding XR
944    // blocks" (and an offerer the ones a "sendrecv" answer asks for). A unilateral format the
945    // remote side (`b`) asks for is negotiated in its form, size limit and fields included,
946    // whatever this endpoint registered: it is a request to this endpoint's receiver, which the
947    // XR generator answers (`interceptor::XrReportInterceptor`). It is not repeated in this
948    // endpoint's own `a=rtcp-xr` (`add_transceiver_sdp`), where it would ask the peer for blocks.
949    for b_feedback in b {
950        if b_feedback.typ == interceptor::RTCP_FB_XR
951            && is_unilateral_xr_format(&b_feedback.parameter)
952            && !out.contains(b_feedback)
953        {
954            out.push(b_feedback.clone());
955        }
956    }
957
958    // RFC 8888 section 6: of several congestion control feedback mechanisms "that offer
959    // substantially the same semantics", the answer SHOULD include only one, and the same one
960    // in a later answer to the same offer. RFC 8888 is kept and transport-wide congestion
961    // control dropped, which is also what the interceptors run a stream on when a peer
962    // answered both (`interceptor::negotiated_congestion_feedback`).
963    //
964    // RFC 8888 section 7: "If an SDP offer signals support for both RTP Congestion Control
965    // Feedback Packets and the RTCP ECN Feedback Packet, the answering party SHOULD signal
966    // support for one, but not both": the RFC 6679 ECN feedback (`nack ecn`) duplicates what
967    // the RFC 8888 report carries per packet, and goes as well.
968    let is_ccfb = |f: &RTCPFeedback| f.typ == TYPE_RTCP_FB_ACK && f.parameter == RTCP_FB_ACK_CCFB;
969    if out.iter().any(is_ccfb) {
970        out.retain(|f| {
971            f.typ != TYPE_RTCP_FB_TRANSPORT_CC
972                && !(f.typ == TYPE_RTCP_FB_NACK && f.parameter == RTCP_FB_NACK_ECN)
973        });
974    }
975
976    out
977}
978
979#[cfg(test)]
980mod congestion_feedback_answer_test {
981    use super::*;
982
983    fn feedback(typ: &str, parameter: &str) -> RTCPFeedback {
984        RTCPFeedback {
985            typ: typ.to_owned(),
986            parameter: parameter.to_owned(),
987        }
988    }
989
990    /// RFC 8888 section 6: offered RFC 8888 and transport-wide congestion control together,
991    /// the answer keeps one of them, RFC 8888, and the same one every time.
992    #[test]
993    fn an_answer_keeps_one_congestion_feedback_mechanism() {
994        let ours = [
995            feedback("nack", ""),
996            feedback("transport-cc", ""),
997            feedback("ack", "ccfb"),
998        ];
999        let offered_both = [
1000            feedback("ack", "ccfb"),
1001            feedback("transport-cc", ""),
1002            feedback("nack", ""),
1003        ];
1004        let expected = vec![feedback("nack", ""), feedback("ack", "ccfb")];
1005        assert_eq!(expected, rtcp_feedback_intersection(&ours, &offered_both));
1006        assert_eq!(
1007            expected,
1008            rtcp_feedback_intersection(&ours, &offered_both),
1009            "a later answer to the same offer chooses the same mechanism"
1010        );
1011    }
1012
1013    /// RFC 8888 section 7: offered RFC 8888 feedback and the RFC 6679 ECN feedback packet
1014    /// (`nack ecn`) together, the answer signals one, RFC 8888, even where the answerer
1015    /// registered both; plain `nack` is another matter and stays.
1016    #[test]
1017    fn an_offer_of_ccfb_and_nack_ecn_is_answered_with_ccfb_only() {
1018        let ours = [
1019            feedback("nack", ""),
1020            feedback("nack", "ecn"),
1021            feedback("ack", "ccfb"),
1022        ];
1023        let offered = [
1024            feedback("nack", "ecn"),
1025            feedback("ack", "ccfb"),
1026            feedback("nack", ""),
1027        ];
1028        assert_eq!(
1029            vec![feedback("nack", ""), feedback("ack", "ccfb")],
1030            rtcp_feedback_intersection(&ours, &offered)
1031        );
1032        // Without RFC 8888 in the answer, `nack ecn` is the ECN feedback and is kept.
1033        assert_eq!(
1034            vec![feedback("nack", "ecn")],
1035            rtcp_feedback_intersection(&ours[1..2], &offered)
1036        );
1037    }
1038
1039    /// A peer that offers transport-wide congestion control alone, as browsers do, gets it.
1040    #[test]
1041    fn transport_cc_is_answered_when_rfc8888_was_not_offered() {
1042        let ours = [feedback("transport-cc", ""), feedback("ack", "ccfb")];
1043        let offered = [feedback("transport-cc", ""), feedback("nack", "")];
1044        assert_eq!(
1045            vec![feedback("transport-cc", "")],
1046            rtcp_feedback_intersection(&ours, &offered)
1047        );
1048    }
1049}
1050
1051#[cfg(test)]
1052#[path = "rtp_codec_packetization_test.rs"]
1053mod rtp_codec_packetization_test;
1054
1055#[cfg(test)]
1056#[path = "rtp_codec_flexfec_test.rs"]
1057mod rtp_codec_flexfec_test;
1058
1059#[cfg(test)]
1060mod rtx_apt_test {
1061    use super::{
1062        RTCRtpCodec, RTCRtpCodecParameters, encoding_send_codec, find_rtx_payload_type,
1063        is_rtx_mime_type, parse_rtx_apt, parse_rtx_time,
1064    };
1065
1066    fn media(mime_type: &str, payload_type: u8) -> RTCRtpCodecParameters {
1067        RTCRtpCodecParameters {
1068            rtp_codec: RTCRtpCodec {
1069                mime_type: mime_type.to_owned(),
1070                clock_rate: 90000,
1071                ..Default::default()
1072            },
1073            payload_type,
1074        }
1075    }
1076
1077    #[test]
1078    fn an_encoding_without_a_codec_is_sent_with_the_first_media_codec() {
1079        // Repair formats only accompany a media codec: one listed first is passed over.
1080        let negotiated = vec![
1081            rtx(97, "apt=96"),
1082            media("video/red", 63),
1083            media("video/ulpfec", 116),
1084            media("video/flexfec-03", 118),
1085            media("video/VP8", 96),
1086            media("video/H264", 102),
1087        ];
1088        let chosen = encoding_send_codec(&RTCRtpCodec::default(), &negotiated);
1089        assert_eq!(chosen.map(|c| c.payload_type), Some(96));
1090        assert_eq!(
1091            encoding_send_codec(&RTCRtpCodec::default(), &[rtx(97, "apt=96")]),
1092            None,
1093            "nothing to send with"
1094        );
1095    }
1096
1097    #[test]
1098    fn an_encoding_naming_a_codec_is_sent_with_that_codec_or_not_at_all() {
1099        let negotiated = vec![media("video/VP8", 96), media("video/H264", 102)];
1100        let h264 = RTCRtpCodec {
1101            mime_type: "video/H264".to_owned(),
1102            clock_rate: 90000,
1103            ..Default::default()
1104        };
1105        assert_eq!(
1106            encoding_send_codec(&h264, &negotiated).map(|c| c.payload_type),
1107            Some(102)
1108        );
1109        let vp9 = RTCRtpCodec {
1110            mime_type: "video/VP9".to_owned(),
1111            clock_rate: 90000,
1112            ..Default::default()
1113        };
1114        assert_eq!(
1115            encoding_send_codec(&vp9, &negotiated),
1116            None,
1117            "a codec that was not negotiated is not replaced by another"
1118        );
1119    }
1120
1121    fn rtx(payload_type: u8, fmtp: &str) -> RTCRtpCodecParameters {
1122        RTCRtpCodecParameters {
1123            rtp_codec: RTCRtpCodec {
1124                mime_type: "video/rtx".to_owned(),
1125                clock_rate: 90000,
1126                channels: 0,
1127                sdp_fmtp_line: fmtp.to_owned(),
1128                rtcp_feedback: vec![],
1129            },
1130            payload_type,
1131        }
1132    }
1133
1134    #[test]
1135    fn find_rtx_payload_type_tolerates_extra_apt_params() {
1136        // A remote may append rtx-time to the apt fmtp (RFC 4588 §8.1); the
1137        // association must still succeed rather than dropping RTX from the answer.
1138        let haystack = vec![rtx(97, "apt=96;rtx-time=3000"), rtx(99, "apt=98")];
1139        assert_eq!(find_rtx_payload_type(96, &haystack), Some(97));
1140        assert_eq!(find_rtx_payload_type(98, &haystack), Some(99));
1141        assert_eq!(find_rtx_payload_type(100, &haystack), None);
1142    }
1143
1144    #[test]
1145    fn parses_plain_apt() {
1146        assert_eq!(parse_rtx_apt("apt=96"), Some(96));
1147        assert_eq!(parse_rtx_apt("apt=127"), Some(127));
1148        assert_eq!(parse_rtx_apt("apt=0"), Some(0));
1149    }
1150
1151    #[test]
1152    fn parses_apt_with_extra_params() {
1153        // RFC 4588 §8.1 allows an optional rtx-time parameter alongside apt.
1154        assert_eq!(parse_rtx_apt("apt=96;rtx-time=3000"), Some(96));
1155        assert_eq!(parse_rtx_apt("rtx-time=3000;apt=102"), Some(102));
1156        assert_eq!(parse_rtx_apt("apt=98 ; rtx-time=1000"), Some(98));
1157        let ms = std::time::Duration::from_millis;
1158        assert_eq!(parse_rtx_time("apt=96;rtx-time=3000"), Some(ms(3000)));
1159        assert_eq!(parse_rtx_time("rtx-time=250; apt=102"), Some(ms(250)));
1160        assert_eq!(parse_rtx_time("apt=96"), None);
1161        assert_eq!(parse_rtx_time("apt=96;rtx-time=soon"), None);
1162        assert!(is_rtx_mime_type("video/rtx") && is_rtx_mime_type("audio/RTX"));
1163        assert!(!is_rtx_mime_type("video/VP8"));
1164    }
1165
1166    #[test]
1167    fn returns_none_without_apt() {
1168        assert_eq!(parse_rtx_apt(""), None);
1169        assert_eq!(parse_rtx_apt("profile-id=0"), None);
1170        assert_eq!(parse_rtx_apt("apt="), None);
1171        assert_eq!(parse_rtx_apt("apt=notanumber"), None);
1172        // Out of the u8 payload-type range.
1173        assert_eq!(parse_rtx_apt("apt=300"), None);
1174    }
1175
1176    fn tmmbr(parameter: &str) -> Vec<super::RTCPFeedback> {
1177        vec![super::RTCPFeedback {
1178            typ: super::TYPE_RTCP_FB_CCM.to_owned(),
1179            parameter: parameter.to_owned(),
1180        }]
1181    }
1182
1183    /// RFC 5104 section 7.2: "the highest value from offer and answer SHALL be used", and
1184    /// section 7.1: without `smaxpr` the rate "defaults to infinity". This endpoint's offered
1185    /// `smaxpr` against a remote answer: a higher answered value wins, a lower one loses, and
1186    /// an answer without one leaves the session without a limit (infinity is the highest).
1187    #[test]
1188    fn the_session_maximum_packet_rate_is_the_highest_of_offer_and_answer() {
1189        let ours = tmmbr("tmmbr smaxpr=120");
1190        assert_eq!(
1191            super::rtcp_feedback_intersection(&ours, &tmmbr("tmmbr smaxpr=200")),
1192            tmmbr("tmmbr smaxpr=200")
1193        );
1194        assert_eq!(
1195            super::rtcp_feedback_intersection(&ours, &tmmbr("tmmbr smaxpr=60")),
1196            tmmbr("tmmbr smaxpr=120")
1197        );
1198        assert_eq!(
1199            super::rtcp_feedback_intersection(&ours, &tmmbr("tmmbr")),
1200            tmmbr("tmmbr")
1201        );
1202        // An answerer without a limit of its own keeps the offered one: the highest of the
1203        // two is the offer's, which it states (section 7.2 forbids only adding one).
1204        assert_eq!(
1205            super::rtcp_feedback_intersection(&tmmbr("tmmbr"), &tmmbr("tmmbr smaxpr=120")),
1206            tmmbr("tmmbr smaxpr=120")
1207        );
1208    }
1209
1210    /// RFC 3611 section 5.1: `rcvr-rtt=<mode>[:<max size>]` reaches the stream as the remote
1211    /// side signalled it, mode and maximum DLRR size included, whatever form this endpoint
1212    /// registered, so that the RTCP session keeps its DLRR blocks within the peer's maximum.
1213    #[test]
1214    fn the_remote_rcvr_rtt_mode_and_maximum_are_negotiated() {
1215        let rrtr = |parameter: &str| {
1216            vec![super::RTCPFeedback {
1217                typ: interceptor::RTCP_FB_RRTR.to_owned(),
1218                parameter: parameter.to_owned(),
1219            }]
1220        };
1221        assert_eq!(
1222            super::rtcp_feedback_intersection(&rrtr("rcvr-rtt=all"), &rrtr("rcvr-rtt=sender:64")),
1223            rrtr("rcvr-rtt=sender:64")
1224        );
1225    }
1226
1227    /// RFC 3611 section 5.2: the unilateral formats the remote side's `a=rtcp-xr` asks for
1228    /// are negotiated in the remote form (this endpoint sends those blocks), although this
1229    /// endpoint registered none of them; a format the generator does not write, and `ecn-sum`
1230    /// (RFC 6679, which both sides must have), are not.
1231    #[test]
1232    fn the_unilateral_xr_formats_the_remote_side_asks_for_are_negotiated() {
1233        let feedback = |typ: &str, parameter: &str| super::RTCPFeedback {
1234            typ: typ.to_owned(),
1235            parameter: parameter.to_owned(),
1236        };
1237        let ours = vec![feedback("nack", "")];
1238        let remote = vec![
1239            feedback("nack", ""),
1240            feedback(interceptor::RTCP_FB_XR, "pkt-loss-rle=1024"),
1241            feedback(interceptor::RTCP_FB_XR, "voip-metrics"),
1242            feedback(interceptor::RTCP_FB_XR, "stat-summary=loss,jitt"),
1243            feedback(interceptor::RTCP_FB_XR, "x-unknown"),
1244            feedback(interceptor::RTCP_FB_XR, interceptor::RTCP_XR_ECN_SUMMARY),
1245        ];
1246        assert!(
1247            !ours.iter().any(|f| f.typ == interceptor::RTCP_FB_XR),
1248            "this endpoint registered no XR format"
1249        );
1250        assert_eq!(
1251            super::rtcp_feedback_intersection(&ours, &remote),
1252            vec![
1253                feedback("nack", ""),
1254                feedback(interceptor::RTCP_FB_XR, "pkt-loss-rle=1024"),
1255                feedback(interceptor::RTCP_FB_XR, "voip-metrics"),
1256                feedback(interceptor::RTCP_FB_XR, "stat-summary=loss,jitt"),
1257            ]
1258        );
1259        // Not without the remote side asking.
1260        assert_eq!(
1261            super::rtcp_feedback_intersection(&ours, &ours),
1262            vec![feedback("nack", "")]
1263        );
1264    }
1265}
1266
1267#[cfg(test)]
1268mod codec_dictionary_match_test {
1269    use super::{
1270        RTCRtpCodec, RTCRtpCodecParameters, codec_dictionary_match_with, encoding_send_codec,
1271    };
1272
1273    fn h264(fmtp: &str) -> RTCRtpCodec {
1274        RTCRtpCodec {
1275            mime_type: "video/H264".to_owned(),
1276            clock_rate: 90000,
1277            channels: 0,
1278            sdp_fmtp_line: fmtp.to_owned(),
1279            rtcp_feedback: vec![],
1280        }
1281    }
1282
1283    /// W3C webrtc 5.4 "codec dictionary match": an `sdpFmtpLine` on one side only is no
1284    /// match; lines that are not key-value are compared as strings; symmetrical parameters
1285    /// (H.264 profile, packetization mode) must be equal; the asymmetrical ones (the H.264
1286    /// level) too unless `ignoreAsymmetricalParameters`; a parameter left out is its
1287    /// inferred default.
1288    #[test]
1289    fn the_codec_dictionary_match_follows_the_w3c_algorithm() {
1290        let base = "level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f";
1291        let cases = [
1292            (base, base, true, true),
1293            // Order and case of the parameter names do not matter.
1294            (
1295                base,
1296                "PROFILE-LEVEL-ID=42e01f;packetization-mode=1;level-asymmetry-allowed=1",
1297                true,
1298                true,
1299            ),
1300            // Another level: asymmetrical.
1301            (
1302                base,
1303                "level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e034",
1304                false,
1305                true,
1306            ),
1307            // Another packetization mode: symmetrical.
1308            (
1309                base,
1310                "level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=42e01f",
1311                false,
1312                false,
1313            ),
1314            // Another profile: symmetrical.
1315            (
1316                base,
1317                "level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=640c1f",
1318                false,
1319                false,
1320            ),
1321            // An inferred default: packetization-mode=0 left out.
1322            (
1323                "packetization-mode=0;profile-level-id=42e01f",
1324                "profile-level-id=42e01f",
1325                true,
1326                true,
1327            ),
1328            // On one side only.
1329            (base, "", false, false),
1330        ];
1331        for (first, second, strict, ignoring) in cases {
1332            assert_eq!(
1333                codec_dictionary_match_with(&h264(first), &h264(second), false),
1334                strict,
1335                "{first} / {second}"
1336            );
1337            assert_eq!(
1338                codec_dictionary_match_with(&h264(first), &h264(second), true),
1339                ignoring,
1340                "{first} / {second}, ignoring asymmetrical parameters"
1341            );
1342        }
1343        let red = |fmtp: &str| RTCRtpCodec {
1344            mime_type: "audio/red".to_owned(),
1345            clock_rate: 48000,
1346            channels: 2,
1347            sdp_fmtp_line: fmtp.to_owned(),
1348            rtcp_feedback: vec![],
1349        };
1350        assert!(codec_dictionary_match_with(
1351            &red("111/111"),
1352            &red("111/111"),
1353            false
1354        ));
1355        assert!(!codec_dictionary_match_with(
1356            &red("111/111"),
1357            &red("111/111/111"),
1358            true
1359        ));
1360    }
1361
1362    /// W3C webrtc 4.4.1.6: an encoding's codec is the negotiated codec it matches with
1363    /// `ignoreAsymmetricalParameters` true. A codec of the same MIME type with another
1364    /// profile is no match (the mime-type-only fallback is gone); another level is.
1365    #[test]
1366    fn an_encoding_codec_matches_a_negotiated_one_by_the_dictionary_match() {
1367        let negotiated = vec![RTCRtpCodecParameters {
1368            rtp_codec: h264(
1369                "level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f",
1370            ),
1371            payload_type: 102,
1372        }];
1373        let other_level =
1374            h264("level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e034");
1375        assert_eq!(
1376            encoding_send_codec(&other_level, &negotiated).map(|c| c.payload_type),
1377            Some(102)
1378        );
1379        let other_profile =
1380            h264("level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=640c1f");
1381        assert_eq!(encoding_send_codec(&other_profile, &negotiated), None);
1382    }
1383}