Skip to main content

str0m/format/
payload_params.rs

1// Changed by Alakazam Labs for sew-str0m; the fork's patches are listed in its README.
2use serde::{Deserialize, Serialize};
3use std::collections::HashSet;
4use std::ops::RangeInclusive;
5
6use crate::packet::H264ProfileLevel;
7use crate::packet::H265ProfileTierLevel;
8use crate::packet::H266ProfileTierLevel;
9use crate::rtp_::Pt;
10
11use super::codec::{Codec, CodecSpec};
12use super::format_params::FormatParams;
13
14/// Preferred ranges for dynamic payload type allocation.
15pub(crate) const PREFERED_RANGES: &[RangeInclusive<usize>] = &[
16    // Payload identifiers 96–127 are used for payloads defined dynamically during a session.
17    96..=127,
18    // "unassigned" ranged. note that RTCP packet type 207 (XR, Extended Reports) would be
19    // indistinguishable from RTP payload types 79 with the marker bit set
20    80..=95,
21    77..=78,
22    // reserved because RTCP packet types 200–204 would otherwise be indistinguishable
23    // from RTP payload types 72–76
24    // 72..77,
25    // lol range.
26    35..=71,
27];
28
29pub(crate) trait Claimed {
30    fn assert_claim_once(&mut self, pt: Pt) -> bool;
31    fn is_claimed(&self, pt: Pt) -> bool;
32    fn find_unclaimed(
33        &self,
34        ranges: &[RangeInclusive<usize>],
35        unlocked: &HashSet<Pt>,
36    ) -> Option<Pt>;
37}
38
39impl Claimed for [bool; 128] {
40    fn assert_claim_once(&mut self, pt: Pt) -> bool {
41        let idx = *pt as usize;
42        if self[idx] {
43            warn!("Ignore already claimed PT {}", pt);
44            return false;
45        }
46        self[idx] = true;
47        true
48    }
49    fn is_claimed(&self, pt: Pt) -> bool {
50        let idx = *pt as usize;
51        self[idx]
52    }
53    fn find_unclaimed(
54        &self,
55        ranges: &[RangeInclusive<usize>],
56        unlocked: &HashSet<Pt>,
57    ) -> Option<Pt> {
58        for range in ranges {
59            for i in range.clone() {
60                if !self[i] && !unlocked.contains(&(i as u8).into()) {
61                    let pt: Pt = (i as u8).into();
62                    return Some(pt);
63                }
64            }
65        }
66
67        // Failed to find unclaimed PT.
68        None
69    }
70}
71
72/// Group of parameters for a payload type (PT).
73///
74/// In the SDP a payload type has a number of associated parameters. See example below:
75///
76/// ```text
77/// a=rtpmap:96 H264/90000
78/// a=rtcp-fb:96 goog-remb
79/// a=rtcp-fb:96 transport-cc
80/// a=rtcp-fb:96 ccm fir
81/// a=rtcp-fb:96 nack
82/// a=rtcp-fb:96 nack pli
83/// a=fmtp:96 level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=42001f
84/// ```
85#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
86pub struct PayloadParams {
87    /// The payload type that groups these parameters.
88    pub(crate) pt: Pt,
89
90    /// Whether these parameters are repairing some other set of parameters.
91    /// This is used to, via PT, separate RTX resend streams from the main stream.
92    pub(crate) resend: Option<Pt>,
93
94    /// The codec with settings for this group of parameters.
95    pub(crate) spec: CodecSpec,
96
97    /// Whether the payload use the TWCC feedback mechanic.
98    pub(crate) fb_transport_cc: bool,
99
100    /// Whether the payload uses NACK to request resends.
101    pub(crate) fb_nack: bool,
102
103    /// Whether the payload uses the PLI (Picture Loss Indication) mechanic.
104    pub(crate) fb_pli: bool,
105
106    /// Whether the payload uses the FIR (Full Intra Request) mechanic.
107    pub(crate) fb_fir: bool,
108
109    /// Whether the payload uses the REMB (Receiver Estimated Maximum Bitrate) mechanic.
110    pub(crate) fb_remb: bool,
111
112    /// The RFC 2198 RED payload type that wraps this primary codec, if negotiated.
113    /// Like `resend`, this links a secondary PT to this primary via SDP.
114    pub(crate) red: Option<Pt>,
115
116    /// Whether the payload is locked by negotiation or can still be debated.
117    ///
118    /// If we make an OFFER or ANSWER and the direction is sendrecv/recvonly, the parameters are locked
119    /// can't be further changed. If we make an OFFER for a sendonly, the parameters are only proposed
120    /// and don't lock.
121    pub(crate) locked: bool,
122
123    /// Whether these parameters were locked without RTX of our own (`resend` was `None` when
124    /// they locked), so a remote RTX payload type is never adopted for them, even after locking.
125    #[serde(default)]
126    pub(crate) rtx_declined: bool,
127}
128
129// we don't want to compare "locked"
130impl PartialEq for PayloadParams {
131    fn eq(&self, other: &Self) -> bool {
132        self.pt == other.pt
133            && self.resend == other.resend
134            && self.spec == other.spec
135            && self.fb_transport_cc == other.fb_transport_cc
136            && self.fb_nack == other.fb_nack
137            && self.fb_pli == other.fb_pli
138            && self.fb_fir == other.fb_fir
139            && self.fb_remb == other.fb_remb
140            && self.red == other.red
141    }
142}
143
144impl Eq for PayloadParams {}
145
146impl PayloadParams {
147    /// Maximum match score.
148    ///
149    /// This is returned for an exact `CodecSpec` match in `match_score()`. It is also used as the
150    /// starting point for codec-specific scoring in this file:
151    /// - Opus/H.264/H.265 decrement from a perfect match.
152    /// - VP9/AV1 return the max score when their relevant fmtp parameters match.
153    /// - VP8 currently only matches via the exact `CodecSpec` equality fast-path (no fuzzy scorer).
154    const EXACT_MATCH_SCORE: usize = 100;
155
156    /// Score used for H.265 profile-only compatibility matches.
157    ///
158    /// Some endpoints (notably browsers) may signal H.265 using only `profile-id` without
159    /// tier/level information; when we can only validate profile equality we return this lower
160    /// score so full ProfileTierLevel matches win when available.
161    const PROFILE_ONLY_MATCH_SCORE: usize = 90;
162
163    /// Creates new payload params.
164    ///
165    /// * `pt` is the payload type RTP mapping in the session.
166    /// * `resend` is the payload type used for (RTX) resend channel.
167    /// * `spec` configures details about the codec.
168    pub fn new(pt: Pt, resend: Option<Pt>, spec: CodecSpec) -> Self {
169        let is_video = spec.codec.is_video();
170
171        PayloadParams {
172            pt,
173            resend,
174
175            spec,
176
177            // Both audio and video use TWCC
178            fb_transport_cc: true,
179
180            // Only true for video.
181            fb_fir: is_video,
182            fb_nack: is_video,
183            fb_pli: is_video,
184            fb_remb: is_video,
185
186            red: None,
187            locked: false,
188            rtx_declined: false,
189        }
190    }
191
192    /// Creates minimal payload params for SSRC 0 BWE probes.
193    ///
194    /// These probes don't carry real media, only padding for bandwidth estimation.
195    /// Uses 90kHz clock rate (video rate) and enables only transport_cc feedback.
196    pub(crate) fn new_probe(pt: Pt) -> Self {
197        use super::codec::Codec;
198        use super::format_params::FormatParams;
199        use crate::rtp_::Frequency;
200
201        PayloadParams {
202            pt,
203            resend: None,
204            spec: CodecSpec {
205                codec: Codec::Null,
206                clock_rate: Frequency::NINETY_KHZ,
207                channels: None,
208                format: FormatParams::default(),
209            },
210            fb_transport_cc: true,
211            fb_nack: false,
212            fb_pli: false,
213            fb_fir: false,
214            fb_remb: false,
215            red: None,
216            locked: false,
217            rtx_declined: false,
218        }
219    }
220
221    /// The payload type that groups these parameters.
222    pub fn pt(&self) -> Pt {
223        self.pt
224    }
225
226    /// Whether these parameters are repairing some other set of parameters.
227    /// This is used to, via PT, separate RTX resend streams from the main stream.
228    pub fn resend(&self) -> Option<Pt> {
229        self.resend
230    }
231
232    /// Sets the RTX resend payload type. Use `None` to disable RTX, in which
233    /// case retransmissions (if NACK is enabled) are sent in-band on the main SSRC.
234    pub fn set_resend(&mut self, resend: Option<Pt>) {
235        self.resend = resend;
236    }
237
238    /// The codec with settings for this group of parameters.
239    pub fn spec(&self) -> CodecSpec {
240        self.spec
241    }
242
243    /// Sets whether the payload use the TWCC feedback mechanic.
244    pub fn set_fb_transport_cc(&mut self, fb_transport_cc: bool) {
245        self.fb_transport_cc = fb_transport_cc
246    }
247
248    /// Whether the payload use the TWCC feedback mechanic.
249    pub fn fb_transport_cc(&self) -> bool {
250        self.fb_transport_cc
251    }
252
253    /// Sets whether the payload uses NACK to request resends.
254    pub fn set_fb_nack(&mut self, fb_nack: bool) {
255        self.fb_nack = fb_nack
256    }
257
258    /// Whether the payload uses NACK to request resends.
259    pub fn fb_nack(&self) -> bool {
260        self.fb_nack
261    }
262
263    /// Set whether the payload uses the PLI (Picture Loss Indication) mechanic.
264    pub fn set_fb_pli(&mut self, fb_pli: bool) {
265        self.fb_pli = fb_pli
266    }
267
268    /// Whether the payload uses the PLI (Picture Loss Indication) mechanic.
269    pub fn fb_pli(&self) -> bool {
270        self.fb_pli
271    }
272
273    /// Set whether the payload uses the FIR (Full Intra Request) mechanic.
274    pub fn set_fb_fir(&mut self, fb_fir: bool) {
275        self.fb_fir = fb_fir
276    }
277
278    /// Whether the payload uses the FIR (Full Intra Request) mechanic.
279    pub fn fb_fir(&self) -> bool {
280        self.fb_fir
281    }
282
283    /// Set whether the payload uses the REMB (Receiver Estimated Maximum Bitrate) mechanic.
284    pub fn set_fb_remb(&mut self, fb_remb: bool) {
285        self.fb_remb = fb_remb
286    }
287
288    /// Whether the payload uses the REMB (Receiver Estimated Maximum Bitrate) mechanic.
289    pub fn fb_remb(&self) -> bool {
290        self.fb_remb
291    }
292
293    /// The RFC 2198 RED payload type wrapping this primary codec, if negotiated.
294    pub fn red(&self) -> Option<Pt> {
295        self.red
296    }
297
298    pub(crate) fn match_score(&self, o: &PayloadParams) -> Option<usize> {
299        // we don't want to compare PT
300        let c0 = self.spec;
301        let c1 = o.spec;
302
303        if c0 == c1 && c0.codec != Codec::AmrWb {
304            // Exact match
305            return Some(Self::EXACT_MATCH_SCORE);
306        }
307
308        // Attempt fuzzy matching, since we don't have an exact match
309        if c0.codec != c1.codec || (c0.codec == Codec::Unknown && c1.codec == Codec::Unknown) {
310            // Codecs must match
311            return None;
312        }
313
314        if c0.clock_rate != c1.clock_rate {
315            // Clock rates must match
316            return None;
317        }
318
319        // Telephone events match by clock rate, regardless of channel count.
320        if c0.codec.is_tele() {
321            return Some(Self::EXACT_MATCH_SCORE);
322        }
323
324        // AMR-WB defaults an omitted channel count to mono, so it must match
325        // before the generic channel comparison below.
326        if c0.codec == Codec::AmrWb {
327            return Self::match_amr_wb_score(c0, c1);
328        }
329
330        if c0.channels != c1.channels {
331            // Channels must match
332            return None;
333        }
334
335        if c0.codec.is_audio() && c0.codec == Codec::Opus {
336            return Some(Self::match_opus_score(c0, c1));
337        }
338
339        if c0.codec == Codec::H264 {
340            return Self::match_h264_score(c0, c1);
341        }
342
343        if c0.codec == Codec::H265 {
344            return Self::match_h265_score(c0, c1);
345        }
346
347        if c0.codec == Codec::H266 {
348            return Self::match_h266_score(c0, c1);
349        }
350
351        if c0.codec == Codec::Vp9 {
352            return Self::match_vp9_score(c0, c1);
353        }
354
355        if c0.codec == Codec::Av1 {
356            return Self::match_av1_score(c0, c1);
357        }
358
359        // TODO: Fuzzy matching for any other audio codecs
360        // TODO: Fuzzy matching for video
361
362        None
363    }
364
365    fn match_opus_score(c0: CodecSpec, c1: CodecSpec) -> usize {
366        let mut score: usize = Self::EXACT_MATCH_SCORE;
367
368        // If neither value is specified both sides should assume the default value, 3.
369        let either_p_time_specified =
370            c0.format.min_p_time.is_some() || c1.format.min_p_time.is_some();
371        if either_p_time_specified && c0.format.min_p_time != c1.format.min_p_time {
372            score = score.saturating_sub(1);
373        }
374
375        // If neither value is specified both sides should assume FEC is not used as this is
376        // the default.
377        let either_fec_specified =
378            c0.format.use_inband_fec.is_some() || c1.format.use_inband_fec.is_some();
379
380        if either_fec_specified && c0.format.use_inband_fec != c1.format.use_inband_fec {
381            score = score.saturating_sub(2);
382        }
383
384        // If neither value is specified both sides should assume DTX is not used as this is
385        // the default.
386        let either_dtx_specified = c0.format.use_dtx.is_some() || c1.format.use_dtx.is_some();
387        if either_dtx_specified && c0.format.use_dtx != c1.format.use_dtx {
388            score = score.saturating_sub(4);
389        }
390
391        // If neither value is specified both sides should assume mono for stereo
392        // and the sprop-stereo hint defaults to false.
393        let c0_stereo = c0.format.stereo.unwrap_or(false);
394        let c1_stereo = c1.format.stereo.unwrap_or(false);
395        if c0_stereo != c1_stereo {
396            score = score.saturating_sub(8);
397        }
398
399        let c0_sprop_stereo = c0.format.sprop_stereo.unwrap_or(false);
400        let c1_sprop_stereo = c1.format.sprop_stereo.unwrap_or(false);
401        if c0_sprop_stereo != c1_sprop_stereo {
402            score = score.saturating_sub(8);
403        }
404
405        score
406    }
407
408    fn match_vp9_score(c0: CodecSpec, c1: CodecSpec) -> Option<usize> {
409        // Default profile_id is 0. https://datatracker.ietf.org/doc/html/draft-ietf-payload-vp9-16#section-6
410        let c0_profile_id = c0.format.profile_id.unwrap_or(0);
411        let c1_profile_id = c1.format.profile_id.unwrap_or(0);
412
413        if c0_profile_id != c1_profile_id {
414            return None;
415        }
416
417        Some(Self::EXACT_MATCH_SCORE)
418    }
419
420    fn match_av1_score(c0: CodecSpec, c1: CodecSpec) -> Option<usize> {
421        // TODO: consider media direction for a proper less or equal matching
422        // The AV1 stream sent by either the offerer or the answerer MUST be
423        // encoded with a profile, level and tier, lesser or equal to the values
424        // of the level-idx, profile and tier declared in the SDP by the receiving
425        // agent.
426        // https://aomediacodec.github.io/av1-rtp-spec/#723-usage-with-the-sdp-offeranswer-model
427
428        // Default values: profile = 0, level-idx = 5, tier = 0
429        // https://aomediacodec.github.io/av1-rtp-spec/#72-sdp-parameters
430        let c0_profile = c0.format.profile.unwrap_or(0);
431        let c1_profile = c1.format.profile.unwrap_or(0);
432        if c0_profile != c1_profile {
433            return None;
434        }
435
436        let c0_level_idx = c0.format.level_idx.unwrap_or(5);
437        let c1_level_idx = c1.format.level_idx.unwrap_or(5);
438        if c0_level_idx != c1_level_idx {
439            return None;
440        }
441
442        let c0_tier = c0.format.tier.unwrap_or(0);
443        let c1_tier = c1.format.tier.unwrap_or(0);
444        if c0_tier != c1_tier {
445            return None;
446        }
447
448        Some(Self::EXACT_MATCH_SCORE)
449    }
450
451    fn match_amr_wb_score(c0: CodecSpec, c1: CodecSpec) -> Option<usize> {
452        // Only mono is implemented, and octet-aligned and bandwidth-efficient
453        // payloads are not interchangeable.
454        if c0.channels.unwrap_or(1) != 1 || c1.channels.unwrap_or(1) != 1 {
455            return None;
456        }
457        if c0.format.octet_align.unwrap_or(false) != c1.format.octet_align.unwrap_or(false) {
458            return None;
459        }
460
461        // A mode-set binds both peers (RFC 4867 §8.3.1), so prefer unrestricted
462        // payload types when the remote offers both.
463        match (c0.format.mode_set, c1.format.mode_set) {
464            (None, None) => Some(Self::EXACT_MATCH_SCORE),
465            (Some(a), Some(b)) if a != b => None,
466            _ => Some(Self::EXACT_MATCH_SCORE - 1),
467        }
468    }
469
470    pub(crate) fn match_h264_score(c0: CodecSpec, c1: CodecSpec) -> Option<usize> {
471        // Default packetization mode is 0. https://www.rfc-editor.org/rfc/rfc6184#section-6.2
472        let c0_packetization_mode = c0.format.packetization_mode.unwrap_or(0);
473        let c1_packetization_mode = c1.format.packetization_mode.unwrap_or(0);
474
475        if c0_packetization_mode != c1_packetization_mode {
476            return None;
477        }
478
479        let c0_profile_level = c0
480            .format
481            .profile_level_id
482            .map(|l| l.try_into().ok())
483            .unwrap_or(Some(H264ProfileLevel::FALLBACK))?;
484        let c1_profile_level = c1
485            .format
486            .profile_level_id
487            .map(|l| l.try_into().ok())
488            .unwrap_or(Some(H264ProfileLevel::FALLBACK))?;
489
490        // RFC 6184 Section 8.2.2: Profiles must match exactly.
491        if c0_profile_level.profile() != c1_profile_level.profile() {
492            return None;
493        }
494
495        // RFC 6184 Section 8.2.2: the level is a negotiable (downgradable)
496        // parameter, so a level mismatch in either direction is allowed and
497        // only penalizes the match score rather than rejecting the payload.
498        //
499        // NOTE: this only affects *matching*. Unlike H.265/H.266, `update_param`
500        // does not narrow the answered H.264 level to `min(local, remote)`, so
501        // when `level-asymmetry-allowed` is absent we may answer with a level
502        // higher than the offer. See the note in `update_param`.
503        let level_difference: usize = c0_profile_level
504            .level()
505            .ordinal()
506            .abs_diff(c1_profile_level.level().ordinal());
507
508        Some(Self::EXACT_MATCH_SCORE.saturating_sub(level_difference))
509    }
510
511    /// Match H.265 codec specifications and return compatibility score.
512    ///
513    /// # Matching Rules — Full PTL (both sides have profile+tier+level)
514    ///
515    /// - **Profiles** must match exactly (no cross-profile compatibility)
516    /// - **Tiers** must match exactly (Main vs High tier are distinct)
517    /// - **Levels** penalize score by `|c0_level - c1_level|` but never reject.
518    ///   Both H.264 and H.265 tolerate level mismatches in either direction at
519    ///   match time. For H.265, `update_param` additionally narrows the
520    ///   negotiated level to `min(local, remote)` afterward; H.264 does not.
521    ///
522    /// # Matching Rules — Profile-only (at least one side lacks tier+level)
523    ///
524    /// - **Profiles** must match; missing profile info falls back to
525    ///   `FALLBACK.profile()` (not rejected).
526    /// - **Tiers and levels** are not checked (insufficient information).
527    /// - Returns a lower score (90) so full-PTL matches are preferred.
528    ///
529    /// # Returns
530    ///
531    /// - `Some(100)` for exact full-PTL match
532    /// - `Some(100 - level_gap)` for profile/tier match with level difference
533    /// - `Some(90)` for profile-only match (when tier/level unavailable)
534    /// - `None` for profile or tier mismatch
535    pub(crate) fn match_h265_score(c0: CodecSpec, c1: CodecSpec) -> Option<usize> {
536        match (
537            c0.format.h265_profile_tier_level,
538            c1.format.h265_profile_tier_level,
539        ) {
540            (Some(c0_ptl), Some(c1_ptl)) => {
541                // Both have full PTL - strict matching
542
543                // Profiles must match exactly.
544                // RFC 7798 §7.2.2: profile-id is a configuration parameter
545                // that MUST be used symmetrically in offer/answer.
546                // https://www.rfc-editor.org/rfc/rfc7798#section-7.2.2
547                if c0_ptl.profile() != c1_ptl.profile() {
548                    return None;
549                }
550
551                // Tiers must match exactly.
552                // RFC 7798 §7.2.2: tier-flag is a configuration parameter
553                // that MUST be used symmetrically in offer/answer.
554                // https://www.rfc-editor.org/rfc/rfc7798#section-7.2.2
555                if c0_ptl.tier() != c1_ptl.tier() {
556                    return None;
557                }
558
559                // Level difference penalizes score but never causes rejection.
560                // Actual level narrowing to min(local, remote) is done in update_param.
561                let level_difference: usize =
562                    c0_ptl.level().ordinal().abs_diff(c1_ptl.level().ordinal());
563
564                // Pure scoring without artificial floor - let caller decide policy
565                Some(Self::EXACT_MATCH_SCORE.saturating_sub(level_difference))
566            }
567            _ => {
568                // At least one side has only profile-id (not full PTL).
569                // Match on profile only, using FALLBACK for missing values.
570
571                // Get profile from PTL if present, otherwise from profile_id field
572                let c0_profile = c0
573                    .format
574                    .h265_profile_tier_level
575                    .map(|ptl| ptl.profile().to_id())
576                    .or_else(|| c0.format.profile_id.map(|p| p as u8))
577                    .unwrap_or(H265ProfileTierLevel::FALLBACK.profile().to_id());
578
579                let c1_profile = c1
580                    .format
581                    .h265_profile_tier_level
582                    .map(|ptl| ptl.profile().to_id())
583                    .or_else(|| c1.format.profile_id.map(|p| p as u8))
584                    .unwrap_or(H265ProfileTierLevel::FALLBACK.profile().to_id());
585
586                // Profiles must match
587                if c0_profile != c1_profile {
588                    return None;
589                }
590
591                // When only profile is specified, we can't verify tier/level compatibility.
592                // Return a lower score to prefer exact PTL matches when available.
593                Some(Self::PROFILE_ONLY_MATCH_SCORE)
594            }
595        }
596    }
597
598    pub(crate) fn match_h266_score(c0: CodecSpec, c1: CodecSpec) -> Option<usize> {
599        match (
600            c0.format.h266_profile_tier_level,
601            c1.format.h266_profile_tier_level,
602        ) {
603            (Some(c0_ptl), Some(c1_ptl)) => {
604                // Both have full PTL - strict matching
605
606                // Profiles must match exactly.
607                // RFC 9328 §7.2: profile-id is a configuration parameter
608                // that MUST be used symmetrically in offer/answer.
609                if c0_ptl.profile() != c1_ptl.profile() {
610                    return None;
611                }
612
613                // Tiers must match exactly.
614                // RFC 9328 §7.2: tier-flag is a configuration parameter
615                // that MUST be used symmetrically in offer/answer.
616                if c0_ptl.tier() != c1_ptl.tier() {
617                    return None;
618                }
619
620                // Level difference penalizes score but never causes rejection.
621                let level_difference: usize =
622                    c0_ptl.level().ordinal().abs_diff(c1_ptl.level().ordinal());
623
624                Some(Self::EXACT_MATCH_SCORE.saturating_sub(level_difference))
625            }
626            _ => {
627                // At least one side has no full PTL (e.g. a GStreamer offer
628                // with a bare rtpmap and no fmtp). Match on profile only,
629                // using FALLBACK for missing values.
630                let c0_profile = c0
631                    .format
632                    .h266_profile_tier_level
633                    .map(|ptl| ptl.profile().to_id())
634                    .or_else(|| c0.format.profile_id.map(|p| p as u8))
635                    .unwrap_or(H266ProfileTierLevel::FALLBACK.profile().to_id());
636
637                let c1_profile = c1
638                    .format
639                    .h266_profile_tier_level
640                    .map(|ptl| ptl.profile().to_id())
641                    .or_else(|| c1.format.profile_id.map(|p| p as u8))
642                    .unwrap_or(H266ProfileTierLevel::FALLBACK.profile().to_id());
643
644                // Profiles must match
645                if c0_profile != c1_profile {
646                    return None;
647                }
648
649                Some(Self::PROFILE_ONLY_MATCH_SCORE)
650            }
651        }
652    }
653
654    pub(crate) fn update_param(
655        &mut self,
656        remote_pts: &[PayloadParams],
657        claimed: &mut [bool; 128],
658        local_is_controlling: bool,
659        unlocked: &mut HashSet<Pt>,
660    ) {
661        let Some((first, _)) = remote_pts
662            .iter()
663            // One unrestricted AMR-WB payload can match several local mode sets.
664            // Leave the other alternatives unlocked once its PT has been claimed.
665            .filter(|p| {
666                self.spec.codec != Codec::AmrWb
667                    || self.locked
668                    || local_is_controlling
669                    || !claimed.is_claimed(p.pt)
670            })
671            .filter_map(|p| self.match_score(p).map(|s| (p, s)))
672            .max_by_key(|(_, s)| *s)
673        else {
674            return;
675        };
676
677        let original_spec = self.spec;
678
679        // The first negotiated m-line determines TWCC support for this PT.
680        if !self.locked {
681            self.fb_transport_cc &= first.fb_transport_cc();
682        }
683
684        if self.spec.codec.is_tele() {
685            let local = self
686                .spec
687                .format
688                .telephone_event_max
689                .unwrap_or(FormatParams::DEFAULT_TELEPHONE_EVENT_MAX);
690            let remote = first
691                .spec
692                .format
693                .telephone_event_max
694                .unwrap_or(FormatParams::DEFAULT_TELEPHONE_EVENT_MAX);
695            self.spec.format.telephone_event_max = Some(local.min(remote));
696        }
697
698        // Mirror the remote's H.265 fmtp shape: echo back only the params they offered.
699        if self.spec.codec == Codec::H265 && first.spec.codec == Codec::H265 {
700            if let Some(remote_ptl) = first.spec.format.h265_profile_tier_level {
701                // Narrow level to min(local, remote) so the negotiated level
702                // never exceeds either side's capability.
703                let negotiated_ptl =
704                    if let Some(local_ptl) = self.spec.format.h265_profile_tier_level {
705                        remote_ptl.with_level(std::cmp::min(local_ptl.level(), remote_ptl.level()))
706                    } else {
707                        remote_ptl
708                    };
709                self.spec.format.h265_profile_tier_level = Some(negotiated_ptl);
710                // Avoid also serializing `profile-id` via the VP9 `profile_id` field.
711                self.spec.format.profile_id = None;
712            } else if let Some(profile_id) = first.spec.format.profile_id {
713                // Remote only offered `profile-id`.
714                self.spec.format.h265_profile_tier_level = None;
715                self.spec.format.profile_id = Some(profile_id);
716            } else {
717                // No remote H.265 fmtp, omit ours as well.
718                self.spec.format.h265_profile_tier_level = None;
719                self.spec.format.profile_id = None;
720            }
721
722            // Adopt remote's sprop-max-don-diff so the depacketizer knows whether
723            // incoming packets contain DONL fields (RFC 7798 §7.1).
724            // The packetizer also uses this to decide whether to emit DONL.
725            if first.spec.format.sprop_max_don_diff.is_some() {
726                self.spec.format.sprop_max_don_diff = first.spec.format.sprop_max_don_diff;
727            }
728        }
729
730        // Same negotiation for H.266 (RFC 9328 §7.2, offer/answer model §7.3.2).
731        if self.spec.codec == Codec::H266 && first.spec.codec == Codec::H266 {
732            if let Some(remote_ptl) = first.spec.format.h266_profile_tier_level {
733                // Narrow level to min(local, remote) so the negotiated level
734                // never exceeds either side's capability.
735                let negotiated_ptl =
736                    if let Some(local_ptl) = self.spec.format.h266_profile_tier_level {
737                        remote_ptl.with_level(std::cmp::min(local_ptl.level(), remote_ptl.level()))
738                    } else {
739                        remote_ptl
740                    };
741                self.spec.format.h266_profile_tier_level = Some(negotiated_ptl);
742                // Avoid also serializing `profile-id` via the VP9 `profile_id` field.
743                self.spec.format.profile_id = None;
744            } else if let Some(profile_id) = first.spec.format.profile_id {
745                // Remote only offered `profile-id`.
746                self.spec.format.h266_profile_tier_level = None;
747                self.spec.format.profile_id = Some(profile_id);
748            } else {
749                // No remote H.266 fmtp, omit ours as well.
750                self.spec.format.h266_profile_tier_level = None;
751                self.spec.format.profile_id = None;
752            }
753
754            // Adopt remote's sprop-max-don-diff (RFC 9328 §7.2) — enables
755            // DONL on both packetizer and depacketizer.
756            if first.spec.format.sprop_max_don_diff.is_some() {
757                self.spec.format.sprop_max_don_diff = first.spec.format.sprop_max_don_diff;
758            }
759        }
760
761        // KNOWN LIMITATION: H.264 has no equivalent level-narrowing pass here.
762        // `match_h264_score` treats the level as negotiable, but we keep our
763        // locally configured `profile-level-id` in the answer instead of
764        // narrowing it to `min(local, remote)`. Per RFC 6184 §8.2.2, when
765        // `level-asymmetry-allowed` is not set the answer should use the lower
766        // level.
767
768        // RFC 4867 §8.3.1: an answer repeats the offer's octet-align and channels,
769        // and a mode-set from either side applies to both directions.
770        if self.spec.codec == Codec::AmrWb {
771            let remote = first.spec;
772            self.spec.channels = remote.channels;
773            self.spec.format.octet_align = remote.format.octet_align;
774            self.spec.format.mode_set = self.spec.format.mode_set.or(remote.format.mode_set);
775        }
776
777        let mut remote_pt = first.pt;
778        let mut remote_rtx = first.resend;
779
780        // The RTX payload type (RFC 4588 §8.6) is a media format, and for unicast
781        // the answerer selects formats (RFC 3264 §6.1, Unicast Streams) "from
782        // amongst those listed in the offer". So if we didn't offer RTX for this
783        // codec, don't adopt the remote's RTX PT. Once locked, that holds only for parameters
784        // locked without RTX of our own: a locked `resend` of `None` that came from the remote
785        // is checked against the remote's RTX like any other locked value.
786        if self.resend.is_none() && (!self.locked || self.rtx_declined) {
787            remote_rtx = None;
788        }
789
790        if self.locked {
791            if self.spec != original_spec {
792                warn!("Ignore remote codec parameters for locked PT {}", self.pt);
793                self.spec = original_spec;
794            }
795            // This can happen if the incoming PTs are suggestions (send-direction) rather than demanded
796            // (receive-direction). We only want to warn if we get receive direction changes.
797            if local_is_controlling {
798                return;
799            }
800            // Just verify it's still the same. We should validate this in apply_offer/answer instead
801            // of ever seeing this error message.
802            if self.pt != remote_pt {
803                warn!("Ignore remote PT change {} => {}", self.pt, remote_pt);
804            }
805
806            if self.resend != remote_rtx {
807                warn!(
808                    "Ignore remote PT RTX change {:?} => {:?}",
809                    self.resend, remote_rtx
810                );
811            }
812
813            if self.red != first.red {
814                warn!(
815                    "Ignore remote PT RED change {:?} => {:?}",
816                    self.red, first.red
817                );
818            }
819        } else {
820            // Before locking, check if the remote PT conflicts with an already locked PT.
821            // If we're receiving, we control what PTs to use,
822            // so we can remap the conflicting PT.
823            if local_is_controlling && claimed.is_claimed(remote_pt) {
824                // Prefer our configured PT, then fall back to any free PT.
825                let new_pt = (!claimed.is_claimed(self.pt))
826                    .then_some(self.pt)
827                    .or_else(|| claimed.find_unclaimed(PREFERED_RANGES, unlocked));
828
829                if let Some(new_pt) = new_pt {
830                    debug!(
831                        "Remapped conflicting PT {} => {} for codec {:?}",
832                        remote_pt, new_pt, self.spec.codec
833                    );
834                    remote_pt = new_pt;
835                    unlocked.remove(&new_pt);
836                } else {
837                    warn!("Exhausted PT ranges; ignoring remote payload");
838                    return;
839                }
840            }
841
842            // Lock down the PT
843            if !claimed.assert_claim_once(remote_pt) {
844                return;
845            }
846            self.pt = remote_pt;
847
848            // Check if RTX PT also conflicts
849            if local_is_controlling {
850                if let Some(rtx) = remote_rtx {
851                    if claimed.is_claimed(rtx) {
852                        let new_rtx = self
853                            .resend
854                            .filter(|pt| !claimed.is_claimed(*pt))
855                            .or_else(|| claimed.find_unclaimed(PREFERED_RANGES, unlocked));
856
857                        if let Some(new_rtx) = new_rtx {
858                            debug!("Remapped conflicting RTX PT {:?} => {}", rtx, new_rtx);
859                            remote_rtx = Some(new_rtx);
860                            unlocked.remove(&new_rtx);
861                        } else {
862                            warn!("Exhausted PT ranges; ignoring remote RTX");
863                            remote_rtx = None;
864                        }
865                    }
866                }
867            }
868
869            // Remember whether we lock without RTX of our own (see `rtx_declined`).
870            self.rtx_declined = self.resend.is_none();
871
872            // Lock down the RTX PT
873            self.resend = remote_rtx;
874            if let Some(rtx) = remote_rtx {
875                if !claimed.assert_claim_once(rtx) {
876                    self.resend = None;
877                }
878            }
879
880            // RED is opt-in on our side and audio-only: keep it only if the matched remote also
881            // offers RED (`and`) and our codec is an audio codec. A RED PT can still collide (two
882            // codecs mapped to the same PT), so resolve any collision before claiming it. The
883            // collision check runs regardless of who controls PT allocation: only the resolution
884            // differs, and claiming the same PT twice would panic.
885            let mut remote_red = self
886                .red
887                .and(first.red)
888                .filter(|_| self.spec.codec.is_audio());
889            if let Some(red) = remote_red {
890                if claimed.is_claimed(red) {
891                    if local_is_controlling {
892                        // We control PT allocation: remap the conflicting RED to a free PT.
893                        if let Some(new_red) = claimed.find_unclaimed(PREFERED_RANGES, unlocked) {
894                            debug!("Remapped conflicting RED PT {:?} => {}", red, new_red);
895                            remote_red = Some(new_red);
896                            unlocked.remove(&new_red);
897                        } else {
898                            // RED is opt-in; drop it rather than panic if no PT is free.
899                            debug!("No free PT for RED; dropping it");
900                            remote_red = None;
901                        }
902                    } else {
903                        // The remote dictated the PTs and mapped a RED PT that is already taken.
904                        // We can't reassign PTs the remote controls, and RED is opt-in, so drop it
905                        // rather than claim the same PT twice (which would panic).
906                        debug!("Conflicting remote RED PT {:?}; dropping it", red);
907                        remote_red = None;
908                    }
909                }
910            }
911            self.red = remote_red;
912            if let Some(red) = remote_red {
913                claimed.assert_claim_once(red);
914            }
915
916            // The answerer removes rtcp-fb attributes it does not support, and per
917            // RFC 4585 §4.2 "both offerer and answerer MUST only use feedback
918            // mechanisms negotiated in this way". So intersect our local `fb_nack`
919            // with what the remote signaled (`a=rtcp-fb <pt> nack`). Runs once at
920            // lock time, when `self.fb_nack` still holds the local desired value.
921            self.fb_nack = self.fb_nack && first.fb_nack;
922
923            // This is now locked.
924            self.locked = true;
925        }
926    }
927}
928
929#[cfg(test)]
930mod test {
931    use crate::rtp_::Frequency;
932
933    use super::*;
934    use crate::format::{CodecSpec, FormatParams};
935
936    #[test]
937    fn payload_params_red_defaults_none() {
938        let spec = CodecSpec {
939            codec: Codec::Opus,
940            clock_rate: Frequency::NINETY_KHZ,
941            channels: Some(2),
942            format: FormatParams::default(),
943        };
944        let p = PayloadParams::new(Pt::new_with_value(111), None, spec);
945        assert_eq!(p.red(), None);
946    }
947
948    #[test]
949    fn red_pt_remapped_on_conflict() {
950        use std::collections::HashSet;
951
952        // When we control PT allocation (the remote is send-only) and the RED PT we would adopt
953        // from the remote is already taken, RED is remapped to a free PT rather than colliding
954        // or being dropped.
955        let spec = CodecSpec {
956            codec: Codec::Opus,
957            clock_rate: Frequency::FORTY_EIGHT_KHZ,
958            channels: Some(2),
959            format: FormatParams::default(),
960        };
961
962        let red_pt = Pt::new_with_value(63);
963
964        let mut local = PayloadParams::new(Pt::new_with_value(111), None, spec);
965        local.red = Some(red_pt);
966
967        let mut remote = PayloadParams::new(Pt::new_with_value(111), None, spec);
968        remote.red = Some(red_pt);
969
970        // Pre-claim the RED PT as if another payload already holds it.
971        let mut claimed = [false; 128];
972        claimed[*red_pt as usize] = true;
973        let mut unlocked = HashSet::new();
974
975        // local_is_controlling = true: we allocate PTs and may remap the conflict.
976        local.update_param(&[remote], &mut claimed, true, &mut unlocked);
977
978        let got = local.red.expect("RED is kept, remapped to a free PT");
979        assert_ne!(
980            got, red_pt,
981            "RED PT must be remapped away from the conflict"
982        );
983        assert!(
984            claimed.is_claimed(got),
985            "the remapped RED PT must be claimed"
986        );
987    }
988
989    mod h264 {
990        use super::*;
991
992        fn h264_codec_spec(
993            level_asymmetry_allowed: Option<bool>,
994            packetization_mode: Option<u8>,
995            profile_level_id: Option<u32>,
996        ) -> CodecSpec {
997            CodecSpec {
998                codec: Codec::H264,
999                clock_rate: Frequency::NINETY_KHZ,
1000                channels: None,
1001                format: FormatParams {
1002                    level_asymmetry_allowed,
1003                    packetization_mode,
1004                    profile_level_id,
1005                    ..Default::default()
1006                },
1007            }
1008        }
1009
1010        #[test]
1011        fn test_h264_profile_matching() {
1012            struct Case {
1013                c0: CodecSpec,
1014                c1: CodecSpec,
1015                must_match: bool,
1016                msg: &'static str,
1017            }
1018
1019            let cases = [
1020                Case {
1021                    c0: h264_codec_spec(None, None, Some(0x42E01F)),
1022                    c1: h264_codec_spec(None, None, Some(0x4DA01F)),
1023                    must_match: true,
1024                    msg: "0x42A01F and 0x4DF01F should match, they are both constrained baseline subprofile",
1025                },
1026                Case {
1027                    c0: h264_codec_spec(None, None, Some(0x42E01F)),
1028                    c1: h264_codec_spec(None, Some(1), Some(0x4DA01F)),
1029                    must_match: false,
1030                    msg: "0x42A01F and 0x4DF01F with differing packetization modes should not match",
1031                },
1032                Case {
1033                    c0: h264_codec_spec(None, Some(0), Some(0x422000)),
1034                    c1: h264_codec_spec(None, None, Some(0x42B00A)),
1035                    must_match: true,
1036                    msg: "0x424000 and 0x42B00A should match because they are both the baseline subprofile \
1037                    and the level idc of 0x42F01F will be adjusted to Level1B because the constraint \
1038                    set 3 flag is set",
1039                },
1040            ];
1041
1042            for Case {
1043                c0,
1044                c1,
1045                must_match,
1046                msg,
1047            } in cases.into_iter()
1048            {
1049                let matched = PayloadParams::match_h264_score(c0, c1).is_some();
1050                assert_eq!(matched, must_match, "{msg}\nc0: {c0:#?}\nc1: {c1:#?}");
1051            }
1052        }
1053
1054        #[test]
1055        fn test_h264_level_matching_rfc_compliant() {
1056            struct Case {
1057                c0: CodecSpec,
1058                c1: CodecSpec,
1059                expected: Option<usize>,
1060                msg: &'static str,
1061            }
1062
1063            let cases = [
1064                // Test 1: Same profile, same level -> should match
1065                Case {
1066                    c0: h264_codec_spec(None, None, Some(0x42e028)), // CB L4.0
1067                    c1: h264_codec_spec(None, None, Some(0x42e028)), // CB L4.0
1068                    expected: Some(PayloadParams::EXACT_MATCH_SCORE),
1069                    msg: "Same profile (CB) and same level (4.0) should match",
1070                },
1071                // Test 2: Same profile, offered level lower -> should match (RFC 6184)
1072                Case {
1073                    c0: h264_codec_spec(None, None, Some(0x42e028)), // CB L4.0 (configured)
1074                    c1: h264_codec_spec(None, None, Some(0x42e01f)), // CB L3.1 (offered)
1075                    expected: Some(PayloadParams::EXACT_MATCH_SCORE - 2),
1076                    msg: "Same profile (CB), offered level 3.1 < configured 4.0 should match per RFC 6184",
1077                },
1078                // Test 3: Same profile, offered level higher -> should match (RFC 6184)
1079                Case {
1080                    c0: h264_codec_spec(None, None, Some(0x42e01f)), // CB L3.1 (configured)
1081                    c1: h264_codec_spec(None, None, Some(0x42e028)), // CB L4.0 (offered)
1082                    expected: Some(PayloadParams::EXACT_MATCH_SCORE - 2),
1083                    msg: "Same profile (CB), offered level 4.0 > configured 3.1 should match, \
1084                    the level is negotiable per RFC 6184",
1085                },
1086                // Test 4: Different profiles -> should NOT match
1087                Case {
1088                    c0: h264_codec_spec(None, None, Some(0x42e028)), // CB L4.0
1089                    c1: h264_codec_spec(None, None, Some(0x4d0028)), // Main L4.0
1090                    expected: None,
1091                    msg: "Different profiles (CB vs Main) should NOT match even with same level",
1092                },
1093                // Test 5: Main profile, offered lower level -> should match
1094                Case {
1095                    c0: h264_codec_spec(None, None, Some(0x4d002a)), // Main L4.2 (configured)
1096                    c1: h264_codec_spec(None, None, Some(0x4d0028)), // Main L4.0 (offered)
1097                    expected: Some(PayloadParams::EXACT_MATCH_SCORE - 2),
1098                    msg: "Same profile (Main), offered level 4.0 < configured 4.2 should match",
1099                },
1100                // Test 6: High profile, multiple levels down -> should match
1101                Case {
1102                    c0: h264_codec_spec(None, None, Some(0x640033)), // High L5.1 (configured)
1103                    c1: h264_codec_spec(None, None, Some(0x64001f)), // High L3.1 (offered)
1104                    expected: Some(PayloadParams::EXACT_MATCH_SCORE - 6),
1105                    msg: "Same profile (High), offered level 3.1 < configured 5.1 should match",
1106                },
1107                // Test 7: Baseline (not CB) with Level1B as offered
1108                Case {
1109                    c0: h264_codec_spec(None, None, Some(0x42001f)), // Baseline L3.1
1110                    c1: h264_codec_spec(None, None, Some(0x420000)), // Baseline Level1B
1111                    expected: Some(PayloadParams::EXACT_MATCH_SCORE - 8),
1112                    msg: "Same profile (Baseline), offered level 1B < configured 3.1 should match",
1113                },
1114                // Test 8: Baseline (not CB) offered lower level > should match with (special Level1B case)
1115                Case {
1116                    c0: h264_codec_spec(None, None, Some(0x420000)), // Baseline Level1B
1117                    c1: h264_codec_spec(None, None, Some(0x42000a)), // Baseline L1
1118                    expected: Some(PayloadParams::EXACT_MATCH_SCORE - 1),
1119                    msg: "Same profile (Baseline), offered level 1 < configured 1B should match",
1120                },
1121                // Test 9: Baseline (not CB) offered higher level -> should match (special Level1B case)
1122                Case {
1123                    c0: h264_codec_spec(None, None, Some(0x42000a)), // Baseline L1
1124                    c1: h264_codec_spec(None, None, Some(0x420000)), // Baseline Level1B
1125                    expected: Some(PayloadParams::EXACT_MATCH_SCORE - 1),
1126                    msg: "Same profile (Baseline), offered level 1B > configured 1 should match",
1127                },
1128                // Test 10: Offered Constrained Baseline level 5.2 is higher than
1129                // the default configured 3.1. Must match.
1130                Case {
1131                    c0: h264_codec_spec(Some(true), Some(1), Some(0x42e01f)), // CB L3.1 (configured)
1132                    c1: h264_codec_spec(Some(true), Some(1), Some(0x42e034)), // CB L5.2 (offered)
1133                    expected: Some(PayloadParams::EXACT_MATCH_SCORE - 7),
1134                    msg: "Same profile (CB), offered level 5.2 > configured 3.1 should match",
1135                },
1136                // Test 11: Constrained High (profile-iop 0x0C) must be recognized
1137                // and match a configured Constrained High.
1138                Case {
1139                    c0: h264_codec_spec(Some(true), Some(1), Some(0x640c1f)), // CH L3.1 (configured)
1140                    c1: h264_codec_spec(Some(true), Some(1), Some(0x640c34)), // CH L5.2 (offered)
1141                    expected: Some(PayloadParams::EXACT_MATCH_SCORE - 7),
1142                    msg: "Same profile (Constrained High), offered level 5.2 should match",
1143                },
1144                // Test 12: Constrained High is not the same profile as High.
1145                Case {
1146                    c0: h264_codec_spec(None, None, Some(0x64001f)), // High L3.1
1147                    c1: h264_codec_spec(None, None, Some(0x640c1f)), // Constrained High L3.1
1148                    expected: None,
1149                    msg: "Different profiles (High vs Constrained High) should NOT match",
1150                },
1151            ];
1152
1153            for Case {
1154                c0,
1155                c1,
1156                expected,
1157                msg,
1158            } in cases.into_iter()
1159            {
1160                assert_eq!(
1161                    PayloadParams::match_h264_score(c0, c1),
1162                    expected,
1163                    "{msg}\nc0: {c0:#?}\nc1: {c1:#?}"
1164                );
1165            }
1166        }
1167    }
1168
1169    mod h265 {
1170        use super::*;
1171        use crate::packet::Packetizer;
1172
1173        fn h265_codec_spec(profile_id: u8, tier_flag: u8, level_id: u8) -> CodecSpec {
1174            CodecSpec {
1175                codec: Codec::H265,
1176                clock_rate: Frequency::NINETY_KHZ,
1177                channels: None,
1178                format: FormatParams {
1179                    h265_profile_tier_level: Some(
1180                        H265ProfileTierLevel::new(profile_id, tier_flag, level_id).unwrap(),
1181                    ),
1182                    ..Default::default()
1183                },
1184            }
1185        }
1186
1187        fn h265_codec_spec_profile_only(profile_id: u32) -> CodecSpec {
1188            CodecSpec {
1189                codec: Codec::H265,
1190                clock_rate: Frequency::NINETY_KHZ,
1191                channels: None,
1192                format: FormatParams {
1193                    profile_id: Some(profile_id),
1194                    ..Default::default()
1195                },
1196            }
1197        }
1198
1199        /// Test basic H.265 profile/tier/level matching scenarios.
1200        /// Verifies that full ProfileTierLevel parameters are matched correctly.
1201        #[test]
1202        fn test_profile_tier_level_matching() {
1203            struct Case {
1204                c0: CodecSpec,
1205                c1: CodecSpec,
1206                must_match: bool,
1207                msg: &'static str,
1208            }
1209
1210            let cases = [
1211                // Same profile, tier, level -> should match
1212                Case {
1213                    c0: h265_codec_spec(1, 0, 93), // Main, Main tier, Level 3.1
1214                    c1: h265_codec_spec(1, 0, 93),
1215                    must_match: true,
1216                    msg: "Same profile (Main), tier (Main), level (3.1) should match",
1217                },
1218                // Same profile and tier, offered level lower -> should match
1219                Case {
1220                    c0: h265_codec_spec(1, 0, 120), // Main, Main tier, Level 4.0
1221                    c1: h265_codec_spec(1, 0, 93),  // Main, Main tier, Level 3.1
1222                    must_match: true,
1223                    msg: "Same profile/tier, offered level 3.1 < configured 4.0 should match",
1224                },
1225                // Same profile and tier, offered level higher -> should still match (with penalty)
1226                Case {
1227                    c0: h265_codec_spec(1, 0, 93),  // Main, Main tier, Level 3.1
1228                    c1: h265_codec_spec(1, 0, 120), // Main, Main tier, Level 4.0
1229                    must_match: true,
1230                    msg: "Same profile/tier, offered level 4.0 > configured 3.1 should match (penalized)",
1231                },
1232                // Different profiles -> should NOT match
1233                Case {
1234                    c0: h265_codec_spec(1, 0, 93), // Main, Main tier, Level 3.1
1235                    c1: h265_codec_spec(2, 0, 93), // Main10, Main tier, Level 3.1
1236                    must_match: false,
1237                    msg: "Different profiles (Main vs Main10) should NOT match",
1238                },
1239                // Different tiers -> should NOT match
1240                Case {
1241                    c0: h265_codec_spec(1, 0, 93), // Main, Main tier, Level 3.1
1242                    c1: h265_codec_spec(1, 1, 93), // Main, High tier, Level 3.1
1243                    must_match: false,
1244                    msg: "Different tiers (Main vs High) should NOT match",
1245                },
1246                // Main10 profile, same tier, lower level -> should match
1247                Case {
1248                    c0: h265_codec_spec(2, 0, 153), // Main10, Main tier, Level 5.1
1249                    c1: h265_codec_spec(2, 0, 120), // Main10, Main tier, Level 4.0
1250                    must_match: true,
1251                    msg: "Main10 profile, offered level 4.0 < configured 5.1 should match",
1252                },
1253                // High tier, multiple levels down -> should match
1254                Case {
1255                    c0: h265_codec_spec(1, 1, 153), // Main, High tier, Level 5.1
1256                    c1: h265_codec_spec(1, 1, 93),  // Main, High tier, Level 3.1
1257                    must_match: true,
1258                    msg: "High tier, offered level 3.1 < configured 5.1 should match",
1259                },
1260            ];
1261
1262            for Case {
1263                c0,
1264                c1,
1265                must_match,
1266                msg,
1267            } in cases.into_iter()
1268            {
1269                let matched = PayloadParams::match_h265_score(c0, c1).is_some();
1270                assert_eq!(matched, must_match, "{msg}\nc0: {c0:#?}\nc1: {c1:#?}");
1271            }
1272        }
1273
1274        /// Test H.265 level matching with exact scores.
1275        /// Verifies that the score decrements based on level difference.
1276        #[test]
1277        fn test_level_matching_scores() {
1278            struct Case {
1279                c0: CodecSpec,
1280                c1: CodecSpec,
1281                expected: Option<usize>,
1282                msg: &'static str,
1283            }
1284
1285            let cases = [
1286                // Exact match -> score 100
1287                Case {
1288                    c0: h265_codec_spec(1, 0, 93), // Main, Main tier, Level 3.1
1289                    c1: h265_codec_spec(1, 0, 93),
1290                    expected: Some(PayloadParams::EXACT_MATCH_SCORE),
1291                    msg: "Exact match should return score 100",
1292                },
1293                // One level down -> score 100 - 1
1294                Case {
1295                    c0: h265_codec_spec(1, 0, 120), // Main, Main tier, Level 4.0
1296                    c1: h265_codec_spec(1, 0, 93),  // Main, Main tier, Level 3.1
1297                    expected: Some(PayloadParams::EXACT_MATCH_SCORE - 1),
1298                    msg: "One level difference should return score 99",
1299                },
1300                // Two levels down -> score 100 - 2
1301                Case {
1302                    c0: h265_codec_spec(1, 0, 123), // Main, Main tier, Level 4.1
1303                    c1: h265_codec_spec(1, 0, 93),  // Main, Main tier, Level 3.1
1304                    expected: Some(PayloadParams::EXACT_MATCH_SCORE - 2),
1305                    msg: "Two level difference should return score 98",
1306                },
1307                // Multiple levels down
1308                Case {
1309                    c0: h265_codec_spec(1, 0, 153), // Main, Main tier, Level 5.1
1310                    c1: h265_codec_spec(1, 0, 93),  // Main, Main tier, Level 3.1
1311                    expected: Some(PayloadParams::EXACT_MATCH_SCORE - 4),
1312                    msg: "Four level difference (5.1 to 3.1) should return score 96",
1313                },
1314                // Offered level higher -> still matches, penalized by 1 ordinal
1315                Case {
1316                    c0: h265_codec_spec(1, 0, 93),  // Main, Main tier, Level 3.1
1317                    c1: h265_codec_spec(1, 0, 120), // Main, Main tier, Level 4.0
1318                    expected: Some(PayloadParams::EXACT_MATCH_SCORE - 1),
1319                    msg: "Offered level one higher than configured should return score 99",
1320                },
1321                // Different profiles -> None
1322                Case {
1323                    c0: h265_codec_spec(1, 0, 93), // Main, Main tier, Level 3.1
1324                    c1: h265_codec_spec(2, 0, 93), // Main10, Main tier, Level 3.1
1325                    expected: None,
1326                    msg: "Different profiles should return None",
1327                },
1328                // Different tiers -> None
1329                Case {
1330                    c0: h265_codec_spec(1, 0, 93), // Main, Main tier, Level 3.1
1331                    c1: h265_codec_spec(1, 1, 93), // Main, High tier, Level 3.1
1332                    expected: None,
1333                    msg: "Different tiers should return None",
1334                },
1335            ];
1336
1337            for Case {
1338                c0,
1339                c1,
1340                expected,
1341                msg,
1342            } in cases.into_iter()
1343            {
1344                assert_eq!(
1345                    PayloadParams::match_h265_score(c0, c1),
1346                    expected,
1347                    "{msg}\nc0: {c0:#?}\nc1: {c1:#?}"
1348                );
1349            }
1350        }
1351
1352        /// Test H.265 profile-only matching (for Chrome compatibility).
1353        /// When only profile-id is provided without tier/level, match on profile only.
1354        #[test]
1355        fn test_profile_only_matching() {
1356            struct Case {
1357                c0: CodecSpec,
1358                c1: CodecSpec,
1359                expected: Option<usize>,
1360                msg: &'static str,
1361            }
1362
1363            let cases = [
1364                // Both have profile-only, same profile -> score 90
1365                Case {
1366                    c0: h265_codec_spec_profile_only(1), // Main
1367                    c1: h265_codec_spec_profile_only(1), // Main
1368                    expected: Some(PayloadParams::PROFILE_ONLY_MATCH_SCORE),
1369                    msg: "Profile-only match (Main) should return score 90",
1370                },
1371                // Both have profile-only, different profiles -> None
1372                Case {
1373                    c0: h265_codec_spec_profile_only(1), // Main
1374                    c1: h265_codec_spec_profile_only(2), // Main10
1375                    expected: None,
1376                    msg: "Profile-only with different profiles should return None",
1377                },
1378                // One has full PTL, other has profile-only, same profile -> score 90
1379                Case {
1380                    c0: h265_codec_spec(1, 0, 93),       // Main, Main tier, Level 3.1
1381                    c1: h265_codec_spec_profile_only(1), // Main
1382                    expected: Some(PayloadParams::PROFILE_ONLY_MATCH_SCORE),
1383                    msg: "Mixed PTL and profile-only with matching profile should return score 90",
1384                },
1385                // One has full PTL, other has profile-only, different profiles -> None
1386                Case {
1387                    c0: h265_codec_spec(1, 0, 93),       // Main, Main tier, Level 3.1
1388                    c1: h265_codec_spec_profile_only(2), // Main10
1389                    expected: None,
1390                    msg: "Mixed PTL and profile-only with different profiles should return None",
1391                },
1392                // Reverse: profile-only vs full PTL, same profile -> score 90
1393                Case {
1394                    c0: h265_codec_spec_profile_only(1), // Main
1395                    c1: h265_codec_spec(1, 0, 93),       // Main, Main tier, Level 3.1
1396                    expected: Some(PayloadParams::PROFILE_ONLY_MATCH_SCORE),
1397                    msg: "Profile-only vs full PTL with matching profile should return score 90",
1398                },
1399            ];
1400
1401            for Case {
1402                c0,
1403                c1,
1404                expected,
1405                msg,
1406            } in cases.into_iter()
1407            {
1408                assert_eq!(
1409                    PayloadParams::match_h265_score(c0, c1),
1410                    expected,
1411                    "{msg}\nc0: {c0:#?}\nc1: {c1:#?}"
1412                );
1413            }
1414        }
1415
1416        /// Test negative cases for H.265 matching to ensure proper rejection.
1417        #[test]
1418        fn test_negative_cases() {
1419            struct Case {
1420                c0: CodecSpec,
1421                c1: CodecSpec,
1422                msg: &'static str,
1423            }
1424
1425            let cases = [
1426                // Profile mismatch with full PTL
1427                Case {
1428                    c0: h265_codec_spec(1, 0, 93), // Main, Main tier, Level 3.1
1429                    c1: h265_codec_spec(2, 0, 93), // Main10, Main tier, Level 3.1
1430                    msg: "Profile mismatch (Main vs Main10) must not match",
1431                },
1432                // Tier mismatch
1433                Case {
1434                    c0: h265_codec_spec(1, 0, 93), // Main, Main tier, Level 3.1
1435                    c1: h265_codec_spec(1, 1, 93), // Main, High tier, Level 3.1
1436                    msg: "Tier mismatch (Main vs High) must not match",
1437                },
1438                // All three different (profile+tier mismatch rejects)
1439                Case {
1440                    c0: h265_codec_spec(1, 0, 93),  // Main, Main tier, Level 3.1
1441                    c1: h265_codec_spec(2, 1, 153), // Main10, High tier, Level 5.1
1442                    msg: "Profile and tier different must not match",
1443                },
1444                // Profile-only mismatch
1445                Case {
1446                    c0: h265_codec_spec_profile_only(1), // Main
1447                    c1: h265_codec_spec_profile_only(2), // Main10
1448                    msg: "Profile-only mismatch must not match",
1449                },
1450                // Mixed full PTL vs profile-only with different profiles
1451                Case {
1452                    c0: h265_codec_spec(2, 0, 93),       // Main10, Main tier, Level 3.1
1453                    c1: h265_codec_spec_profile_only(1), // Main
1454                    msg: "Full PTL (Main10) vs profile-only (Main) must not match",
1455                },
1456            ];
1457
1458            for Case { c0, c1, msg } in cases.into_iter() {
1459                assert_eq!(
1460                    PayloadParams::match_h265_score(c0, c1),
1461                    None,
1462                    "{msg}\nc0: {c0:#?}\nc1: {c1:#?}"
1463                );
1464            }
1465        }
1466
1467        /// Test that sprop-max-don-diff is adopted from remote SDP during negotiation,
1468        /// and that packetizer/depacketizer are correctly initialized with DONL enabled.
1469        #[test]
1470        fn test_sprop_max_don_diff_negotiation_enables_donl() {
1471            use crate::packet::{CodecDepacketizer, CodecPacketizer};
1472
1473            // Local config: no sprop-max-don-diff (default)
1474            let local_spec = h265_codec_spec(1, 0, 93);
1475            let mut local_params = PayloadParams::new(
1476                Pt::new_with_value(102),
1477                Some(Pt::new_with_value(103)),
1478                local_spec,
1479            );
1480            assert_eq!(
1481                local_params.spec.format.sprop_max_don_diff, None,
1482                "Local should have no sprop-max-don-diff initially"
1483            );
1484
1485            // Remote offers H.265 with sprop-max-don-diff=32
1486            let mut remote_spec = h265_codec_spec(1, 0, 93);
1487            remote_spec.format.sprop_max_don_diff = Some(32);
1488            let remote_params = PayloadParams::new(
1489                Pt::new_with_value(102),
1490                Some(Pt::new_with_value(103)),
1491                remote_spec,
1492            );
1493
1494            // Simulate SDP negotiation (update_param merges remote into local)
1495            let mut claimed = [false; 128];
1496            let mut unlocked = std::collections::HashSet::new();
1497            local_params.update_param(
1498                &[remote_params],
1499                &mut claimed,
1500                false, // remote is controlling (we're answering)
1501                &mut unlocked,
1502            );
1503
1504            // Verify sprop-max-don-diff was adopted from remote
1505            assert_eq!(
1506                local_params.spec.format.sprop_max_don_diff,
1507                Some(32),
1508                "sprop-max-don-diff should be adopted from remote after negotiation"
1509            );
1510
1511            // Verify packetizer is initialized with DONL enabled
1512            let donl_enabled = local_params.spec.format.sprop_max_don_diff.unwrap_or(0) > 0;
1513            assert!(
1514                donl_enabled,
1515                "DONL should be enabled when sprop-max-don-diff > 0"
1516            );
1517
1518            let mut pack = CodecPacketizer::new(
1519                local_params.spec.codec,
1520                crate::format::Vp9PacketizerMode::default(),
1521            );
1522            if let CodecPacketizer::H265(ref mut h265) = pack {
1523                h265.with_donl(donl_enabled);
1524            }
1525
1526            // Packetize a NAL — should include DONL field (2 extra bytes)
1527            let nalu = vec![0x02, 0x01, 0xAA, 0xBB];
1528            let packets = pack.packetize(1200, &nalu).unwrap();
1529            assert_eq!(packets.len(), 1);
1530            assert_eq!(
1531                packets[0].len(),
1532                nalu.len() + 2, // +2 for DONL
1533                "Packetized output should include 2-byte DONL field"
1534            );
1535
1536            // Verify depacketizer is initialized with DONL enabled
1537            let mut depack: CodecDepacketizer = local_params.spec.codec.into();
1538            if let CodecDepacketizer::H265(ref mut h265) = depack {
1539                h265.with_donl(donl_enabled);
1540            }
1541
1542            // Depacketize the packet — should correctly strip DONL
1543            use crate::packet::{CodecExtra, Depacketizer};
1544            let mut out = Vec::new();
1545            let mut extra = CodecExtra::None;
1546            if let CodecDepacketizer::H265(ref mut h265) = depack {
1547                h265.depacketize(&packets[0], &mut out, &mut extra).unwrap();
1548            }
1549
1550            // Output should be Annex-B: start code + original NAL
1551            assert_eq!(&out[0..4], &[0x00, 0x00, 0x00, 0x01]);
1552            assert_eq!(
1553                &out[4..],
1554                &nalu[..],
1555                "Depacketized NAL should match original"
1556            );
1557        }
1558
1559        /// Test that sprop-max-don-diff=0 from remote does NOT enable DONL.
1560        #[test]
1561        fn test_sprop_max_don_diff_zero_disables_donl() {
1562            let local_spec = h265_codec_spec(1, 0, 93);
1563            let mut local_params = PayloadParams::new(
1564                Pt::new_with_value(102),
1565                Some(Pt::new_with_value(103)),
1566                local_spec,
1567            );
1568
1569            // Remote offers with sprop-max-don-diff=0 (no reordering)
1570            let mut remote_spec = h265_codec_spec(1, 0, 93);
1571            remote_spec.format.sprop_max_don_diff = Some(0);
1572            let remote_params = PayloadParams::new(
1573                Pt::new_with_value(102),
1574                Some(Pt::new_with_value(103)),
1575                remote_spec,
1576            );
1577
1578            let mut claimed = [false; 128];
1579            let mut unlocked = std::collections::HashSet::new();
1580            local_params.update_param(&[remote_params], &mut claimed, false, &mut unlocked);
1581
1582            assert_eq!(local_params.spec.format.sprop_max_don_diff, Some(0));
1583            let donl_enabled = local_params.spec.format.sprop_max_don_diff.unwrap_or(0) > 0;
1584            assert!(
1585                !donl_enabled,
1586                "DONL should NOT be enabled when sprop-max-don-diff=0"
1587            );
1588
1589            // Packetize without DONL — packet should be same size as NAL
1590            let nalu = vec![0x02, 0x01, 0xAA, 0xBB];
1591            let mut pack = crate::packet::CodecPacketizer::new(
1592                local_params.spec.codec,
1593                crate::format::Vp9PacketizerMode::default(),
1594            );
1595            // Don't call with_donl(true) since donl_enabled is false
1596            let packets = pack.packetize(1200, &nalu).unwrap();
1597            assert_eq!(
1598                packets[0].len(),
1599                nalu.len(),
1600                "No DONL field when sprop-max-don-diff=0"
1601            );
1602        }
1603
1604        /// Test that missing sprop-max-don-diff from remote preserves local value.
1605        #[test]
1606        fn test_sprop_max_don_diff_absent_preserves_local() {
1607            // Local has sprop-max-don-diff=16
1608            let mut local_spec = h265_codec_spec(1, 0, 93);
1609            local_spec.format.sprop_max_don_diff = Some(16);
1610            let mut local_params = PayloadParams::new(
1611                Pt::new_with_value(102),
1612                Some(Pt::new_with_value(103)),
1613                local_spec,
1614            );
1615
1616            // Remote offers without sprop-max-don-diff
1617            let remote_spec = h265_codec_spec(1, 0, 93);
1618            assert!(remote_spec.format.sprop_max_don_diff.is_none());
1619            let remote_params = PayloadParams::new(
1620                Pt::new_with_value(102),
1621                Some(Pt::new_with_value(103)),
1622                remote_spec,
1623            );
1624
1625            let mut claimed = [false; 128];
1626            let mut unlocked = std::collections::HashSet::new();
1627            local_params.update_param(&[remote_params], &mut claimed, false, &mut unlocked);
1628
1629            // Local value should be preserved (remote didn't override)
1630            assert_eq!(
1631                local_params.spec.format.sprop_max_don_diff,
1632                Some(16),
1633                "Local sprop-max-don-diff should be preserved when remote doesn't specify it"
1634            );
1635        }
1636    }
1637
1638    mod h266 {
1639        use super::*;
1640        use crate::packet::H266ProfileTierLevel;
1641        use crate::packet::Packetizer;
1642
1643        fn h266_codec_spec(profile_id: u8, tier_flag: u8, level_id: u8) -> CodecSpec {
1644            CodecSpec {
1645                codec: Codec::H266,
1646                clock_rate: Frequency::NINETY_KHZ,
1647                channels: None,
1648                format: FormatParams {
1649                    h266_profile_tier_level: Some(
1650                        H266ProfileTierLevel::new(profile_id, tier_flag, level_id).unwrap(),
1651                    ),
1652                    ..Default::default()
1653                },
1654            }
1655        }
1656
1657        fn h266_codec_spec_profile_only(profile_id: u32) -> CodecSpec {
1658            CodecSpec {
1659                codec: Codec::H266,
1660                clock_rate: Frequency::NINETY_KHZ,
1661                channels: None,
1662                format: FormatParams {
1663                    profile_id: Some(profile_id),
1664                    ..Default::default()
1665                },
1666            }
1667        }
1668
1669        /// Test basic H.266 profile/tier/level matching scenarios.
1670        /// Verifies that full ProfileTierLevel parameters are matched correctly.
1671        #[test]
1672        fn test_profile_tier_level_matching() {
1673            struct Case {
1674                c0: CodecSpec,
1675                c1: CodecSpec,
1676                must_match: bool,
1677                msg: &'static str,
1678            }
1679
1680            let cases = [
1681                // Same profile, tier, level -> should match
1682                Case {
1683                    c0: h266_codec_spec(1, 0, 51), // Main, Main tier, Level 3.1
1684                    c1: h266_codec_spec(1, 0, 51),
1685                    must_match: true,
1686                    msg: "Same profile (Main), tier (Main), level (3.1) should match",
1687                },
1688                // Same profile and tier, offered level lower -> should match
1689                Case {
1690                    c0: h266_codec_spec(1, 0, 64), // Main, Main tier, Level 4.0
1691                    c1: h266_codec_spec(1, 0, 51), // Main, Main tier, Level 3.1
1692                    must_match: true,
1693                    msg: "Same profile/tier, offered level 3.1 < configured 4.0 should match",
1694                },
1695                // Same profile and tier, offered level higher -> should still match (with penalty)
1696                Case {
1697                    c0: h266_codec_spec(1, 0, 51), // Main, Main tier, Level 3.1
1698                    c1: h266_codec_spec(1, 0, 64), // Main, Main tier, Level 4.0
1699                    must_match: true,
1700                    msg: "Same profile/tier, offered level 4.0 > configured 3.1 should match (penalized)",
1701                },
1702                // Different profiles -> should NOT match
1703                Case {
1704                    c0: h266_codec_spec(1, 0, 51),  // Main, Main tier, Level 3.1
1705                    c1: h266_codec_spec(33, 0, 51), // Main10, Main tier, Level 3.1
1706                    must_match: false,
1707                    msg: "Different profiles (Main vs Main10) should NOT match",
1708                },
1709                // Different tiers -> should NOT match
1710                Case {
1711                    c0: h266_codec_spec(1, 0, 51), // Main, Main tier, Level 3.1
1712                    c1: h266_codec_spec(1, 1, 51), // Main, High tier, Level 3.1
1713                    must_match: false,
1714                    msg: "Different tiers (Main vs High) should NOT match",
1715                },
1716                // Main10 profile, same tier, lower level -> should match
1717                Case {
1718                    c0: h266_codec_spec(33, 0, 83), // Main10, Main tier, Level 5.1
1719                    c1: h266_codec_spec(33, 0, 64), // Main10, Main tier, Level 4.0
1720                    must_match: true,
1721                    msg: "Main10 profile, offered level 4.0 < configured 5.1 should match",
1722                },
1723                // High tier, multiple levels down -> should match
1724                Case {
1725                    c0: h266_codec_spec(1, 1, 83), // Main, High tier, Level 5.1
1726                    c1: h266_codec_spec(1, 1, 51), // Main, High tier, Level 3.1
1727                    must_match: true,
1728                    msg: "High tier, offered level 3.1 < configured 5.1 should match",
1729                },
1730            ];
1731
1732            for Case {
1733                c0,
1734                c1,
1735                must_match,
1736                msg,
1737            } in cases.into_iter()
1738            {
1739                let matched = PayloadParams::match_h266_score(c0, c1).is_some();
1740                assert_eq!(matched, must_match, "{msg}\nc0: {c0:#?}\nc1: {c1:#?}");
1741            }
1742        }
1743
1744        /// Test H.266 level matching with exact scores.
1745        /// Verifies that the score decrements based on level difference.
1746        #[test]
1747        fn test_level_matching_scores() {
1748            struct Case {
1749                c0: CodecSpec,
1750                c1: CodecSpec,
1751                expected: Option<usize>,
1752                msg: &'static str,
1753            }
1754
1755            let cases = [
1756                // Exact match -> score 100
1757                Case {
1758                    c0: h266_codec_spec(1, 0, 51), // Main, Main tier, Level 3.1
1759                    c1: h266_codec_spec(1, 0, 51),
1760                    expected: Some(PayloadParams::EXACT_MATCH_SCORE),
1761                    msg: "Exact match should return score 100",
1762                },
1763                // One level down -> score 100 - 1
1764                Case {
1765                    c0: h266_codec_spec(1, 0, 64), // Main, Main tier, Level 4.0
1766                    c1: h266_codec_spec(1, 0, 51), // Main, Main tier, Level 3.1
1767                    expected: Some(PayloadParams::EXACT_MATCH_SCORE - 1),
1768                    msg: "One level difference should return score 99",
1769                },
1770                // Two levels down -> score 100 - 2
1771                Case {
1772                    c0: h266_codec_spec(1, 0, 67), // Main, Main tier, Level 4.1
1773                    c1: h266_codec_spec(1, 0, 51), // Main, Main tier, Level 3.1
1774                    expected: Some(PayloadParams::EXACT_MATCH_SCORE - 2),
1775                    msg: "Two level difference should return score 98",
1776                },
1777                // Multiple levels down
1778                Case {
1779                    c0: h266_codec_spec(1, 0, 83), // Main, Main tier, Level 5.1
1780                    c1: h266_codec_spec(1, 0, 51), // Main, Main tier, Level 3.1
1781                    expected: Some(PayloadParams::EXACT_MATCH_SCORE - 4),
1782                    msg: "Four level difference (5.1 to 3.1) should return score 96",
1783                },
1784                // Offered level higher -> still matches, penalized by 1 ordinal
1785                Case {
1786                    c0: h266_codec_spec(1, 0, 51), // Main, Main tier, Level 3.1
1787                    c1: h266_codec_spec(1, 0, 64), // Main, Main tier, Level 4.0
1788                    expected: Some(PayloadParams::EXACT_MATCH_SCORE - 1),
1789                    msg: "Offered level one higher than configured should return score 99",
1790                },
1791                // Different profiles -> None
1792                Case {
1793                    c0: h266_codec_spec(1, 0, 51),  // Main, Main tier, Level 3.1
1794                    c1: h266_codec_spec(33, 0, 51), // Main10, Main tier, Level 3.1
1795                    expected: None,
1796                    msg: "Different profiles should return None",
1797                },
1798                // Different tiers -> None
1799                Case {
1800                    c0: h266_codec_spec(1, 0, 51), // Main, Main tier, Level 3.1
1801                    c1: h266_codec_spec(1, 1, 51), // Main, High tier, Level 3.1
1802                    expected: None,
1803                    msg: "Different tiers should return None",
1804                },
1805            ];
1806
1807            for Case {
1808                c0,
1809                c1,
1810                expected,
1811                msg,
1812            } in cases.into_iter()
1813            {
1814                assert_eq!(
1815                    PayloadParams::match_h266_score(c0, c1),
1816                    expected,
1817                    "{msg}\nc0: {c0:#?}\nc1: {c1:#?}"
1818                );
1819            }
1820        }
1821
1822        /// Test H.266 profile-only matching (for Chrome compatibility).
1823        /// When only profile-id is provided without tier/level, match on profile only.
1824        #[test]
1825        fn test_profile_only_matching() {
1826            struct Case {
1827                c0: CodecSpec,
1828                c1: CodecSpec,
1829                expected: Option<usize>,
1830                msg: &'static str,
1831            }
1832
1833            let cases = [
1834                // Both have profile-only, same profile -> score 90
1835                Case {
1836                    c0: h266_codec_spec_profile_only(1), // Main
1837                    c1: h266_codec_spec_profile_only(1), // Main
1838                    expected: Some(PayloadParams::PROFILE_ONLY_MATCH_SCORE),
1839                    msg: "Profile-only match (Main) should return score 90",
1840                },
1841                // Both have profile-only, different profiles -> None
1842                Case {
1843                    c0: h266_codec_spec_profile_only(1),  // Main
1844                    c1: h266_codec_spec_profile_only(33), // Main10
1845                    expected: None,
1846                    msg: "Profile-only with different profiles should return None",
1847                },
1848                // One has full PTL, other has profile-only, same profile -> score 90
1849                Case {
1850                    c0: h266_codec_spec(1, 0, 51),       // Main, Main tier, Level 3.1
1851                    c1: h266_codec_spec_profile_only(1), // Main
1852                    expected: Some(PayloadParams::PROFILE_ONLY_MATCH_SCORE),
1853                    msg: "Mixed PTL and profile-only with matching profile should return score 90",
1854                },
1855                // One has full PTL, other has profile-only, different profiles -> None
1856                Case {
1857                    c0: h266_codec_spec(1, 0, 51),        // Main, Main tier, Level 3.1
1858                    c1: h266_codec_spec_profile_only(33), // Main10
1859                    expected: None,
1860                    msg: "Mixed PTL and profile-only with different profiles should return None",
1861                },
1862                // Reverse: profile-only vs full PTL, same profile -> score 90
1863                Case {
1864                    c0: h266_codec_spec_profile_only(1), // Main
1865                    c1: h266_codec_spec(1, 0, 51),       // Main, Main tier, Level 3.1
1866                    expected: Some(PayloadParams::PROFILE_ONLY_MATCH_SCORE),
1867                    msg: "Profile-only vs full PTL with matching profile should return score 90",
1868                },
1869            ];
1870
1871            for Case {
1872                c0,
1873                c1,
1874                expected,
1875                msg,
1876            } in cases.into_iter()
1877            {
1878                assert_eq!(
1879                    PayloadParams::match_h266_score(c0, c1),
1880                    expected,
1881                    "{msg}\nc0: {c0:#?}\nc1: {c1:#?}"
1882                );
1883            }
1884        }
1885
1886        /// Test negative cases for H.266 matching to ensure proper rejection.
1887        #[test]
1888        fn test_negative_cases() {
1889            struct Case {
1890                c0: CodecSpec,
1891                c1: CodecSpec,
1892                msg: &'static str,
1893            }
1894
1895            let cases = [
1896                // Profile mismatch with full PTL
1897                Case {
1898                    c0: h266_codec_spec(1, 0, 51),  // Main, Main tier, Level 3.1
1899                    c1: h266_codec_spec(33, 0, 51), // Main10, Main tier, Level 3.1
1900                    msg: "Profile mismatch (Main vs Main10) must not match",
1901                },
1902                // Tier mismatch
1903                Case {
1904                    c0: h266_codec_spec(1, 0, 51), // Main, Main tier, Level 3.1
1905                    c1: h266_codec_spec(1, 1, 51), // Main, High tier, Level 3.1
1906                    msg: "Tier mismatch (Main vs High) must not match",
1907                },
1908                // All three different (profile+tier mismatch rejects)
1909                Case {
1910                    c0: h266_codec_spec(1, 0, 51),  // Main, Main tier, Level 3.1
1911                    c1: h266_codec_spec(33, 1, 83), // Main10, High tier, Level 5.1
1912                    msg: "Profile and tier different must not match",
1913                },
1914                // Profile-only mismatch
1915                Case {
1916                    c0: h266_codec_spec_profile_only(1),  // Main
1917                    c1: h266_codec_spec_profile_only(33), // Main10
1918                    msg: "Profile-only mismatch must not match",
1919                },
1920                // Mixed full PTL vs profile-only with different profiles
1921                Case {
1922                    c0: h266_codec_spec(33, 0, 51),      // Main10, Main tier, Level 3.1
1923                    c1: h266_codec_spec_profile_only(1), // Main
1924                    msg: "Full PTL (Main10) vs profile-only (Main) must not match",
1925                },
1926            ];
1927
1928            for Case { c0, c1, msg } in cases.into_iter() {
1929                assert_eq!(
1930                    PayloadParams::match_h266_score(c0, c1),
1931                    None,
1932                    "{msg}\nc0: {c0:#?}\nc1: {c1:#?}"
1933                );
1934            }
1935        }
1936
1937        /// Test that sprop-max-don-diff is adopted from remote SDP during negotiation,
1938        /// and that packetizer/depacketizer are correctly initialized with DONL enabled.
1939        #[test]
1940        fn test_sprop_max_don_diff_negotiation_enables_donl() {
1941            use crate::packet::{CodecDepacketizer, CodecPacketizer};
1942
1943            // Local config: no sprop-max-don-diff (default)
1944            let local_spec = h266_codec_spec(1, 0, 51);
1945            let mut local_params = PayloadParams::new(
1946                Pt::new_with_value(102),
1947                Some(Pt::new_with_value(103)),
1948                local_spec,
1949            );
1950            assert_eq!(
1951                local_params.spec.format.sprop_max_don_diff, None,
1952                "Local should have no sprop-max-don-diff initially"
1953            );
1954
1955            // Remote offers H.266 with sprop-max-don-diff=32
1956            let mut remote_spec = h266_codec_spec(1, 0, 51);
1957            remote_spec.format.sprop_max_don_diff = Some(32);
1958            let remote_params = PayloadParams::new(
1959                Pt::new_with_value(102),
1960                Some(Pt::new_with_value(103)),
1961                remote_spec,
1962            );
1963
1964            // Simulate SDP negotiation (update_param merges remote into local)
1965            let mut claimed = [false; 128];
1966            let mut unlocked = std::collections::HashSet::new();
1967            local_params.update_param(
1968                &[remote_params],
1969                &mut claimed,
1970                false, // remote is controlling (we're answering)
1971                &mut unlocked,
1972            );
1973
1974            // Verify sprop-max-don-diff was adopted from remote
1975            assert_eq!(
1976                local_params.spec.format.sprop_max_don_diff,
1977                Some(32),
1978                "sprop-max-don-diff should be adopted from remote after negotiation"
1979            );
1980
1981            // Verify packetizer is initialized with DONL enabled
1982            let donl_enabled = local_params.spec.format.sprop_max_don_diff.unwrap_or(0) > 0;
1983            assert!(
1984                donl_enabled,
1985                "DONL should be enabled when sprop-max-don-diff > 0"
1986            );
1987
1988            let mut pack = CodecPacketizer::new(
1989                local_params.spec.codec,
1990                crate::format::Vp9PacketizerMode::default(),
1991            );
1992            if let CodecPacketizer::H266(ref mut h266) = pack {
1993                h266.with_donl(donl_enabled);
1994            }
1995
1996            // Packetize a NAL — should include DONL field (2 extra bytes)
1997            let nalu = vec![0x00, 0x09, 0xAA, 0xBB];
1998            let packets = pack.packetize(1200, &nalu).unwrap();
1999            assert_eq!(packets.len(), 1);
2000            assert_eq!(
2001                packets[0].len(),
2002                nalu.len() + 2, // +2 for DONL
2003                "Packetized output should include 2-byte DONL field"
2004            );
2005
2006            // Verify depacketizer is initialized with DONL enabled
2007            let mut depack: CodecDepacketizer = local_params.spec.codec.into();
2008            if let CodecDepacketizer::H266(ref mut h266) = depack {
2009                h266.with_donl(donl_enabled);
2010            }
2011
2012            // Depacketize the packet — should correctly strip DONL
2013            use crate::packet::{CodecExtra, Depacketizer};
2014            let mut out = Vec::new();
2015            let mut extra = CodecExtra::None;
2016            if let CodecDepacketizer::H266(ref mut h266) = depack {
2017                h266.depacketize(&packets[0], &mut out, &mut extra).unwrap();
2018            }
2019
2020            // Output should be Annex-B: start code + original NAL
2021            assert_eq!(&out[0..4], &[0x00, 0x00, 0x00, 0x01]);
2022            assert_eq!(
2023                &out[4..],
2024                &nalu[..],
2025                "Depacketized NAL should match original"
2026            );
2027        }
2028
2029        /// Test that missing sprop-max-don-diff from remote preserves local value.
2030        #[test]
2031        fn test_sprop_max_don_diff_absent_preserves_local() {
2032            // Local has sprop-max-don-diff=16
2033            let mut local_spec = h266_codec_spec(1, 0, 51);
2034            local_spec.format.sprop_max_don_diff = Some(16);
2035            let mut local_params = PayloadParams::new(
2036                Pt::new_with_value(102),
2037                Some(Pt::new_with_value(103)),
2038                local_spec,
2039            );
2040
2041            // Remote offers without sprop-max-don-diff
2042            let remote_spec = h266_codec_spec(1, 0, 51);
2043            assert!(remote_spec.format.sprop_max_don_diff.is_none());
2044            let remote_params = PayloadParams::new(
2045                Pt::new_with_value(102),
2046                Some(Pt::new_with_value(103)),
2047                remote_spec,
2048            );
2049
2050            let mut claimed = [false; 128];
2051            let mut unlocked = std::collections::HashSet::new();
2052            local_params.update_param(&[remote_params], &mut claimed, false, &mut unlocked);
2053
2054            // Local value should be preserved (remote didn't override)
2055            assert_eq!(
2056                local_params.spec.format.sprop_max_don_diff,
2057                Some(16),
2058                "Local sprop-max-don-diff should be preserved when remote doesn't specify it"
2059            );
2060        }
2061
2062        /// Test that sprop-max-don-diff=0 from remote does NOT enable DONL.
2063        #[test]
2064        fn test_sprop_max_don_diff_zero_disables_donl() {
2065            let local_spec = h266_codec_spec(1, 0, 51);
2066            let mut local_params = PayloadParams::new(
2067                Pt::new_with_value(102),
2068                Some(Pt::new_with_value(103)),
2069                local_spec,
2070            );
2071
2072            // Remote offers with sprop-max-don-diff=0 (no reordering)
2073            let mut remote_spec = h266_codec_spec(1, 0, 51);
2074            remote_spec.format.sprop_max_don_diff = Some(0);
2075            let remote_params = PayloadParams::new(
2076                Pt::new_with_value(102),
2077                Some(Pt::new_with_value(103)),
2078                remote_spec,
2079            );
2080
2081            let mut claimed = [false; 128];
2082            let mut unlocked = std::collections::HashSet::new();
2083            local_params.update_param(&[remote_params], &mut claimed, false, &mut unlocked);
2084
2085            assert_eq!(local_params.spec.format.sprop_max_don_diff, Some(0));
2086            let donl_enabled = local_params.spec.format.sprop_max_don_diff.unwrap_or(0) > 0;
2087            assert!(
2088                !donl_enabled,
2089                "DONL should NOT be enabled when sprop-max-don-diff=0"
2090            );
2091
2092            // Packetize without DONL — packet should be same size as NAL
2093            let nalu = vec![0x00, 0x09, 0xAA, 0xBB];
2094            let mut pack = crate::packet::CodecPacketizer::new(
2095                local_params.spec.codec,
2096                crate::format::Vp9PacketizerMode::default(),
2097            );
2098            // Don't enable DONL since donl_enabled is false
2099            let packets = pack.packetize(1200, &nalu).unwrap();
2100            assert_eq!(
2101                packets[0].len(),
2102                nalu.len(),
2103                "No DONL field when sprop-max-don-diff=0"
2104            );
2105        }
2106    }
2107
2108    mod amr_wb {
2109        use super::*;
2110
2111        fn amr_wb(channels: Option<u8>, format: FormatParams) -> PayloadParams {
2112            let spec = CodecSpec {
2113                codec: Codec::AmrWb,
2114                clock_rate: Frequency::SIXTEEN_KHZ,
2115                channels,
2116                format,
2117            };
2118            PayloadParams::new(122.into(), None, spec)
2119        }
2120
2121        fn octet_aligned() -> FormatParams {
2122            FormatParams {
2123                octet_align: Some(true),
2124                ..Default::default()
2125            }
2126        }
2127
2128        #[test]
2129        fn matching() {
2130            let local = amr_wb(Some(1), octet_aligned());
2131            let score = |remote: PayloadParams| local.match_score(&remote);
2132
2133            assert!(score(local).is_some());
2134            assert!(score(amr_wb(None, octet_aligned())).is_some());
2135            assert!(score(amr_wb(Some(1), FormatParams::default())).is_none());
2136
2137            let bandwidth_efficient = FormatParams {
2138                octet_align: Some(false),
2139                ..Default::default()
2140            };
2141            let default = amr_wb(None, FormatParams::default());
2142            assert!(
2143                default
2144                    .match_score(&amr_wb(None, bandwidth_efficient))
2145                    .is_some()
2146            );
2147
2148            let modes = |mode_set| FormatParams {
2149                mode_set: Some(mode_set),
2150                ..octet_aligned()
2151            };
2152            let restricted = amr_wb(Some(1), modes(0b111));
2153            assert!(score(restricted).is_some_and(|s| Some(s) < score(local)));
2154            assert!(restricted.match_score(&amr_wb(None, modes(0b11))).is_none());
2155
2156            let stereo = amr_wb(Some(2), octet_aligned());
2157            assert!(stereo.match_score(&stereo).is_none());
2158        }
2159
2160        #[test]
2161        fn update_param_mirrors_layout_channels_and_mode_set() {
2162            let mut local = amr_wb(Some(1), FormatParams::default());
2163            let remote_format = FormatParams {
2164                octet_align: Some(false),
2165                mode_set: Some(0b111),
2166                ..Default::default()
2167            };
2168            let remote = amr_wb(None, remote_format);
2169
2170            local.update_param(&[remote], &mut [false; 128], false, &mut HashSet::new());
2171
2172            assert_eq!(local.spec.channels, None);
2173            assert_eq!(local.spec.format, remote_format);
2174        }
2175    }
2176}