Skip to main content

o_sfu_router/model/
rtp_negotiation.rs

1//! RTP capability matching between producers, routers, and consumers.
2//!
3//! Separates negotiation into two distinct stages to keep producer codecs
4//! decoupled from consumer capabilities:
5//!
6//! 1. **Ingress Normalization**: Producer formats are matched against router capabilities
7//!    to produce a standardized `Consumable` stream.
8//! 2. **Egress Selection**: Consumer capabilities are intersected with the `Consumable` stream
9//!    to determine supported formats, RTCP feedback, and congestion control modes.
10//!
11//! ```text
12//!                   Producer Stream                     Router Capabilities
13//!                          \                                   /
14//!                           v                                 v
15//!                +-------------------------------------------------------+
16//!                | Stage 1: Ingress Normalization                        |
17//!                | - Match primary codecs & assign router payload types  |
18//!                | - Remap RTX `apt` to negotiated primary payload types |
19//!                | - Intersect supported header extensions               |
20//!                +-------------------------------------------------------+
21//!                                            |
22//!                                            v
23//!                                Consumable MediaStream
24//!                                            |
25//!                                            +--------------------+
26//!                                            |                    |
27//!                                            v                    v
28//!                                  Consumer 1 Capabilities    Consumer 2 Capabilities
29//!                                            |                    |
30//!                                            v                    v
31//!                              +-----------------------+ +-----------------------+
32//!                              | Stage 2: Egress Match | | Stage 2: Egress Match |
33//!                              | - Codec intersection  | | - Codec intersection  |
34//!                              | - RTCP feedback match | | - RTCP feedback match |
35//!                              | - BWE policy (TWCC)   | | - BWE policy (REMB)   |
36//!                              +-----------------------+ +-----------------------+
37//!                                            |                    |
38//!                                            v                    v
39//!                                Consumer 1 Egress Stream    Consumer 2 Egress Stream
40//! ```
41//!
42//! This module operates purely on the typed domain model (`MediaStream`, `MediaFormat`,
43//! `HeaderExtension`, `StreamBinding`). Rules that depend on raw SDP session structure
44//! (m-line ordering, rejected m-sections, BUNDLE extmap consistency) are outside this module
45//! and belong at the signaling edge.
46
47use std::collections::HashSet;
48
49use o_sfu_rfc::rtp as rfc_rtp;
50
51#[cfg(any(test, feature = "test-support"))]
52use super::diagnostic::{ParseDiagnostic, ParseDiagnosticKind, ParseDiagnosticSpec, RfcReference};
53use super::{
54    CodecSetting, HeaderExtension, HeaderExtensionUri, MediaCapabilities, MediaCodec,
55    MediaCodecCapability, MediaFormat, MediaKind, MediaStream, PayloadType, RtcpFeedback,
56    RtcpFeedbackKind,
57};
58
59/// Failure raised while deriving or negotiating RTP parameters.
60#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
61pub enum RtpNegotiationError {
62    #[error("unsupported producer codec {codec_name} payload {payload_type}")]
63    UnsupportedProducerCodec {
64        codec_name: String,
65        payload_type: u8,
66    },
67    #[error("invalid apt parameter for codec {codec_name} payload {payload_type}")]
68    InvalidAptParameter {
69        codec_name: String,
70        payload_type: u8,
71    },
72    #[error("missing media codec for rtx payload {payload_type} apt {associated_payload_type}")]
73    MissingAssociatedMediaCodecForRtx {
74        payload_type: u8,
75        associated_payload_type: u8,
76    },
77    #[error("no compatible consumer codec")]
78    NoCompatibleConsumerCodec,
79}
80
81#[cfg(any(test, feature = "test-support"))]
82const RFC_3264_SECTION_6: RfcReference = RfcReference::new(
83    "RFC 3264",
84    "section 6",
85    "https://www.rfc-editor.org/rfc/rfc3264.html#section-6",
86);
87#[cfg(any(test, feature = "test-support"))]
88const RFC_4588_SECTION_8_1: RfcReference = RfcReference::new(
89    "RFC 4588",
90    "section 8.1",
91    "https://www.rfc-editor.org/rfc/rfc4588.html#section-8.1",
92);
93
94#[cfg(any(test, feature = "test-support"))]
95impl ParseDiagnostic for RtpNegotiationError {
96    fn diagnostic(&self) -> ParseDiagnosticSpec {
97        match self {
98            Self::UnsupportedProducerCodec { .. } => ParseDiagnosticSpec::new(
99                ParseDiagnosticKind::UnsupportedFeature,
100                "producer codec is valid but not supported by router capabilities",
101                RFC_3264_SECTION_6,
102                "capture producer media stream and router media capabilities and replay derive_consumable_rtp_parameters",
103            ),
104            Self::InvalidAptParameter { .. } => ParseDiagnosticSpec::new(
105                ParseDiagnosticKind::InvalidInput,
106                "RTX codec has an invalid or missing apt parameter",
107                RFC_4588_SECTION_8_1,
108                "capture producer media stream and replay derive_consumable_rtp_parameters to inspect RTX linkage",
109            ),
110            Self::MissingAssociatedMediaCodecForRtx { .. } => ParseDiagnosticSpec::new(
111                ParseDiagnosticKind::InvalidInput,
112                "RTX codec references an associated payload type that is not negotiated",
113                RFC_4588_SECTION_8_1,
114                "capture producer media stream and replay derive_consumable_rtp_parameters to inspect RTX linkage",
115            ),
116            Self::NoCompatibleConsumerCodec => ParseDiagnosticSpec::new(
117                ParseDiagnosticKind::UnsupportedFeature,
118                "consumer capabilities have no compatible media codec with the consumable set",
119                RFC_3264_SECTION_6,
120                "capture consumable media stream and consumer capabilities and replay negotiate_consumer_rtp_parameters",
121            ),
122        }
123    }
124}
125
126/// Derives the router-consumable media stream from producer parameters.
127///
128/// # Two-Pass Codec Resolution
129///
130/// Retransmission (RTX) formats depend on an associated primary codec via RFC 4588 `apt`.
131/// Negotiation therefore executes in two passes:
132/// 1. **Pass 1 (Primary Codecs)**: Match primary media formats against router capabilities,
133///    assigning router-normalized payload types and building a translation map.
134/// 2. **Pass 2 (RTX Codecs)**: Match RTX repair formats, resolve their `apt` references against
135///    the translation map, and omit valid formats with no matching router RTX capability.
136///
137/// ```text
138/// Incoming Producer Formats:
139///   [ Format 0: RTX (PT 97, apt=96) ] <---+ (references PT 96)
140///   [ Format 1: VP8 (PT 96)         ] ----+
141///
142/// Pass 1: Primary Codec Matching (Skip RTX)
143///   Format 1 (VP8, PT 96) matches Router Capability (VP8, PT 100)
144///     ==> Consumable Primary: VP8 (PT 100)
145///     ==> Translation Map: [ Producer PT 96 -> Router PT 100 ]
146///
147/// Pass 2: RTX Matching & `apt` Rewriting
148///   Format 0 (RTX, PT 97, apt=96):
149///     - Lookup `apt=96` in Translation Map ==> matches Router PT 100
150///     - Match Router Capability for RTX with apt=100 ==> Router PT 101
151///     ==> Consumable Repair: RTX (PT 101, apt=100)
152///
153/// Final Consumable Stream:
154///   [ Primary: VP8 (PT 100) ] + [ Repair: RTX (PT 101, apt=100) ]
155/// ```
156///
157/// The final repair pair is retained only when the primary format also retains Generic NACK.
158///
159/// # Errors
160///
161/// Returns [`RtpNegotiationError::UnsupportedProducerCodec`] when a producer media codec does not
162/// match any router media codec capability, [`RtpNegotiationError::InvalidAptParameter`] when a
163/// RTX codec carries an invalid `apt` parameter, or
164/// [`RtpNegotiationError::MissingAssociatedMediaCodecForRtx`] when a RTX codec references a media
165/// payload that is not part of the negotiated media codec set.
166pub fn derive_consumable_rtp_parameters(
167    producer_parameters: &MediaStream,
168    capabilities: &MediaCapabilities,
169) -> Result<MediaStream, RtpNegotiationError> {
170    // Maps the producer's original primary payload type to the router-visible
171    // payload type chosen for the consumable stream.
172    //
173    // This exists for two reasons:
174    // - RTX `apt` must be rewritten to point at the negotiated primary PT.
175    // - payload-type-bound stream bindings must keep pointing at the negotiated PT,
176    //   not the producer's original PT.
177    let mut producer_to_router_payload_types = Vec::<(PayloadType, PayloadType)>::new();
178    let mut consumable_formats = Vec::new();
179
180    // Primary media codecs are the actual media contract.
181    // If a producer format has no router capability match, the router would not be
182    // able to describe or forward that media in its consumable model, so we reject
183    // the whole producer stream instead of silently dropping the codec.
184    for format in producer_parameters.formats() {
185        // RFC 4588 section 8.1 binds RTX to an already-negotiated primary PT
186        // through `apt`, so media codecs must be matched first.
187        // https://www.rfc-editor.org/rfc/rfc4588.html#section-8.1
188        if format.codec().is_rtx() {
189            continue;
190        }
191        let Some(capability_format) = find_matching_media_capability(format, capabilities) else {
192            // RFC 3264 section 6 only allows formats that both sides support to survive
193            // negotiation, so a producer codec with no router capability match is rejected.
194            // https://www.rfc-editor.org/rfc/rfc3264.html#section-6
195            return Err(RtpNegotiationError::UnsupportedProducerCodec {
196                codec_name: format.codec().as_str().to_owned(),
197                payload_type: format.payload_type(),
198            });
199        };
200        let negotiated_payload_type = negotiated_payload_type(capability_format, format);
201        producer_to_router_payload_types.push((format.payload_type_id(), negotiated_payload_type));
202        let feedback =
203            intersect_feedback(format.rtcp_feedback(), capability_format.rtcp_feedback());
204        consumable_formats.push(format_with_overrides(
205            format,
206            negotiated_payload_type,
207            None,
208            &feedback,
209        ));
210    }
211
212    for format in producer_parameters.formats() {
213        if !format.codec().is_rtx() {
214            continue;
215        }
216        let associated_payload_type = parse_rtx_associated_payload(format)?;
217        let Some(negotiated_associated_payload_type) = producer_to_router_payload_types
218            .iter()
219            .find_map(|(original, mapped)| {
220                (*original == associated_payload_type).then_some(*mapped)
221            })
222        else {
223            // RFC 4588 section 8.1 makes RTX invalid without a negotiated
224            // associated payload type.
225            // https://www.rfc-editor.org/rfc/rfc4588.html#section-8.1
226            return Err(RtpNegotiationError::MissingAssociatedMediaCodecForRtx {
227                payload_type: format.payload_type(),
228                associated_payload_type: associated_payload_type.value(),
229            });
230        };
231        let Some(capability_format) =
232            find_matching_rtx_capability(format, negotiated_associated_payload_type, capabilities)
233        else {
234            // Unlike a primary media codec, RTX is an auxiliary retransmission format.
235            // If the router does not support this RTX pairing, the media stream can still
236            // remain valid without retransmission support, so we drop RTX rather than fail
237            // the whole negotiation.
238            continue;
239        };
240        let negotiated_payload_type = negotiated_payload_type(capability_format, format);
241        let feedback =
242            intersect_feedback(format.rtcp_feedback(), capability_format.rtcp_feedback());
243        consumable_formats.push(format_with_overrides(
244            format,
245            negotiated_payload_type,
246            Some(negotiated_associated_payload_type),
247            &feedback,
248        ));
249    }
250    normalize_nack_rtx(&mut consumable_formats);
251
252    let header_extensions = capabilities
253        .header_extensions()
254        .filter(|extension| {
255            // RFC 8285 negotiates header extensions by common support. Keep only producer-backed
256            // URIs here because the runtime only forwards observed extension values
257            // https://www.rfc-editor.org/rfc/rfc8285.html#section-5
258            producer_parameters
259                .header_extensions()
260                .any(|producer_extension| producer_extension.uri_kind() == extension.uri_kind())
261        })
262        .cloned()
263        .collect::<Vec<_>>();
264    let bindings = producer_parameters
265        .bindings()
266        .cloned()
267        .map(|binding| binding.with_payload_type_mapping(&producer_to_router_payload_types))
268        .collect::<Vec<_>>();
269
270    let mut consumable = MediaStream::new(consumable_formats, header_extensions, bindings);
271    if let Some(mid) = producer_parameters.mid() {
272        consumable = consumable.with_mid(mid);
273    }
274    Ok(consumable)
275}
276
277/// Negotiates the consumer-facing stream from a consumable stream.
278///
279/// Algorithm:
280/// 1. Intersect header extensions.
281/// 2. Derive the BWE feedback policy from surviving extensions.
282/// 3. negotiate primary media codecs first
283/// 4. Admit RTX only when its primary codec survived
284/// 5. Filter bindings so they only reference negotiated payload types.
285///
286/// The output keeps consumable payload types rather than adopting arbitrary
287/// consumer capability PT numbers, because the consumable stream is already the
288/// router's negotiated forwarding model
289///
290/// # Errors
291///
292/// Returns [`RtpNegotiationError::NoCompatibleConsumerCodec`] when no compatible media codec can
293/// be negotiated.
294pub fn negotiate_consumer_rtp_parameters(
295    consumable_parameters: &MediaStream,
296    consumer_capabilities: &MediaCapabilities,
297) -> Result<MediaStream, RtpNegotiationError> {
298    let negotiated_header_extensions =
299        negotiate_header_extensions(consumable_parameters, consumer_capabilities);
300    let feedback_policy = bwe_feedback_policy(&negotiated_header_extensions);
301
302    let mut negotiated_formats = consumable_parameters
303        .formats()
304        .filter_map(|format| {
305            // RFC 4588 section 8.1 requires a surviving primary codec before
306            // RTX can be admitted, so the first pass negotiates primary formats.
307            // https://www.rfc-editor.org/rfc/rfc4588.html#section-8.1
308            if format.codec().is_rtx() {
309                return None;
310            }
311            let capability_format = find_matching_media_capability(format, consumer_capabilities)?;
312            let feedback =
313                intersect_feedback(format.rtcp_feedback(), capability_format.rtcp_feedback());
314            let feedback = apply_bwe_feedback_policy(feedback, feedback_policy);
315            Some(format_with_overrides(
316                format,
317                format.payload_type_id(),
318                None,
319                &feedback,
320            ))
321        })
322        .collect::<Vec<_>>();
323
324    if negotiated_formats.is_empty() {
325        // RFC 3264 section 6 requires at least one mutually acceptable media format for an
326        // accepted stream, so a consumer with no surviving media codec is incompatible.
327        // https://www.rfc-editor.org/rfc/rfc3264.html#section-6
328        return Err(RtpNegotiationError::NoCompatibleConsumerCodec);
329    }
330
331    for format in consumable_parameters.formats() {
332        if !format.codec().is_rtx() {
333            continue;
334        }
335        let Some(capability_format) = find_matching_consumer_rtx_capability(
336            format,
337            &negotiated_formats,
338            consumer_capabilities,
339        ) else {
340            continue;
341        };
342        let feedback =
343            intersect_feedback(format.rtcp_feedback(), capability_format.rtcp_feedback());
344        let feedback = apply_bwe_feedback_policy(feedback, feedback_policy);
345        negotiated_formats.push(format_with_overrides(
346            format,
347            format.payload_type_id(),
348            None,
349            &feedback,
350        ));
351    }
352    normalize_nack_rtx(&mut negotiated_formats);
353
354    let bindings = consumable_parameters
355        .bindings()
356        .filter(|binding| {
357            binding.payload_type_id().is_none_or(|payload_type| {
358                formats_contain_payload_type(&negotiated_formats, payload_type)
359            })
360        })
361        .cloned()
362        .collect::<Vec<_>>();
363
364    let mut negotiated =
365        MediaStream::new(negotiated_formats, negotiated_header_extensions, bindings);
366    if let Some(mid) = consumable_parameters.mid() {
367        negotiated = negotiated.with_mid(mid);
368    }
369    Ok(negotiated)
370}
371
372/// Payload-type policy:
373///
374/// - if the capability pins an explicit PT, that PT becomes authoritative in the
375///   negotiated stream
376/// - otherwise we preserve the source PT
377///
378/// This keeps PT assignment under capability control without forcing every
379/// capability entry to hardcode payload types.
380fn negotiated_payload_type(
381    capability_format: &MediaCodecCapability,
382    format: &MediaFormat,
383) -> PayloadType {
384    capability_format
385        .payload_type_id()
386        .unwrap_or(format.payload_type_id())
387}
388
389/// Media capability matching ignores payload type.
390/// PT is negotiated output state, not an identity key for codec compatibility.
391///
392/// Compatibility is instead based on the codec's media kind, codec name,
393/// clock rate, normalized channel count, and codec-specific critical fmtp
394/// parameters.
395fn find_matching_media_capability<'a>(
396    format: &MediaFormat,
397    capabilities: &'a MediaCapabilities,
398) -> Option<&'a MediaCodecCapability> {
399    capabilities.codecs().find(|capability_format| {
400        !capability_format.codec().is_rtx()
401            && codec_match_ignoring_payload_type(format, capability_format)
402    })
403}
404
405/// RTX matching has one extra constraint beyond ordinary codec matching:
406///
407/// the router RTX capability must be associated with the already negotiated
408/// primary payload type, because RFC 4588 binds RTX to a specific primary PT
409/// through `apt`.
410/// <https://www.rfc-editor.org/rfc/rfc4588.html#section-8.1>
411fn find_matching_rtx_capability<'a>(
412    format: &MediaFormat,
413    negotiated_associated_payload_type: PayloadType,
414    capabilities: &'a MediaCapabilities,
415) -> Option<&'a MediaCodecCapability> {
416    capabilities.codecs().find(|capability_format| {
417        capability_format.codec().is_rtx()
418            && codec_match_ignoring_payload_type(format, capability_format)
419            && capability_format.rtx_associated_payload_type_id()
420                == Some(negotiated_associated_payload_type)
421    })
422}
423
424/// Consumer-side RTX matching works against the already-consumable stream.
425/// At this point the stream's `apt` must refer to a primary PT that survived
426/// consumer negotiation, otherwise forwarding RTX would create an orphan repair
427/// stream with no valid primary target
428fn find_matching_consumer_rtx_capability<'a>(
429    format: &MediaFormat,
430    negotiated_formats: &[MediaFormat],
431    capabilities: &'a MediaCapabilities,
432) -> Option<&'a MediaCodecCapability> {
433    let associated_payload_type = parse_rtx_associated_payload(format).ok()?;
434    // RFC 4588 section 8.1 ties each RTX format to one negotiated primary PT.
435    // https://www.rfc-editor.org/rfc/rfc4588.html#section-8.1
436    if !formats_contain_primary_payload_type(negotiated_formats, associated_payload_type) {
437        return None;
438    }
439    capabilities.codecs().find(|capability_format| {
440        capability_format.codec().is_rtx()
441            && codec_match_ignoring_payload_type(format, capability_format)
442            && capability_format.rtx_associated_payload_type_id() == Some(associated_payload_type)
443    })
444}
445
446/// Returns whether two formats describe the same codec configuration, ignoring PT
447///
448/// In RTP/SDP, payload type is only a local number bound to a codec description;
449/// it is not itself the codec identity. Compatibility therefore comes from the
450/// semantic codec fields and any fmtp parameters that change the wire format
451fn codec_match_ignoring_payload_type(
452    format: &MediaFormat,
453    capability_format: &MediaCodecCapability,
454) -> bool {
455    if format.media_kind() != capability_format.media_kind()
456        || format.codec() != capability_format.codec()
457        || format.clock_rate() != capability_format.clock_rate()
458    {
459        return false;
460    }
461    if normalized_channels(format.media_kind(), format.channels())
462        != normalized_channels(capability_format.media_kind(), capability_format.channels())
463    {
464        return false;
465    }
466    critical_codec_settings_match(format, capability_format)
467}
468
469/// Only settings that actually affect wire compatibility are treated as hard
470/// negotiation keys here.
471///
472/// Receiver preferences or advisory parameters are not all compatibility
473/// blockers because this module is trying to answer "can the
474/// formats interoperate?" rather than "are all local preferences identical?"
475fn critical_codec_settings_match(
476    format: &MediaFormat,
477    capability_format: &MediaCodecCapability,
478) -> bool {
479    match format.codec() {
480        MediaCodec::H264 => h264_critical_settings_match(format, capability_format),
481        MediaCodec::Vp9 => vp9_critical_settings_match(format, capability_format),
482        _ => true,
483    }
484}
485
486/// `packetization-mode` is a hard compatibility key.
487/// Different packetization modes describe different RTP packetization behaviour,
488/// so mismatches are not just preferences
489fn h264_critical_settings_match(
490    format: &MediaFormat,
491    capability_format: &MediaCodecCapability,
492) -> bool {
493    let Some(format_packetization_mode) = h264_packetization_mode(format.settings()) else {
494        return false;
495    };
496    let Some(capability_packetization_mode) = h264_packetization_mode(capability_format.settings())
497    else {
498        return false;
499    };
500    // RFC 6184 section 8.2.2 requires packetization-mode compatibility, mismatched packetization
501    // modes describe different wire behaviors and are therefore rejected.
502    // https://www.rfc-editor.org/rfc/rfc6184.html#section-8.2.2
503    if format_packetization_mode != capability_packetization_mode {
504        return false;
505    }
506    let format_profile_level_id = format
507        .settings()
508        .find_map(|setting| match setting {
509            CodecSetting::H264ProfileLevelId(profile_level_id) => Some(profile_level_id.as_str()),
510            _ => None,
511        })
512        .unwrap_or(rfc_rtp::fmtp::H264_DEFAULT_PROFILE_LEVEL_ID);
513    let capability_profile_level_id = capability_format
514        .settings()
515        .find_map(|setting| match setting {
516            CodecSetting::H264ProfileLevelId(profile_level_id) => Some(profile_level_id.as_str()),
517            _ => None,
518        })
519        .unwrap_or(rfc_rtp::fmtp::H264_DEFAULT_PROFILE_LEVEL_ID);
520    let Some(parsed_format_profile_level_id) =
521        rfc_rtp::h264::ProfileLevelId::parse(format_profile_level_id)
522    else {
523        return false;
524    };
525    let Some(parsed_capability_profile_level_id) =
526        rfc_rtp::h264::ProfileLevelId::parse(capability_profile_level_id)
527    else {
528        return false;
529    };
530    parsed_format_profile_level_id.profile() == parsed_capability_profile_level_id.profile()
531        && parsed_format_profile_level_id.level() <= parsed_capability_profile_level_id.level()
532}
533
534fn h264_packetization_mode<'a>(
535    settings: impl Iterator<Item = &'a CodecSetting>,
536) -> Option<rfc_rtp::h264::PacketizationMode> {
537    for setting in settings {
538        match setting {
539            CodecSetting::H264PacketizationMode(mode) => return Some(*mode),
540            CodecSetting::Other { key, .. } if key == rfc_rtp::fmtp::H264_PACKETIZATION_MODE => {
541                return None;
542            }
543            _ => {}
544        }
545    }
546    rfc_rtp::h264::PacketizationMode::from_fmtp_value(
547        rfc_rtp::fmtp::H264_DEFAULT_PACKETIZATION_MODE,
548    )
549}
550
551fn vp9_critical_settings_match(
552    format: &MediaFormat,
553    capability_format: &MediaCodecCapability,
554) -> bool {
555    effective_vp9_profile_id(format.settings())
556        .zip(effective_vp9_profile_id(capability_format.settings()))
557        .is_some_and(|(format_profile, capability_profile)| format_profile == capability_profile)
558}
559
560fn effective_vp9_profile_id<'a>(
561    settings: impl Iterator<Item = &'a CodecSetting>,
562) -> Option<rfc_rtp::Vp9ProfileId> {
563    let mut profile_id = None;
564    for setting in settings {
565        match setting {
566            CodecSetting::Vp9ProfileId(value) => profile_id = Some(*value),
567            CodecSetting::Other { key, .. } if key == rfc_rtp::fmtp::VP9_PROFILE_ID => return None,
568            _ => {}
569        }
570    }
571    Some(profile_id.unwrap_or(rfc_rtp::fmtp::VP9_DEFAULT_PROFILE_ID))
572}
573
574/// `apt` is not optional metadata for RTX.
575/// It is the linkage that says which primary payload type this repair stream
576/// protects. Without it, the RTX format is structurally invalid for negotiation.
577fn parse_rtx_associated_payload(format: &MediaFormat) -> Result<PayloadType, RtpNegotiationError> {
578    format.rtx_associated_payload_type_id().ok_or_else(|| {
579        RtpNegotiationError::InvalidAptParameter {
580            codec_name: format.codec().as_str().to_owned(),
581            payload_type: format.payload_type(),
582        }
583    })
584}
585
586/// Rebuild the format from the source while applying negotiated overrides.
587///
588/// We copy all original codec settings except RTX `apt`, because `apt` may need
589/// to be rewritten after payload-type remapping. RTCP feedback is also rebuilt
590/// from the negotiated intersection rather than just copied, so the result
591/// only advertises mutually supported feedback mechanisms.
592fn format_with_overrides(
593    source: &MediaFormat,
594    payload_type: PayloadType,
595    apt_override: Option<PayloadType>,
596    feedback: &[RtcpFeedback],
597) -> MediaFormat {
598    let mut format = MediaFormat::new(
599        source.media_kind(),
600        source.codec().clone(),
601        payload_type,
602        source.clock_rate(),
603    );
604    if let Some(channels) = source.channels() {
605        format = format.with_channels(channels);
606    }
607    for setting in source
608        .settings()
609        .filter(|setting| !matches!(setting, CodecSetting::RtxAssociation(_)))
610        .cloned()
611    {
612        format = format.with_setting(setting);
613    }
614    if let Some(apt) = apt_override {
615        format = format.with_setting(CodecSetting::RtxAssociation(apt));
616    } else if let Some(apt) = source.rtx_associated_payload_type_id() {
617        format = format.with_setting(CodecSetting::RtxAssociation(apt));
618    }
619    for entry in feedback {
620        format = format.with_rtcp_feedback(entry.clone());
621    }
622    format
623}
624
625/// RTCP feedback is negotiated by common support, not by union.
626/// Advertising feedback that only one side supports would let later code assume
627/// a control signal is usable when the peer never negotiated it.
628/// <https://www.rfc-editor.org/rfc/rfc4585.html#section-4.2>
629fn intersect_feedback<'a>(
630    format_feedback: impl Iterator<Item = &'a RtcpFeedback>,
631    capability_feedback: impl Iterator<Item = &'a RtcpFeedback>,
632) -> Vec<RtcpFeedback> {
633    let capability_feedback = capability_feedback.cloned().collect::<Vec<_>>();
634    format_feedback
635        .filter(|feedback| capability_feedback.contains(feedback))
636        .cloned()
637        .collect()
638}
639
640fn normalize_nack_rtx(formats: &mut Vec<MediaFormat>) {
641    // RFC 4585 negotiates Generic NACK per format and RFC 4588 links RTX through
642    // `apt`. O-SFU policy exposes repair only as a complete pair. It keeps the
643    // first matching RTX, drops duplicates and orphans then removes Generic
644    // NACK when no repair remains.
645    // https://www.rfc-editor.org/rfc/rfc4585.html#section-4.2
646    // https://www.rfc-editor.org/rfc/rfc4588.html#section-8.1
647    let nack_payload_types = formats
648        .iter()
649        .filter(|format| !format.codec().is_rtx() && has_generic_nack(format))
650        .map(MediaFormat::payload_type_id)
651        .collect::<HashSet<_>>();
652    let mut paired_payload_types = HashSet::new();
653    formats.retain(|format| {
654        !format.codec().is_rtx()
655            || format.rtx_associated_payload_type_id().is_some_and(|apt| {
656                nack_payload_types.contains(&apt) && paired_payload_types.insert(apt)
657            })
658    });
659
660    for format in formats.iter_mut() {
661        if format.codec().is_rtx()
662            || !has_generic_nack(format)
663            || paired_payload_types.contains(&format.payload_type_id())
664        {
665            continue;
666        }
667        let feedback = format
668            .rtcp_feedback()
669            .filter(|feedback| !matches!(feedback.kind(), RtcpFeedbackKind::Nack))
670            .cloned()
671            .collect::<Vec<_>>();
672        *format = format_with_overrides(format, format.payload_type_id(), None, &feedback);
673    }
674}
675
676fn has_generic_nack(format: &MediaFormat) -> bool {
677    format
678        .rtcp_feedback()
679        .any(|feedback| matches!(feedback.kind(), RtcpFeedbackKind::Nack))
680}
681
682/// Channel count is only part of codec identity for audio.
683/// Video formats do not use RTP channel count semantics in this model, so we
684/// normalize all video channel counts away to avoid spurious mismatches.
685fn normalized_channels(media_kind: MediaKind, channels: Option<u16>) -> Option<u16> {
686    if media_kind == MediaKind::Audio {
687        Some(channels.unwrap_or(1))
688    } else {
689        None
690    }
691}
692
693/// This is a URI-level capability intersection only.
694///
695/// It does NOT perform full SDP extmap negotiation:
696/// - no direction filtering
697/// - no id collision checks
698/// - no BUNDLE-wide extmap consistency checks
699///
700/// Those rules belong to the SDP/signaling edge. This helper only answers
701/// whether the typed RTP model should keep an extension URI at all.
702fn negotiate_header_extensions(
703    consumable_parameters: &MediaStream,
704    consumer_capabilities: &MediaCapabilities,
705) -> Vec<HeaderExtension> {
706    consumable_parameters
707        .header_extensions()
708        // RFC 8285 extmaps are negotiated by common support. This helper keeps the
709        // router model at URI-intersection scope and leaves direction/id validation to the SDP edge.
710        // https://www.rfc-editor.org/rfc/rfc8285.html#section-5
711        .filter(|extension| {
712            consumer_capabilities
713                .header_extensions()
714                .any(|supported| supported.uri_kind() == extension.uri_kind())
715        })
716        .cloned()
717        .collect()
718}
719
720fn formats_contain_payload_type(formats: &[MediaFormat], payload_type: PayloadType) -> bool {
721    formats
722        .iter()
723        .any(|format| format.payload_type_id() == payload_type)
724}
725
726fn formats_contain_primary_payload_type(
727    formats: &[MediaFormat],
728    payload_type: PayloadType,
729) -> bool {
730    formats
731        .iter()
732        .any(|format| !format.codec().is_rtx() && format.payload_type_id() == payload_type)
733}
734
735#[derive(Debug, Clone, Copy, PartialEq, Eq)]
736enum BweFeedbackPolicy {
737    PreferTransportCc,
738    PreferGoogRemb,
739    DisableBoth,
740}
741
742/// Selects a local forwarding policy for mutually exclusive bandwidth-estimation
743/// feedback families.
744///
745/// Resolves conflicting congestion control feedback modes by removing feedback only:
746/// - if transport-wide CC is available, prefer `transport-cc` and strip `goog-remb`
747/// - otherwise, if abs-send-time is available, prefer `goog-remb` and strip `transport-cc`
748/// - otherwise strip both feedback families
749///
750/// ```text
751///                Negotiated Header Extensions
752///                             |
753///            +----------------+----------------+
754///            |                                 |
755///   Contains TWCC extension?          Otherwise abs-send-time?
756///            |                                 |
757///            v (yes)                           v (yes)
758///  [ PreferTransportCc ]              [ PreferGoogRemb ]
759///            |                                 |
760///            v                                 v
761///  - Keep `transport-cc` feedback     - Keep `goog-remb` feedback
762///  - Strip conflicting `goog-remb`    - Strip `transport-cc`
763/// ```
764///
765/// If neither extension is present, [`BweFeedbackPolicy::DisableBoth`] strips both families.
766fn bwe_feedback_policy(header_extensions: &[HeaderExtension]) -> BweFeedbackPolicy {
767    if header_extensions.iter().any(|extension| {
768        matches!(
769            extension.uri_kind(),
770            HeaderExtensionUri::TransportWideCcDraft01
771        )
772    }) {
773        return BweFeedbackPolicy::PreferTransportCc;
774    }
775    if header_extensions
776        .iter()
777        .any(|extension| matches!(extension.uri_kind(), HeaderExtensionUri::AbsSendTime))
778    {
779        return BweFeedbackPolicy::PreferGoogRemb;
780    }
781    BweFeedbackPolicy::DisableBoth
782}
783
784/// Negotiation may leave both transport-cc and goog-remb present in the raw
785/// RTCP feedback intersection. We filter here so downstream sender logic sees one
786/// coherent bandwidth-estimation mode instead of multiple competing ones.
787fn apply_bwe_feedback_policy(
788    feedback: Vec<RtcpFeedback>,
789    policy: BweFeedbackPolicy,
790) -> Vec<RtcpFeedback> {
791    feedback
792        .into_iter()
793        .filter(|entry| match policy {
794            BweFeedbackPolicy::PreferTransportCc => {
795                !matches!(entry.kind(), RtcpFeedbackKind::GoogRemb)
796            }
797            BweFeedbackPolicy::PreferGoogRemb => {
798                !matches!(entry.kind(), RtcpFeedbackKind::TransportCc)
799            }
800            BweFeedbackPolicy::DisableBoth => !matches!(
801                entry.kind(),
802                RtcpFeedbackKind::TransportCc | RtcpFeedbackKind::GoogRemb
803            ),
804        })
805        .collect()
806}