Skip to main content

str0m/format/
codec_config.rs

1// Changed by Alakazam Labs for sew-str0m; the fork's patches are listed in its README.
2use std::collections::HashSet;
3use std::ops::{Deref, DerefMut};
4
5use crate::packet::H266ProfileTierLevel;
6use crate::packet::MAX_RED_RECOVERY_DEPTH;
7use crate::packet::MediaKind;
8use crate::rtp_::Pt;
9use crate::rtp_::{Direction, Frequency};
10
11use super::codec::{Codec, CodecSpec};
12use super::format_params::FormatParams;
13use super::payload_params::{Claimed, PREFERED_RANGES, PayloadParams};
14
15/// Default payload type for PCMU (G.711 μ-law).
16pub(crate) const PT_PCMU: Pt = Pt::new_with_value(0);
17
18/// Default payload type for PCMA (G.711 A-law).
19pub(crate) const PT_PCMA: Pt = Pt::new_with_value(8);
20
21/// Default payload type for G722.
22pub(crate) const PT_G722: Pt = Pt::new_with_value(9);
23
24/// Static payload type for Comfort Noise at 8000 Hz (RFC 3389).
25pub(crate) const PT_COMFORT_NOISE: Pt = Pt::new_with_value(13);
26
27/// Default payload type for VP8.
28pub(crate) const PT_VP8: Pt = Pt::new_with_value(96);
29
30/// Default payload type for VP8 RTX.
31pub(crate) const PT_VP8_RTX: Pt = Pt::new_with_value(97);
32
33/// Default payload type for VP9 profile 0.
34pub(crate) const PT_VP9: Pt = Pt::new_with_value(98);
35
36/// Default payload type for VP9 profile 0 RTX.
37pub(crate) const PT_VP9_RTX: Pt = Pt::new_with_value(99);
38
39/// Default payload type for AV1.
40pub(crate) const PT_AV1: Pt = Pt::new_with_value(45);
41
42/// Default payload type for AV1 RTX.
43pub(crate) const PT_AV1_RTX: Pt = Pt::new_with_value(46);
44
45/// Default payload type for H265.
46pub(crate) const PT_H265: Pt = Pt::new_with_value(102);
47
48/// Default payload type for H265 RTX.
49pub(crate) const PT_H265_RTX: Pt = Pt::new_with_value(103);
50
51/// Default payload type for H266 (VVC).
52pub(crate) const PT_H266: Pt = Pt::new_with_value(104);
53
54/// Default payload type for H266 RTX.
55pub(crate) const PT_H266_RTX: Pt = Pt::new_with_value(105);
56
57/// Default payload type for Opus.
58pub(crate) const PT_OPUS: Pt = Pt::new_with_value(111);
59
60/// Default RFC 2198 RED payload types, one per audio codec. RED links a single primary codec
61/// via `a=fmtp` and carries that codec's clock rate in `a=rtpmap`, so each audio codec that has
62/// RED needs its own RED payload type. These are the defaults; they are reassigned on conflict
63/// during negotiation, mirroring RTX. They stay below 64 so they are never mistaken for RTCP by
64/// the RTP/RTCP demultiplexer (which reserves payload types 64..=95, see `MultiplexKind`).
65pub(crate) const PT_RED: Pt = Pt::new_with_value(63);
66pub(crate) const PT_G722_RED: Pt = Pt::new_with_value(62);
67pub(crate) const PT_PCMU_RED: Pt = Pt::new_with_value(61);
68pub(crate) const PT_PCMA_RED: Pt = Pt::new_with_value(60);
69
70/// Default payload type for AMR-WB.
71pub(crate) const PT_AMR_WB: Pt = Pt::new_with_value(122);
72
73/// Session config for all codecs.
74#[derive(Debug, Clone, Default)]
75pub struct CodecConfig {
76    params: Vec<PayloadParams>,
77    /// RFC 2198 RED send-side redundancy pattern: how many packets back each redundant level
78    /// carries. Empty means the default single level `[1]` (see [`Self::red_distances`]).
79    red_distances: Box<[u32]>,
80}
81
82impl CodecConfig {
83    /// Creates a new empty config.
84    pub fn empty() -> Self {
85        CodecConfig::default()
86    }
87
88    /// Creates a new config from payload params
89    pub fn new_from_payload_params(payload_params: Vec<PayloadParams>) -> Self {
90        CodecConfig {
91            params: payload_params,
92            ..Default::default()
93        }
94    }
95
96    /// Creates a new config with all default configurations enabled.
97    pub fn new_with_defaults() -> Self {
98        let mut c = Self::empty();
99        c.enable_opus(true, false);
100
101        c.enable_vp8(true);
102        c.enable_h264(true);
103        c.enable_h265(true);
104        // H266/VVC off by default: no browser supports it.
105        c.enable_h266(false);
106        c.enable_vp9(true);
107        c.enable_av1(true);
108
109        c
110    }
111
112    /// Returns a reference to the payload parameters.
113    pub fn params(&self) -> &[PayloadParams] {
114        &self.params
115    }
116
117    /// Clear all configured configs.
118    pub fn clear(&mut self) {
119        self.params.clear();
120    }
121
122    /// Manually configure a payload type. For telephone events, configure one
123    /// payload type per supported RTP clock rate; no rates are added automatically.
124    pub fn add_config(
125        &mut self,
126        pt: Pt,
127        resend: Option<Pt>,
128        codec: Codec,
129        clock_rate: Frequency,
130        channels: Option<u8>,
131        format: FormatParams,
132    ) {
133        let (fb_transport_cc, fb_fir, fb_nack, fb_pli, fb_remb) = if codec.is_video() {
134            (true, true, true, true, true)
135        } else {
136            (true, false, false, false, false)
137        };
138
139        let p = PayloadParams {
140            pt,
141            spec: CodecSpec {
142                codec,
143                clock_rate,
144                channels,
145                format,
146            },
147            resend,
148            fb_transport_cc,
149            fb_fir,
150            fb_nack,
151            fb_pli,
152            fb_remb,
153            red: None,
154            locked: false,
155            rtx_declined: false,
156        };
157
158        self.params.push(p);
159    }
160
161    fn add_static_config(&mut self, pt: Pt) {
162        let spec = CodecSpec::from_static_pt(pt).expect("known static payload type");
163        self.add_config(
164            pt,
165            None,
166            spec.codec,
167            spec.clock_rate,
168            spec.channels,
169            spec.format,
170        );
171    }
172
173    /// Convenience for adding a h264 payload type.
174    pub fn add_h264(
175        &mut self,
176        pt: Pt,
177        resend: Option<Pt>,
178        packetization_mode: bool,
179        profile_level_id: u32,
180    ) {
181        self.add_config(
182            pt,
183            resend,
184            Codec::H264,
185            Frequency::NINETY_KHZ,
186            None,
187            FormatParams {
188                level_asymmetry_allowed: Some(true),
189                packetization_mode: if packetization_mode { Some(1) } else { Some(0) },
190                profile_level_id: Some(profile_level_id),
191                ..Default::default()
192            },
193        )
194    }
195
196    /// Convenience for adding a h265 payload type.
197    pub fn add_h265(
198        &mut self,
199        pt: Pt,
200        resend: Option<Pt>,
201        profile_id: u8,
202        tier_flag: u8,
203        level_id: u8,
204    ) {
205        use crate::packet::H265ProfileTierLevel;
206
207        let ptl = H265ProfileTierLevel::new(profile_id, tier_flag, level_id)
208            .unwrap_or(H265ProfileTierLevel::FALLBACK);
209
210        self.add_config(
211            pt,
212            resend,
213            Codec::H265,
214            Frequency::NINETY_KHZ,
215            None,
216            FormatParams {
217                h265_profile_tier_level: Some(ptl),
218                ..Default::default()
219            },
220        )
221    }
222
223    /// Convenience for adding a PCM u-law payload type, optionally with RFC 2198 RED.
224    ///
225    /// `use_red` folds a RED payload type onto this codec so the receiver can recover packet loss
226    /// without retransmission, at the cost of extra audio payload size.
227    pub fn enable_pcmu(&mut self, enabled: bool, use_red: bool) {
228        self.params.retain(|c| c.spec.codec != Codec::PCMU);
229        if !enabled {
230            return;
231        }
232        self.add_static_config(PT_PCMU);
233        if use_red {
234            self.set_red_pt(Codec::PCMU, PT_PCMU_RED);
235        }
236    }
237
238    /// Convenience for adding a PCM a-law payload type, optionally with RFC 2198 RED.
239    ///
240    /// See [`Self::enable_pcmu`] for `use_red`.
241    pub fn enable_pcma(&mut self, enabled: bool, use_red: bool) {
242        self.params.retain(|c| c.spec.codec != Codec::PCMA);
243        if !enabled {
244            return;
245        }
246        self.add_static_config(PT_PCMA);
247        if use_red {
248            self.set_red_pt(Codec::PCMA, PT_PCMA_RED);
249        }
250    }
251
252    /// Convenience for adding a G722 payload type.
253    ///
254    /// G722 samples audio at 16 kHz, but per RFC 3551 §4.5.2 the RTP clock rate is
255    /// 8000 Hz. The codec is configured at 16 kHz here; str0m maps to 8 kHz for the
256    /// SDP `a=rtpmap` line and when converting to/from RTP timestamps. See
257    /// <https://en.wikipedia.org/wiki/RTP_payload_formats#cite_note-55>
258    ///
259    /// See [`Self::enable_pcmu`] for `use_red`.
260    pub fn enable_g722(&mut self, enabled: bool, use_red: bool) {
261        self.params.retain(|c| c.spec.codec != Codec::G722);
262        if !enabled {
263            return;
264        }
265        self.add_static_config(PT_G722);
266        if use_red {
267            self.set_red_pt(Codec::G722, PT_G722_RED);
268        }
269    }
270
271    /// Add the static Comfort Noise payload type at 8000 Hz.
272    ///
273    /// Higher clock rates require dynamic payload types and can be configured
274    /// with [`CodecConfig::add_config`].
275    pub fn enable_comfort_noise(&mut self, enabled: bool) {
276        self.params.retain(|c| c.spec.codec != Codec::CN);
277        if !enabled {
278            return;
279        }
280        self.add_static_config(PT_COMFORT_NOISE);
281    }
282
283    /// Add a default AMR-WB payload type.
284    pub fn enable_amr_wb(&mut self, enabled: bool) {
285        self.params.retain(|c| c.spec.codec != Codec::AmrWb);
286        if !enabled {
287            return;
288        }
289        self.add_config(
290            PT_AMR_WB,
291            None,
292            Codec::AmrWb,
293            Frequency::SIXTEEN_KHZ,
294            Some(1),
295            FormatParams {
296                octet_align: Some(true),
297                ..Default::default()
298            },
299        );
300    }
301
302    /// Add a default OPUS payload type, optionally with RFC 2198 RED.
303    ///
304    /// See [`Self::enable_pcmu`] for `use_red`.
305    pub fn enable_opus(&mut self, enabled: bool, use_red: bool) {
306        self.params.retain(|c| c.spec.codec != Codec::Opus);
307        if !enabled {
308            return;
309        }
310        self.add_config(
311            PT_OPUS,
312            None,
313            Codec::Opus,
314            Frequency::FORTY_EIGHT_KHZ,
315            Some(2),
316            FormatParams {
317                min_p_time: Some(10),
318                use_inband_fec: Some(true),
319                ..Default::default()
320            },
321        );
322        if use_red {
323            self.set_red_pt(Codec::Opus, PT_RED);
324        }
325    }
326
327    /// Fold the given RFC 2198 RED payload type onto the enabled param for `codec`. Used by the
328    /// audio enable fns when `use_red` is set; each audio codec has its own RED payload type so the
329    /// `a=rtpmap` entries (which carry each codec's clock rate) don't collide in SDP.
330    fn set_red_pt(&mut self, codec: Codec, red_pt: Pt) {
331        if let Some(p) = self.params.iter_mut().find(|p| p.spec.codec == codec) {
332            p.red = Some(red_pt);
333        }
334    }
335
336    /// The RFC 2198 RED send-side redundancy pattern: how many packets back each redundant level
337    /// carries. Defaults to `[1]` (one level, the previous packet, as browsers send).
338    pub fn red_distances(&self) -> &[u32] {
339        if self.red_distances.is_empty() {
340            &[1]
341        } else {
342            &self.red_distances
343        }
344    }
345
346    /// Set the RFC 2198 RED send-side redundancy pattern. Each entry is how many packets back a
347    /// redundant level carries: `[1]` is one level (the previous packet), `[1, 3, 5]` sends three
348    /// levels for higher loss. Deeper redundancy trades bandwidth for resilience.
349    ///
350    /// The input is sanitised: zeros and values deeper than the receiver recovery depth are
351    /// dropped, then the rest is sorted and de-duplicated. Distance 1 is always included: recovery
352    /// derives each block's sequence distance from the closest redundant block, treating it as one
353    /// packet back, so a pattern must anchor on distance 1 or the receiver maps the blocks to the
354    /// wrong sequence numbers (a `[2, 4]` pattern becomes `[1, 2, 4]`). An empty or fully invalid
355    /// input falls back to `[1]`. This only sets the pattern; RED still has to be enabled via the
356    /// `use_red` argument of an audio enable fn (e.g. [`Self::enable_opus`]) or negotiated.
357    pub fn set_red_distances(&mut self, distances: &[u32]) {
358        let mut sane: Vec<u32> = distances
359            .iter()
360            .copied()
361            .filter(|&d| (1..=MAX_RED_RECOVERY_DEPTH as u32).contains(&d))
362            .collect();
363        sane.sort_unstable();
364        sane.dedup();
365        // Always anchor on distance 1 so the receiver can establish the packet duration from the
366        // closest block; without it a pattern like `[2, 4]` is silently mis-recovered.
367        if sane.first() != Some(&1) {
368            sane.insert(0, 1);
369        }
370        self.red_distances = sane.into_boxed_slice();
371    }
372
373    /// Add a default VP8 payload type.
374    pub fn enable_vp8(&mut self, enabled: bool) {
375        self.params.retain(|c| c.spec.codec != Codec::Vp8);
376        if !enabled {
377            return;
378        }
379        self.add_config(
380            PT_VP8,
381            Some(PT_VP8_RTX),
382            Codec::Vp8,
383            Frequency::NINETY_KHZ,
384            None,
385            FormatParams::default(),
386        )
387    }
388
389    /// Add a default H264 payload type.
390    pub fn enable_h264(&mut self, enabled: bool) {
391        self.params.retain(|c| c.spec.codec != Codec::H264);
392        if !enabled {
393            return;
394        }
395        const PARAMS: &[(u8, u8, bool, u32)] = &[
396            (127, 121, true, 0x42001f),
397            (125, 107, false, 0x42001f),
398            (108, 109, true, 0x42e01f),
399            (124, 120, false, 0x42e01f),
400            (123, 119, true, 0x4d001f),
401            (35, 36, false, 0x4d001f),
402            (114, 115, true, 0x64001f),
403        ];
404
405        for p in PARAMS {
406            self.add_h264(p.0.into(), Some(p.1.into()), p.2, p.3)
407        }
408    }
409
410    /// Add a default H265 payload type.
411    /// This enables H265 as a video codec (clock rate 90kHz) with default RTX payload type.
412    /// Note: H265 is still considered an experimental/hidden codec in parts of the public API,
413    /// but it is supported internally for packetization/depacketization.
414    pub fn enable_h265(&mut self, enabled: bool) {
415        self.params.retain(|c| c.spec.codec != Codec::H265);
416        if !enabled {
417            return;
418        }
419
420        // Start with single default configuration
421        // Profile/tier/level negotiation will happen via SDP fmtp parameters
422        //
423        // Level 6.0 (level_id=180) — a high capability level well supported by modern browsers.
424        // Level-id formula per ITU-T H.265 Annex A: level_id = (a*10 + b) * 3
425        //   e.g. Level 6.0 → (6*10 + 0) * 3 = 180
426        //
427        // Chromium H265Level enum definition (kLevel6 = 180):
428        //   https://source.chromium.org/chromium/chromium/src/+/main:
429        //   third_party/webrtc/api/video_codecs/h265_profile_tier_level.h
430        self.add_h265(PT_H265, Some(PT_H265_RTX), 1, 0, 180); // Main, Main tier, Level 6.0
431    }
432
433    /// Convenience for adding a h266 payload type.
434    pub fn add_h266(
435        &mut self,
436        pt: Pt,
437        resend: Option<Pt>,
438        profile_id: u8,
439        tier_flag: u8,
440        level_id: u8,
441    ) {
442        let ptl = H266ProfileTierLevel::new(profile_id, tier_flag, level_id)
443            .unwrap_or(H266ProfileTierLevel::FALLBACK);
444
445        self.add_config(
446            pt,
447            resend,
448            Codec::H266,
449            Frequency::NINETY_KHZ,
450            None,
451            FormatParams {
452                h266_profile_tier_level: Some(ptl),
453                ..Default::default()
454            },
455        )
456    }
457
458    /// Add a default H266 (VVC) payload type.
459    ///
460    /// Enables H266 as a video codec (clock rate 90kHz) with a default RTX
461    /// payload type. Profile/tier/level negotiation happens via the SDP fmtp
462    /// parameters profile-id / tier-flag / level-id (RFC 9328 §7.2).
463    pub fn enable_h266(&mut self, enabled: bool) {
464        self.params.retain(|c| c.spec.codec != Codec::H266);
465        if !enabled {
466            return;
467        }
468
469        // Single default configuration with a high capability level.
470        //
471        // Level 6.0 (level_id=96) — per ITU-T H.266 Annex A the level_id is
472        // 16*major + 3*minor, e.g. Level 6.0 → 16*6 = 96.
473        self.add_h266(PT_H266, Some(PT_H266_RTX), 1, 0, 96); // Main 10, Main tier, Level 6.0
474    }
475
476    /// Add a default VP9 payload type.
477    pub fn enable_vp9(&mut self, enabled: bool) {
478        self.params.retain(|c| c.spec.codec != Codec::Vp9);
479        if !enabled {
480            return;
481        }
482        self.add_config(
483            PT_VP9,
484            Some(PT_VP9_RTX),
485            Codec::Vp9,
486            Frequency::NINETY_KHZ,
487            None,
488            FormatParams {
489                profile_id: Some(0),
490                ..Default::default()
491            },
492        );
493        self.add_config(
494            100.into(),
495            Some(101.into()),
496            Codec::Vp9,
497            Frequency::NINETY_KHZ,
498            None,
499            FormatParams {
500                profile_id: Some(2),
501                ..Default::default()
502            },
503        );
504    }
505
506    /// Add a default AV1 payload type.
507    pub fn enable_av1(&mut self, enabled: bool) {
508        self.params.retain(|c| c.spec.codec != Codec::Av1);
509        if !enabled {
510            return;
511        }
512        self.add_config(
513            PT_AV1,
514            Some(PT_AV1_RTX),
515            Codec::Av1,
516            Frequency::NINETY_KHZ,
517            None,
518            FormatParams::default(),
519        );
520    }
521
522    /// Match the given parameters to the configured parameters.
523    ///
524    /// In a server scenario, a certain codec configuration might not have the same
525    /// payload type (PT) for two different peers. We will have incoming data with one
526    /// PT and need to match that against the PT of the outgoing.
527    ///
528    /// This call performs matching and if a match is found, returns the _local_ PT
529    /// that can be used for sending media.
530    pub fn match_params(&self, params: PayloadParams) -> Option<&PayloadParams> {
531        let c = self.params.iter().max_by_key(|p| p.match_score(&params))?;
532        c.match_score(&params)?; // avoid None, which isn't a match.
533        Some(c)
534    }
535
536    /// When we get remote payload parameters, we need to match differently depending on direction.
537    pub(crate) fn sdp_match_remote(
538        &self,
539        remote_params: PayloadParams,
540        remote_dir: Direction,
541    ) -> Option<Pt> {
542        // If we have no matching parameters locally, we can't accept the remote in any way.
543        let our_params = self.match_params(remote_params)?;
544
545        if remote_dir.sdp_is_receiving() {
546            // The remote is talking about its own receive requirements. The PTs are not suggestions.
547            Some(remote_params.pt())
548        } else {
549            // We can override the remote with our local config. We would have adjusted to
550            // the remote earlier if we can.
551            Some(our_params.pt())
552        }
553    }
554
555    /// Find a payload parameter using a finder function.
556    pub fn find(&self, mut f: impl FnMut(&PayloadParams) -> bool) -> Option<&PayloadParams> {
557        self.params.iter().find(move |p| f(p))
558    }
559
560    /// Return configured payloads for a media kind, optionally preferring event
561    /// clock rates that match audio codecs in a new local offer.
562    pub(crate) fn all_for_kind(
563        &self,
564        kind: MediaKind,
565        for_new_offer: bool,
566    ) -> impl Iterator<Item = &PayloadParams> {
567        let matches_audio_clock = move |event: &PayloadParams| {
568            self.params.iter().any(|audio| {
569                audio.spec.codec.is_audio()
570                    && audio.spec.rtp_clock_rate() == event.spec.rtp_clock_rate()
571            })
572        };
573        let has_matching_events = self
574            .params
575            .iter()
576            .any(|p| p.spec.codec.is_tele() && matches_audio_clock(p));
577
578        self.params.iter().filter(move |p| {
579            if kind == MediaKind::Video {
580                p.spec.codec.is_video()
581            } else {
582                p.spec.codec.is_audio()
583                    || (p.spec.codec.is_tele()
584                        && (!for_new_offer || !has_matching_events || matches_audio_clock(p)))
585            }
586        })
587    }
588
589    /// Highest telephone-event code for this payload type.
590    ///
591    /// Before SDP negotiation this is the configured range (default `0-16`).
592    /// After negotiation it is the smaller range advertised by both peers,
593    /// shared across all m-lines using the payload type. Returns `None` if
594    /// the payload type is not configured as telephone-event.
595    pub(crate) fn tele_event_max(&self, pt: Pt) -> Option<u8> {
596        self.params
597            .iter()
598            .find(|p| p.pt() == pt && p.spec.codec.is_tele())
599            .map(|p| {
600                p.spec
601                    .format
602                    .telephone_event_max
603                    .unwrap_or(FormatParams::DEFAULT_TELEPHONE_EVENT_MAX)
604            })
605    }
606
607    pub(crate) fn update_params(&mut self, remote_params: &[PayloadParams], remote_dir: Direction) {
608        // 0-128 of "claimed" PTs. I.e. PTs that we already allocated to something.
609        let mut claimed: [bool; 128] = [false; 128];
610
611        // Make a pass with all that are definitely confirmed by the remote, since these can't change.
612        for p in self.params.iter() {
613            if !p.locked {
614                continue;
615            }
616
617            claimed.assert_claim_once(p.pt);
618
619            if let Some(rtx) = p.resend {
620                claimed.assert_claim_once(rtx);
621            }
622
623            if let Some(red) = p.red {
624                claimed.assert_claim_once(red);
625            }
626        }
627
628        // Collect all currently unlocked PTs since we will need to avoid them when reassigning.
629        let mut unlocked = self
630            .params
631            .iter()
632            .filter(|p| !p.locked)
633            .flat_map(|p| [Some(p.pt()), p.resend(), p.red()])
634            .flatten()
635            .collect::<HashSet<_>>();
636
637        // Now lock potential new parameters to remote.
638        //
639        // If the remote is doing `SendOnly`, we are receiving, so the PTs are suggestions,
640        // and we are allowed to ANSWER with our own allocations as overrides.
641        // If SendRecv or RecvOnly, the remote is talking about its own receiving capabilities
642        // and we are not allowed to change it in the ANSWER.
643        let local_is_controlling = !remote_dir.sdp_is_receiving();
644
645        for p in self.params.iter_mut() {
646            p.update_param(
647                remote_params,
648                &mut claimed,
649                local_is_controlling,
650                &mut unlocked,
651            );
652        }
653
654        // Make a pass to reassign unconfirmed payloads that have PT which are now claimed.
655        for p in self.params.iter_mut() {
656            if p.locked {
657                continue;
658            }
659
660            if claimed.is_claimed(p.pt) {
661                let Some(pt) = claimed.find_unclaimed(PREFERED_RANGES, &unlocked) else {
662                    warn!("Exhausted PT ranges; ignoring remaining payload updates");
663                    return;
664                };
665
666                debug!("Reassigned PT {} => {}", p.pt, pt);
667                p.pt = pt;
668
669                claimed.assert_claim_once(pt);
670                unlocked.remove(&pt);
671            }
672
673            // RED rides its own PT (like RTX); reassign it if it now collides.
674            if let Some(red) = p.red {
675                if claimed.is_claimed(red) {
676                    match claimed.find_unclaimed(PREFERED_RANGES, &unlocked) {
677                        Some(new_red) => {
678                            debug!("Reassigned RED PT {:?} => {:?}", p.red, new_red);
679                            p.red = Some(new_red);
680                            claimed.assert_claim_once(new_red);
681                            unlocked.remove(&new_red);
682                        }
683                        // RED is opt-in; drop it rather than panic if no PT is free.
684                        None => {
685                            debug!("No free PT for RED; dropping it");
686                            p.red = None;
687                        }
688                    }
689                }
690            }
691
692            let Some(rtx) = p.resend else {
693                continue;
694            };
695
696            if claimed.is_claimed(rtx) {
697                let Some(rtx) = claimed.find_unclaimed(PREFERED_RANGES, &unlocked) else {
698                    warn!("Exhausted PT ranges; ignoring remaining payload updates");
699                    return;
700                };
701
702                debug!("Reassigned RTX PT {:?} => {:?}", p.resend, rtx);
703                p.resend = Some(rtx);
704
705                claimed.assert_claim_once(rtx);
706                unlocked.remove(&rtx);
707            }
708        }
709    }
710
711    pub(crate) fn has_pt(&self, pt: Pt) -> bool {
712        self.params.iter().any(|p| p.pt() == pt)
713    }
714}
715
716impl Deref for CodecConfig {
717    type Target = [PayloadParams];
718
719    fn deref(&self) -> &Self::Target {
720        &self.params
721    }
722}
723
724impl DerefMut for CodecConfig {
725    fn deref_mut(&mut self) -> &mut Self::Target {
726        &mut self.params
727    }
728}
729
730impl CodecSpec {
731    /// Get the standardized codec definition for a static RTP payload type.
732    pub(crate) fn from_static_pt(pt: Pt) -> Option<Self> {
733        let (codec, clock_rate) = if pt == PT_PCMU {
734            (Codec::PCMU, Frequency::EIGHT_KHZ)
735        } else if pt == PT_PCMA {
736            (Codec::PCMA, Frequency::EIGHT_KHZ)
737        } else if pt == PT_G722 {
738            // G722 is represented as 16 kHz internally. CodecSpec::rtp_clock_rate()
739            // maps it to the standardized 8 kHz RTP clock rate on the wire.
740            (Codec::G722, Frequency::SIXTEEN_KHZ)
741        } else if pt == PT_COMFORT_NOISE {
742            (Codec::CN, Frequency::EIGHT_KHZ)
743        } else {
744            return None;
745        };
746
747        Some(CodecSpec {
748            codec,
749            clock_rate,
750            channels: None,
751            format: FormatParams::default(),
752        })
753    }
754}
755
756#[cfg(test)]
757mod test {
758    use crate::io::MultiplexKind;
759    use crate::packet::MediaKind;
760    use crate::rtp_::Direction;
761    use crate::rtp_::Frequency;
762
763    use super::*;
764    use crate::format::{CodecSpec, FormatParams};
765
766    #[test]
767    fn locked_payload_parameters_are_unchanged() {
768        for codec in [Codec::H265, Codec::H266, Codec::Tele, Codec::AmrWb] {
769            for direction in [Direction::SendOnly, Direction::RecvOnly] {
770                let mut config = CodecConfig::empty();
771                config.add_config(
772                    102.into(),
773                    Some(103.into()),
774                    codec,
775                    Frequency::NINETY_KHZ,
776                    None,
777                    FormatParams::default(),
778                );
779                let mut remote = config.params[0];
780                config.update_params(&[remote], direction);
781                assert!(config.params[0].locked);
782                let established = config.params.clone();
783                remote.pt = 104.into();
784                remote.resend = Some(105.into());
785                remote.spec.format.sprop_max_don_diff = Some(1);
786                remote.spec.format.telephone_event_max = Some(10);
787                remote.spec.format.mode_set = Some(0b111);
788                remote.fb_transport_cc = !remote.fb_transport_cc;
789                config.update_params(&[remote], direction);
790                assert_eq!(config.params, established);
791            }
792        }
793    }
794
795    #[test]
796    fn exhausted_payload_allocations_do_not_panic() {
797        let mut config = CodecConfig::empty();
798        config.enable_vp8(true);
799        let payload = config.params[0];
800        for primary in [96, 0] {
801            let mut config = config.clone();
802            config.params[0].pt = primary.into();
803            for pt in PREFERED_RANGES.iter().flat_map(|range| range.clone()) {
804                let mut locked = payload;
805                locked.pt = (pt as u8).into();
806                locked.resend = None;
807                locked.locked = true;
808                config.params.push(locked);
809            }
810            let locked = config.params[1..].to_vec();
811            config.update_params(&[], Direction::RecvOnly);
812            assert_eq!(config.params[1..], locked);
813        }
814        for free_primary in [false, true] {
815            let mut local = payload;
816            let mut claimed = [true; 128];
817            claimed[*local.pt as usize] = !free_primary;
818            local.update_param(&[payload], &mut claimed, true, &mut HashSet::new());
819            assert_eq!(local.locked, free_primary);
820            if free_primary {
821                assert_eq!(local.resend, None);
822            }
823        }
824    }
825
826    #[test]
827    fn transport_cc_uses_first_section_and_preserves_local_capability() {
828        for direction in [Direction::SendOnly, Direction::RecvOnly] {
829            for local_enabled in [false, true] {
830                for sections in [[false, false], [false, true], [true, false]] {
831                    let mut config = CodecConfig::empty();
832                    config.enable_vp8(true);
833                    config.params[0].set_fb_transport_cc(local_enabled);
834                    let mut remote = config.params[0];
835                    let expected = local_enabled && sections[0];
836                    for enabled in sections {
837                        remote.set_fb_transport_cc(enabled);
838                        config.update_params(&[remote], direction);
839                        assert_eq!(config.params()[0].fb_transport_cc(), expected);
840                    }
841                }
842            }
843        }
844    }
845
846    #[test]
847    fn static_payload_types_have_canonical_codec_definitions() {
848        let definitions = [
849            (PT_PCMU, Codec::PCMU, Frequency::EIGHT_KHZ),
850            (PT_PCMA, Codec::PCMA, Frequency::EIGHT_KHZ),
851            (PT_G722, Codec::G722, Frequency::SIXTEEN_KHZ),
852            (PT_COMFORT_NOISE, Codec::CN, Frequency::EIGHT_KHZ),
853        ];
854
855        for (pt, codec, clock_rate) in definitions {
856            let spec = CodecSpec::from_static_pt(pt).expect("static payload definition");
857            assert_eq!(spec.codec, codec);
858            assert_eq!(spec.clock_rate, clock_rate);
859            assert_eq!(spec.channels, None);
860            assert_eq!(spec.format, FormatParams::default());
861        }
862
863        assert!(CodecSpec::from_static_pt(PT_OPUS).is_none());
864    }
865
866    #[test]
867    fn default_red_payload_types_are_demultiplexed_as_rtp() {
868        for pt in [PT_G722_RED, PT_PCMU_RED, PT_PCMA_RED] {
869            let packet = [0x80, *pt, 0];
870            assert_eq!(
871                MultiplexKind::try_from(packet.as_slice()).unwrap(),
872                MultiplexKind::Rtp,
873                "RED payload type {pt} must not be demultiplexed as RTCP"
874            );
875        }
876    }
877
878    #[test]
879    fn dynamic_comfort_noise_collision_preserves_configured_pt() {
880        let mut claimed = PayloadParams::new(
881            96.into(),
882            None,
883            CodecSpec {
884                codec: Codec::Opus,
885                clock_rate: Frequency::FORTY_EIGHT_KHZ,
886                channels: Some(2),
887                format: FormatParams::default(),
888            },
889        );
890        claimed.locked = true;
891
892        let local_cn = PayloadParams::new(
893            97.into(),
894            None,
895            CodecSpec {
896                codec: Codec::CN,
897                clock_rate: Frequency::SIXTEEN_KHZ,
898                channels: None,
899                format: FormatParams::default(),
900            },
901        );
902        let remote_cn = PayloadParams::new(
903            96.into(),
904            None,
905            CodecSpec {
906                codec: Codec::CN,
907                clock_rate: Frequency::SIXTEEN_KHZ,
908                channels: None,
909                format: FormatParams::default(),
910            },
911        );
912
913        let mut config = CodecConfig::new_from_payload_params(vec![claimed, local_cn]);
914        config.update_params(&[remote_cn], Direction::SendOnly);
915
916        let cn = config
917            .iter()
918            .find(|p| p.spec().codec == Codec::CN)
919            .expect("configured CN payload");
920        assert_eq!(
921            *cn.pt(),
922            97,
923            "dynamic CN must retain its configured payload type"
924        );
925    }
926
927    #[test]
928    fn collision_preserves_configured_primary_and_rtx_pts() {
929        let mut claimed = PayloadParams::new(
930            96.into(),
931            Some(97.into()),
932            CodecSpec {
933                codec: Codec::H264,
934                clock_rate: Frequency::NINETY_KHZ,
935                channels: None,
936                format: FormatParams::default(),
937            },
938        );
939        claimed.locked = true;
940
941        let vp8 = CodecSpec {
942            codec: Codec::Vp8,
943            clock_rate: Frequency::NINETY_KHZ,
944            channels: None,
945            format: FormatParams::default(),
946        };
947        let local_vp8 = PayloadParams::new(110.into(), Some(111.into()), vp8);
948        let remote_vp8 = PayloadParams::new(96.into(), Some(97.into()), vp8);
949
950        let mut config = CodecConfig::new_from_payload_params(vec![claimed, local_vp8]);
951        config.update_params(&[remote_vp8], Direction::SendOnly);
952
953        let vp8 = config
954            .iter()
955            .find(|p| p.spec().codec == Codec::Vp8)
956            .expect("configured VP8 payload");
957        assert_eq!((*vp8.pt(), vp8.resend().map(|pt| *pt)), (110, Some(111)));
958    }
959
960    #[test]
961    fn enable_comfort_noise_uses_static_8khz_payload_type() {
962        let mut config = CodecConfig::empty();
963
964        config.enable_comfort_noise(true);
965
966        let params = config
967            .params()
968            .iter()
969            .find(|p| p.spec().codec == Codec::CN)
970            .expect("Comfort Noise should be enabled");
971        assert_eq!(params.pt(), Pt::new_with_value(13));
972        assert_eq!(params.spec().clock_rate, Frequency::EIGHT_KHZ);
973        assert_eq!(params.spec().channels, None);
974
975        config.enable_comfort_noise(false);
976        assert!(config.params().iter().all(|p| p.spec().codec != Codec::CN));
977    }
978
979    #[test]
980    fn comfort_noise_supports_dynamic_payload_types_at_higher_clock_rates() {
981        let mut config = CodecConfig::empty();
982
983        for (pt, clock_rate) in [(96, 16_000), (97, 24_000), (98, 32_000), (99, 48_000)] {
984            config.add_config(
985                pt.into(),
986                None,
987                Codec::CN,
988                Frequency::new(clock_rate).unwrap(),
989                None,
990                FormatParams::default(),
991            );
992        }
993
994        let configured: Vec<_> = config
995            .params()
996            .iter()
997            .map(|p| (*p.pt(), p.spec().clock_rate.get()))
998            .collect();
999        assert_eq!(
1000            configured,
1001            vec![(96, 16_000), (97, 24_000), (98, 32_000), (99, 48_000)]
1002        );
1003    }
1004
1005    #[test]
1006    fn enable_red_links_opus() {
1007        let mut c = CodecConfig::empty();
1008        c.enable_opus(true, true);
1009        let opus = c
1010            .params()
1011            .iter()
1012            .find(|p| p.spec().codec == Codec::Opus)
1013            .unwrap();
1014        assert_eq!(opus.red(), Some(PT_RED));
1015    }
1016
1017    #[test]
1018    fn enable_red_links_all_audio_codecs_with_distinct_pts() {
1019        let mut c = CodecConfig::empty();
1020        c.enable_opus(true, true);
1021        c.enable_g722(true, true);
1022        c.enable_pcmu(true, true);
1023        c.enable_pcma(true, true);
1024
1025        let params = c.params();
1026        let red_of = |codec| {
1027            params
1028                .iter()
1029                .find(|p| p.spec().codec == codec)
1030                .unwrap()
1031                .red()
1032        };
1033
1034        // Every enabled audio codec gets RED, each with its own distinct payload type so the
1035        // `a=rtpmap` entries (which each carry that codec's clock rate) don't collide in SDP.
1036        assert_eq!(red_of(Codec::Opus), Some(PT_RED));
1037        assert_eq!(red_of(Codec::G722), Some(PT_G722_RED));
1038        assert_eq!(red_of(Codec::PCMU), Some(PT_PCMU_RED));
1039        assert_eq!(red_of(Codec::PCMA), Some(PT_PCMA_RED));
1040        // All four RED payload types are distinct.
1041        let pts = [PT_RED, PT_G722_RED, PT_PCMU_RED, PT_PCMA_RED];
1042        for (i, a) in pts.iter().enumerate() {
1043            for b in &pts[i + 1..] {
1044                assert_ne!(a, b, "RED payload types must be distinct");
1045            }
1046        }
1047    }
1048
1049    #[test]
1050    fn enable_amr_wb_uses_a_free_default_pt() {
1051        let mut config = CodecConfig::new_with_defaults();
1052
1053        config.enable_amr_wb(true);
1054
1055        let amr_wb = config
1056            .params()
1057            .iter()
1058            .find(|p| p.spec().codec == Codec::AmrWb)
1059            .expect("AMR-WB should be enabled");
1060        assert_eq!(amr_wb.pt(), PT_AMR_WB);
1061
1062        let mut seen = std::collections::HashSet::new();
1063        for pt in config
1064            .params()
1065            .iter()
1066            .flat_map(|p| [Some(p.pt()), p.resend(), p.red()])
1067            .flatten()
1068        {
1069            assert!(seen.insert(pt), "duplicate PT {pt}");
1070        }
1071    }
1072
1073    #[test]
1074    fn set_red_distances_sanitises_input() {
1075        let mut c = CodecConfig::empty();
1076        // Default is a single level, the previous packet.
1077        assert_eq!(c.red_distances(), &[1]);
1078
1079        // Unsorted, duplicated, zero, and over-cap values are cleaned to a sorted distinct set.
1080        c.set_red_distances(&[5, 1, 0, 3, 3, 1, 999]);
1081        assert_eq!(c.red_distances(), &[1, 3, 5]);
1082
1083        // Empty or fully invalid input falls back to the default single level.
1084        c.set_red_distances(&[0, 999]);
1085        assert_eq!(c.red_distances(), &[1]);
1086
1087        // Distance 1 is always included as the recovery anchor: a pattern without it (which the
1088        // receiver would mis-map) gets 1 prepended rather than mis-recovered.
1089        c.set_red_distances(&[2, 4]);
1090        assert_eq!(c.red_distances(), &[1, 2, 4]);
1091        c.set_red_distances(&[3, 5]);
1092        assert_eq!(c.red_distances(), &[1, 3, 5]);
1093    }
1094
1095    #[test]
1096    fn red_kept_when_both_sides_enable() {
1097        let mut local = CodecConfig::empty();
1098        local.enable_opus(true, true);
1099
1100        let mut remote = CodecConfig::empty();
1101        remote.enable_opus(true, true);
1102
1103        local.update_params(remote.params(), Direction::SendRecv);
1104
1105        let opus = local
1106            .params()
1107            .iter()
1108            .find(|p| p.spec().codec == Codec::Opus)
1109            .unwrap();
1110        assert_eq!(opus.red(), Some(PT_RED));
1111    }
1112
1113    #[test]
1114    fn red_dropped_when_remote_lacks_red() {
1115        let mut local = CodecConfig::empty();
1116        local.enable_opus(true, true);
1117
1118        let mut remote = CodecConfig::empty();
1119        remote.enable_opus(true, false); // remote does not offer RED
1120
1121        local.update_params(remote.params(), Direction::SendRecv);
1122
1123        let opus = local
1124            .params()
1125            .iter()
1126            .find(|p| p.spec().codec == Codec::Opus)
1127            .unwrap();
1128        assert_eq!(
1129            opus.red(),
1130            None,
1131            "RED must be dropped when remote doesn't offer it"
1132        );
1133    }
1134
1135    #[test]
1136    fn conflicting_remote_red_mappings_do_not_panic() {
1137        let shared_red_pt = Pt::new_with_value(63);
1138
1139        let mut local = CodecConfig::empty();
1140        local.enable_g722(true, true);
1141        local.enable_pcmu(true, true);
1142
1143        let mut remote = CodecConfig::empty();
1144        remote.enable_g722(true, true);
1145        remote.enable_pcmu(true, true);
1146        for p in remote.params.iter_mut() {
1147            p.red = Some(shared_red_pt);
1148        }
1149
1150        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1151            local.update_params(remote.params(), Direction::SendRecv);
1152        }));
1153
1154        assert!(
1155            result.is_ok(),
1156            "a conflicting remote RED mapping must be rejected or negotiated without panicking"
1157        );
1158    }
1159
1160    #[test]
1161    fn test_pt_conflict_different_directions() {
1162        // Simulates:
1163        // 1. str0m OFFER sendonly H264 PT 108, RTX PT 109
1164        // 2. FF ANSWER recvonly (locks PT 109 as H264 RTX)
1165        // 3. FF OFFER sendonly Opus PT 109
1166        // 4. Crash on PT 109 conflict
1167
1168        let mut config = CodecConfig::empty();
1169
1170        // Initial local config: H264 with PT 108, RTX 109 and Opus with PT 111
1171        config.add_config(
1172            108.into(),
1173            Some(109.into()),
1174            Codec::H264,
1175            Frequency::NINETY_KHZ,
1176            None,
1177            FormatParams {
1178                packetization_mode: Some(1),
1179                profile_level_id: Some(0x42e01f),
1180                ..Default::default()
1181            },
1182        );
1183        config.add_config(
1184            111.into(),
1185            None,
1186            Codec::Opus,
1187            Frequency::FORTY_EIGHT_KHZ,
1188            Some(2),
1189            FormatParams::default(),
1190        );
1191
1192        // Step 2: Remote answers recvonly with our H264 PT 108/109
1193        // This locks PT 109 as RTX
1194        let remote_h264_params = vec![PayloadParams::new(
1195            108.into(),
1196            Some(109.into()),
1197            CodecSpec {
1198                codec: Codec::H264,
1199                clock_rate: Frequency::NINETY_KHZ,
1200                channels: None,
1201                format: FormatParams {
1202                    packetization_mode: Some(1),
1203                    profile_level_id: Some(0x42e01f),
1204                    ..Default::default()
1205                },
1206            },
1207        )];
1208
1209        config.update_params(&remote_h264_params, Direction::RecvOnly);
1210
1211        // Verify PT 109 is now locked as RTX for H264
1212        assert!(
1213            config
1214                .params()
1215                .iter()
1216                .any(|p| p.resend() == Some(109.into()) && p.locked)
1217        );
1218
1219        // Step 3: Remote offers sendonly Opus PT 109
1220        // This should NOT crash - PT 109 should be remapped to 111 (Opus default)
1221        let remote_opus_params = vec![PayloadParams::new(
1222            109.into(),
1223            None,
1224            CodecSpec {
1225                codec: Codec::Opus,
1226                clock_rate: Frequency::FORTY_EIGHT_KHZ,
1227                channels: Some(2),
1228                format: FormatParams::default(),
1229            },
1230        )];
1231
1232        config.update_params(&remote_opus_params, Direction::SendOnly);
1233
1234        // Verify the fix: Opus should be remapped to PT_OPUS (its default)
1235        let opus_param = config
1236            .params()
1237            .iter()
1238            .find(|p| p.spec().codec == Codec::Opus);
1239        assert!(opus_param.is_some(), "Opus param should exist");
1240        assert_eq!(
1241            opus_param.unwrap().pt(),
1242            PT_OPUS,
1243            "Opus should be remapped to PT_OPUS (default)"
1244        );
1245        assert!(opus_param.unwrap().locked, "Opus param should be locked");
1246
1247        // Verify H264 RTX PT 109 is still locked
1248        assert!(
1249            config
1250                .params()
1251                .iter()
1252                .any(|p| p.resend() == Some(109.into()) && p.locked)
1253        );
1254    }
1255
1256    #[test]
1257    fn test_pt_conflict_same_mline_multiple_codecs() {
1258        // Reproduces a bug we have had where reassigned PTs were conflicting with unlocked PTs.
1259        //
1260        // SCENARIO & ROOT CAUSE:
1261        // This test reproduces the exact bug from sdp.json using str0m's default config.
1262        //
1263        // 1. str0m starts with DEFAULT codec configuration:
1264        //    - VP8 at PT 96/97 (unlocked)
1265        //    - H264 High (0x64001f) at PT 114/115 (unlocked)
1266        //    - Many other H264 profiles at various PTs (127, 125, 108, 124, 123, 35)
1267        //
1268        // 2. Chrome (peer A) offers video with H264 only - PTs: 103/104, 109/114, 117/118
1269        //    Chrome's OFFER direction: sendonly (Chrome sends video to us)
1270        //    **CRITICAL**: Chrome uses PT 114 as RTX for H264 42e01f (PT 109)
1271        //
1272        // 3. str0m ANSWERs accepting Chrome's H264 offer:
1273        //    - Chrome's H264 PTs (103, 109, 117) are LOCKED
1274        //    - Chrome's RTX PTs (104, 114, 118) are LOCKED
1275        //    - VP8 at PT 96 remains UNLOCKED (Chrome didn't negotiate it)
1276        //    - H264 High at PT 114 CONFLICTS with Chrome's RTX usage of PT 114!
1277        //
1278        // 4. THE BUG (before fix): update_params reassigns H264 High from PT 114:
1279        //    - Searches for available PT starting from 96
1280        //    - PT 96 appears "unclaimed" because it only checked LOCKED PTs
1281        //    - VP8 is at PT 96 but UNLOCKED, so wasn't checked!
1282        //    - H264 High gets reassigned to PT 96
1283        //    - Now BOTH VP8 and H264 High are at PT 96! ❌
1284        //
1285        // 5. Later, Firefox (peer B) joins - str0m creates NEW video m-line (mid KvE)
1286        //    When generating SDP, str0m collects ALL video codecs from codec_config
1287        //    Result (before fix): PT 96 appears TWICE in the same m-line!
1288        //    - Line 729 in sdp.json: a=rtpmap:96 VP8/90000
1289        //    - Line 791 in sdp.json: a=rtpmap:96 H264/90000 profile-level-id=64001f
1290        //
1291        // EXPECTED: Each PT in an m-line must be unique
1292        // THE FIX: Now checks BOTH locked and unlocked PTs when reassigning
1293
1294        // Start with str0m's default codec configuration
1295        // This includes VP8 at 96/97 and H264 High at 114/115 (among others)
1296        let mut config = CodecConfig::new_with_defaults();
1297
1298        // Verify H264 High starts at its default PT 114 BEFORE Chrome's offer
1299        let h264_high_before = config
1300            .params()
1301            .iter()
1302            .find(|p| {
1303                p.spec().codec == Codec::H264 && p.spec().format.profile_level_id == Some(0x64001f)
1304            })
1305            .expect("H264 High should exist");
1306        assert_eq!(
1307            h264_high_before.pt(),
1308            114.into(),
1309            "H264 High should start at PT 114"
1310        );
1311
1312        // Simulate Chrome's OFFER with H264 only (sendonly from Chrome's perspective)
1313        // Chrome is sending video to us, so we're receiving
1314        // Direction::SendOnly means the remote is sending (we receive)
1315        let chrome_h264_params = vec![
1316            PayloadParams::new(
1317                103.into(),
1318                Some(104.into()),
1319                CodecSpec {
1320                    codec: Codec::H264,
1321                    clock_rate: Frequency::NINETY_KHZ,
1322                    channels: None,
1323                    format: FormatParams {
1324                        packetization_mode: Some(1),
1325                        profile_level_id: Some(0x42001f),
1326                        ..Default::default()
1327                    },
1328                },
1329            ),
1330            PayloadParams::new(
1331                109.into(),
1332                Some(114.into()),
1333                CodecSpec {
1334                    codec: Codec::H264,
1335                    clock_rate: Frequency::NINETY_KHZ,
1336                    channels: None,
1337                    format: FormatParams {
1338                        packetization_mode: Some(1),
1339                        profile_level_id: Some(0x42e01f),
1340                        ..Default::default()
1341                    },
1342                },
1343            ),
1344            PayloadParams::new(
1345                117.into(),
1346                Some(118.into()),
1347                CodecSpec {
1348                    codec: Codec::H264,
1349                    clock_rate: Frequency::NINETY_KHZ,
1350                    channels: None,
1351                    format: FormatParams {
1352                        packetization_mode: Some(1),
1353                        profile_level_id: Some(0x4d001f),
1354                        ..Default::default()
1355                    },
1356                },
1357            ),
1358        ];
1359
1360        // Process Chrome's offer - this locks the H264 PTs that Chrome offered
1361        // Chrome is SendOnly, so from our perspective we're receiving (recvonly)
1362        config.update_params(&chrome_h264_params, Direction::SendOnly);
1363
1364        // Verify: Chrome's H264 profiles are locked at their specific PTs
1365        assert!(
1366            config.params().iter().any(|p| p.pt() == 103.into()
1367                && p.spec().codec == Codec::H264
1368                && p.spec().format.profile_level_id == Some(0x42001f)
1369                && p.locked),
1370            "H264 42001f should be locked at PT 103"
1371        );
1372        assert!(
1373            config.params().iter().any(|p| p.pt() == 109.into()
1374                && p.spec().codec == Codec::H264
1375                && p.spec().format.profile_level_id == Some(0x42e01f)
1376                && p.locked),
1377            "H264 42e01f should be locked at PT 109"
1378        );
1379        assert!(
1380            config.params().iter().any(|p| p.pt() == 117.into()
1381                && p.spec().codec == Codec::H264
1382                && p.spec().format.profile_level_id == Some(0x4d001f)
1383                && p.locked),
1384            "H264 4d001f should be locked at PT 117"
1385        );
1386
1387        // Verify: VP8 at PT 96 is NOT locked (Chrome didn't negotiate it)
1388        let vp8_param = config
1389            .params()
1390            .iter()
1391            .find(|p| p.spec().codec == Codec::Vp8);
1392        assert!(vp8_param.is_some(), "VP8 should still exist");
1393        assert_eq!(vp8_param.unwrap().pt(), 96.into(), "VP8 should be at PT 96");
1394        assert!(!vp8_param.unwrap().locked, "VP8 should NOT be locked");
1395
1396        // THE FIX VERIFICATION:
1397        // H264 64001f was originally at PT 114, but Chrome used PT 114 for RTX
1398        // update_params should reassign H264 64001f to a PT that avoids BOTH:
1399        // - Locked PTs (103, 104, 109, 114, 117, 118)
1400        // - Unlocked PTs already in use (96 for VP8, 97 for VP8 RTX)
1401        let h264_high_param = config.params().iter().find(|p| {
1402            p.spec().codec == Codec::H264 && p.spec().format.profile_level_id == Some(0x64001f)
1403        });
1404        assert!(h264_high_param.is_some(), "H264 64001f should still exist");
1405        let h264_pt = h264_high_param.unwrap().pt();
1406
1407        // Should NOT be at PT 96 (VP8 is there)
1408        assert_ne!(
1409            h264_pt,
1410            96.into(),
1411            "FIX WORKING: H264 64001f should NOT be at PT 96 (VP8 is there)"
1412        );
1413
1414        // Should NOT be at any of the locked PTs
1415        assert!(
1416            ![103, 104, 109, 114, 117, 118].contains(&{ *h264_pt }),
1417            "H264 64001f should not conflict with locked PTs"
1418        );
1419
1420        assert!(
1421            !h264_high_param.unwrap().locked,
1422            "H264 64001f should NOT be locked (Chrome didn't offer it)"
1423        );
1424
1425        // Now simulate creating a new video m-line (for Firefox's camera)
1426        // This is where the bug manifests: we collect ALL video codecs from config
1427        let all_video_params: Vec<_> = config.all_for_kind(MediaKind::Video, false).collect();
1428
1429        // Extract just the PTs (including RTX PTs)
1430        let mut all_pts = Vec::new();
1431        for p in all_video_params {
1432            all_pts.push(p.pt());
1433            if let Some(rtx) = p.resend() {
1434                all_pts.push(rtx);
1435            }
1436        }
1437
1438        // THE FIX: With the bug fixed, no PT should appear multiple times
1439        // Check for duplicate PTs - this should now PASS
1440        let mut seen = std::collections::HashSet::new();
1441        let mut duplicates = Vec::new();
1442        for pt in &all_pts {
1443            if !seen.insert(pt) {
1444                duplicates.push(*pt);
1445            }
1446        }
1447
1448        assert!(
1449            duplicates.is_empty(),
1450            "FAILED: Found duplicate PTs in same m-line: {:?}\nAll PTs: {:?}\n
1451            This creates invalid SDP with multiple a=rtpmap lines for the same PT!",
1452            duplicates,
1453            all_pts
1454        );
1455    }
1456
1457    // ── H.265 direction-based negotiation tests ──────────────────────────
1458
1459    /// Helper: build a CodecConfig containing only H.265 at the given PTL.
1460    fn h265_config(profile_id: u8, tier_flag: u8, level_id: u8) -> CodecConfig {
1461        let mut config = CodecConfig::empty();
1462        config.add_h265(
1463            102.into(),
1464            Some(103.into()),
1465            profile_id,
1466            tier_flag,
1467            level_id,
1468        );
1469        config
1470    }
1471
1472    /// Helper: build a single-element remote PayloadParams for H.265 with full PTL.
1473    fn h265_remote_ptl(profile_id: u8, tier_flag: u8, level_id: u8) -> Vec<PayloadParams> {
1474        use crate::packet::H265ProfileTierLevel;
1475        vec![PayloadParams::new(
1476            102.into(),
1477            Some(103.into()),
1478            CodecSpec {
1479                codec: Codec::H265,
1480                clock_rate: Frequency::NINETY_KHZ,
1481                channels: None,
1482                format: FormatParams {
1483                    h265_profile_tier_level: Some(
1484                        H265ProfileTierLevel::new(profile_id, tier_flag, level_id).unwrap(),
1485                    ),
1486                    ..Default::default()
1487                },
1488            },
1489        )]
1490    }
1491
1492    /// Helper: build a single-element remote PayloadParams for H.265 with profile-id only.
1493    fn h265_remote_profile_only(profile_id: u32) -> Vec<PayloadParams> {
1494        vec![PayloadParams::new(
1495            102.into(),
1496            Some(103.into()),
1497            CodecSpec {
1498                codec: Codec::H265,
1499                clock_rate: Frequency::NINETY_KHZ,
1500                channels: None,
1501                format: FormatParams {
1502                    profile_id: Some(profile_id),
1503                    ..Default::default()
1504                },
1505            },
1506        )]
1507    }
1508
1509    /// Helper: build a single-element remote PayloadParams for H.265 with no fmtp.
1510    fn h265_remote_no_fmtp() -> Vec<PayloadParams> {
1511        vec![PayloadParams::new(
1512            102.into(),
1513            Some(103.into()),
1514            CodecSpec {
1515                codec: Codec::H265,
1516                clock_rate: Frequency::NINETY_KHZ,
1517                channels: None,
1518                format: FormatParams::default(),
1519            },
1520        )]
1521    }
1522
1523    /// Helper: extract the H.265 param from a config (panics if missing).
1524    fn get_h265(config: &CodecConfig) -> &PayloadParams {
1525        config
1526            .params()
1527            .iter()
1528            .find(|p| p.spec().codec == Codec::H265)
1529            .expect("H.265 param missing")
1530    }
1531
1532    // ── recvonly: remote sends to us ─────────────────────────────────────
1533
1534    /// Remote sends at Level 5.2, we can receive at Level 6.0.
1535    /// Negotiated level should narrow to min(6.0, 5.2) = 5.2.
1536    #[test]
1537    fn test_h265_recvonly_remote_level_lower() {
1538        let mut config = h265_config(1, 0, 180); // Main, Main tier, Level 6.0
1539        let remote = h265_remote_ptl(1, 0, 156); // Level 5.2
1540
1541        // Direction::SendOnly = remote is sending (we receive)
1542        config.update_params(&remote, Direction::SendOnly);
1543
1544        let ptl = get_h265(&config)
1545            .spec()
1546            .format
1547            .h265_profile_tier_level
1548            .unwrap();
1549        assert_eq!(
1550            ptl.level_id(),
1551            156,
1552            "Should narrow to min(180,156) = Level 5.2"
1553        );
1554        assert_eq!(ptl.profile_id(), 1, "Profile should be preserved");
1555        assert_eq!(ptl.tier_flag(), 0, "Tier should be preserved");
1556    }
1557
1558    /// Remote sends at Level 6.0, we can receive at Level 5.2.
1559    /// Negotiated level should narrow to min(5.2, 6.0) = 5.2.
1560    #[test]
1561    fn test_h265_recvonly_local_level_lower() {
1562        let mut config = h265_config(1, 0, 156); // Level 5.2
1563        let remote = h265_remote_ptl(1, 0, 180); // Level 6.0
1564
1565        config.update_params(&remote, Direction::SendOnly);
1566
1567        let ptl = get_h265(&config)
1568            .spec()
1569            .format
1570            .h265_profile_tier_level
1571            .unwrap();
1572        assert_eq!(
1573            ptl.level_id(),
1574            156,
1575            "Should narrow to min(156,180) = Level 5.2"
1576        );
1577    }
1578
1579    // ── sendrecv: both sides send and receive ────────────────────────────
1580
1581    /// Both sides sendrecv. Local Level 6.0, remote Level 5.2.
1582    /// Effective level should narrow to min(6.0, 5.2) = 5.2.
1583    #[test]
1584    fn test_h265_sendrecv_remote_level_lower() {
1585        let mut config = h265_config(1, 0, 180); // Level 6.0
1586        let remote = h265_remote_ptl(1, 0, 156); // Level 5.2
1587
1588        config.update_params(&remote, Direction::SendRecv);
1589
1590        let ptl = get_h265(&config)
1591            .spec()
1592            .format
1593            .h265_profile_tier_level
1594            .unwrap();
1595        assert_eq!(ptl.level_id(), 156, "sendrecv: should narrow to Level 5.2");
1596    }
1597
1598    /// Both sides sendrecv. Local Level 5.2, remote Level 6.0.
1599    /// Effective level should narrow to min(5.2, 6.0) = 5.2.
1600    #[test]
1601    fn test_h265_sendrecv_local_level_lower() {
1602        let mut config = h265_config(1, 0, 156); // Level 5.2
1603        let remote = h265_remote_ptl(1, 0, 180); // Level 6.0
1604
1605        config.update_params(&remote, Direction::SendRecv);
1606
1607        let ptl = get_h265(&config)
1608            .spec()
1609            .format
1610            .h265_profile_tier_level
1611            .unwrap();
1612        assert_eq!(ptl.level_id(), 156, "sendrecv: should narrow to Level 5.2");
1613    }
1614
1615    /// Same level on both sides. Should remain unchanged.
1616    #[test]
1617    fn test_h265_sendrecv_same_level() {
1618        let mut config = h265_config(1, 0, 156); // Level 5.2
1619        let remote = h265_remote_ptl(1, 0, 156); // Level 5.2
1620
1621        config.update_params(&remote, Direction::SendRecv);
1622
1623        let ptl = get_h265(&config)
1624            .spec()
1625            .format
1626            .h265_profile_tier_level
1627            .unwrap();
1628        assert_eq!(ptl.level_id(), 156, "Same levels should stay at Level 5.2");
1629    }
1630
1631    // ── sendonly: we send, remote receives ───────────────────────────────
1632
1633    /// Remote declares recvonly at Level 5.2, we offer sendonly at Level 6.0.
1634    /// Negotiated level should narrow to 5.2 (receiver wins).
1635    #[test]
1636    fn test_h265_sendonly_receiver_level_lower() {
1637        let mut config = h265_config(1, 0, 180); // Level 6.0
1638        let remote = h265_remote_ptl(1, 0, 156); // Level 5.2
1639
1640        // Direction::RecvOnly = remote is receiving (we send)
1641        config.update_params(&remote, Direction::RecvOnly);
1642
1643        let ptl = get_h265(&config)
1644            .spec()
1645            .format
1646            .h265_profile_tier_level
1647            .unwrap();
1648        assert_eq!(
1649            ptl.level_id(),
1650            156,
1651            "sendonly: should narrow to receiver's Level 5.2"
1652        );
1653    }
1654
1655    /// Remote offers only profile-id=1, no tier/level.
1656    /// Local should drop its full PTL and echo back profile-id only.
1657    #[test]
1658    fn test_h265_profile_only_remote_mirrors() {
1659        let mut config = h265_config(1, 0, 180); // Full PTL
1660        let remote = h265_remote_profile_only(1); // profile-id only
1661
1662        config.update_params(&remote, Direction::SendRecv);
1663
1664        let h265 = get_h265(&config);
1665        assert!(
1666            h265.spec().format.h265_profile_tier_level.is_none(),
1667            "Full PTL should be cleared when remote only offers profile-id"
1668        );
1669        assert_eq!(
1670            h265.spec().format.profile_id,
1671            Some(1),
1672            "profile_id should mirror the remote's value"
1673        );
1674    }
1675
1676    // ── no-fmtp remote ──────────────────────────────────────────────────
1677
1678    /// Remote has no H.265 fmtp at all. Local should clear both fields.
1679    #[test]
1680    fn test_h265_no_fmtp_remote_clears() {
1681        let mut config = h265_config(1, 0, 180); // Full PTL
1682        let remote = h265_remote_no_fmtp();
1683
1684        config.update_params(&remote, Direction::SendRecv);
1685
1686        let h265 = get_h265(&config);
1687        assert!(
1688            h265.spec().format.h265_profile_tier_level.is_none(),
1689            "PTL should be cleared when remote has no fmtp"
1690        );
1691        assert!(
1692            h265.spec().format.profile_id.is_none(),
1693            "profile_id should be cleared when remote has no fmtp"
1694        );
1695    }
1696
1697    // ── profile_id field cleanup ─────────────────────────────────────────
1698
1699    /// When remote has full PTL, the `profile_id` field must be None
1700    /// to avoid duplicate serialization (profile-id appears in both
1701    /// h265_profile_tier_level AND the VP9-style profile_id field).
1702    #[test]
1703    fn test_h265_profile_id_cleared_on_ptl_match() {
1704        let mut config = CodecConfig::empty();
1705        // Artificially set both fields to simulate a misconfigured state
1706        config.add_config(
1707            102.into(),
1708            Some(103.into()),
1709            Codec::H265,
1710            Frequency::NINETY_KHZ,
1711            None,
1712            FormatParams {
1713                h265_profile_tier_level: Some(
1714                    crate::packet::H265ProfileTierLevel::new(1, 0, 180).unwrap(),
1715                ),
1716                profile_id: Some(1), // should be cleared after negotiation
1717                ..Default::default()
1718            },
1719        );
1720        let remote = h265_remote_ptl(1, 0, 156);
1721
1722        config.update_params(&remote, Direction::SendRecv);
1723
1724        let h265 = get_h265(&config);
1725        assert!(
1726            h265.spec().format.profile_id.is_none(),
1727            "profile_id field must be None when full PTL is present"
1728        );
1729        assert!(
1730            h265.spec().format.h265_profile_tier_level.is_some(),
1731            "PTL should still be present"
1732        );
1733    }
1734
1735    // ── default level ────────────────────────────────────────────────────
1736
1737    /// `enable_h265` should produce Level 6.0 (level_id = 180).
1738    #[test]
1739    fn test_h265_default_level_is_6_0() {
1740        let mut config = CodecConfig::empty();
1741        config.enable_h265(true);
1742
1743        let h265 = get_h265(&config);
1744        let ptl = h265.spec().format.h265_profile_tier_level.unwrap();
1745        assert_eq!(
1746            ptl.level_id(),
1747            180,
1748            "Default H.265 level should be 6.0 (180)"
1749        );
1750        assert_eq!(
1751            ptl.profile_id(),
1752            1,
1753            "Default H.265 profile should be Main (1)"
1754        );
1755        assert_eq!(ptl.tier_flag(), 0, "Default H.265 tier should be Main (0)");
1756    }
1757
1758    // H.266 direction-based negotiation tests.
1759
1760    /// Helper: build a CodecConfig containing only H.266 at the given PTL.
1761    fn h266_config(profile_id: u8, tier_flag: u8, level_id: u8) -> CodecConfig {
1762        let mut config = CodecConfig::empty();
1763        config.add_h266(PT_H266, Some(PT_H266_RTX), profile_id, tier_flag, level_id);
1764        config
1765    }
1766
1767    /// Helper: build a single-element remote PayloadParams for H.266 with full PTL.
1768    fn h266_remote_ptl(profile_id: u8, tier_flag: u8, level_id: u8) -> Vec<PayloadParams> {
1769        vec![PayloadParams::new(
1770            PT_H266,
1771            Some(PT_H266_RTX),
1772            CodecSpec {
1773                codec: Codec::H266,
1774                clock_rate: Frequency::NINETY_KHZ,
1775                channels: None,
1776                format: FormatParams {
1777                    h266_profile_tier_level: Some(
1778                        H266ProfileTierLevel::new(profile_id, tier_flag, level_id).unwrap(),
1779                    ),
1780                    ..Default::default()
1781                },
1782            },
1783        )]
1784    }
1785
1786    /// Helper: build a single-element remote PayloadParams for H.266 with profile-id only.
1787    fn h266_remote_profile_only(profile_id: u32) -> Vec<PayloadParams> {
1788        vec![PayloadParams::new(
1789            PT_H266,
1790            Some(PT_H266_RTX),
1791            CodecSpec {
1792                codec: Codec::H266,
1793                clock_rate: Frequency::NINETY_KHZ,
1794                channels: None,
1795                format: FormatParams {
1796                    profile_id: Some(profile_id),
1797                    ..Default::default()
1798                },
1799            },
1800        )]
1801    }
1802
1803    /// Helper: build a single-element remote PayloadParams for H.266 with no fmtp.
1804    fn h266_remote_no_fmtp() -> Vec<PayloadParams> {
1805        vec![PayloadParams::new(
1806            PT_H266,
1807            Some(PT_H266_RTX),
1808            CodecSpec {
1809                codec: Codec::H266,
1810                clock_rate: Frequency::NINETY_KHZ,
1811                channels: None,
1812                format: FormatParams::default(),
1813            },
1814        )]
1815    }
1816
1817    /// Helper: extract the H.266 param from a config (panics if missing).
1818    fn get_h266(config: &CodecConfig) -> &PayloadParams {
1819        config
1820            .params()
1821            .iter()
1822            .find(|p| p.spec().codec == Codec::H266)
1823            .expect("H.266 param missing")
1824    }
1825
1826    // recvonly: remote sends to us.
1827
1828    /// Remote sends at Level 4.0, we can receive at Level 6.0.
1829    /// Negotiated level should narrow to min(6.0, 4.0) = 4.0.
1830    #[test]
1831    fn test_h266_recvonly_remote_level_lower() {
1832        let mut config = h266_config(1, 0, 96); // Main 10, Main tier, Level 6.0
1833        let remote = h266_remote_ptl(1, 0, 64); // Level 4.0
1834
1835        // Direction::SendOnly = remote is sending (we receive)
1836        config.update_params(&remote, Direction::SendOnly);
1837
1838        let ptl = get_h266(&config)
1839            .spec()
1840            .format
1841            .h266_profile_tier_level
1842            .unwrap();
1843        assert_eq!(
1844            ptl.level_id(),
1845            64,
1846            "Should narrow to min(96,64) = Level 4.0"
1847        );
1848        assert_eq!(ptl.profile_id(), 1, "Profile should be preserved");
1849        assert_eq!(ptl.tier_flag(), 0, "Tier should be preserved");
1850    }
1851
1852    /// Remote sends at Level 6.0, we can receive at Level 4.0.
1853    /// Negotiated level should narrow to min(4.0, 6.0) = 4.0.
1854    #[test]
1855    fn test_h266_recvonly_local_level_lower() {
1856        let mut config = h266_config(1, 0, 64); // Level 4.0
1857        let remote = h266_remote_ptl(1, 0, 96); // Level 6.0
1858
1859        config.update_params(&remote, Direction::SendOnly);
1860
1861        let ptl = get_h266(&config)
1862            .spec()
1863            .format
1864            .h266_profile_tier_level
1865            .unwrap();
1866        assert_eq!(
1867            ptl.level_id(),
1868            64,
1869            "Should narrow to min(64,96) = Level 4.0"
1870        );
1871    }
1872
1873    // sendrecv: both sides send and receive.
1874
1875    /// Both sides sendrecv. Local Level 6.0, remote Level 4.0.
1876    /// Effective level should narrow to min(6.0, 4.0) = 4.0.
1877    #[test]
1878    fn test_h266_sendrecv_remote_level_lower() {
1879        let mut config = h266_config(1, 0, 96); // Level 6.0
1880        let remote = h266_remote_ptl(1, 0, 64); // Level 4.0
1881
1882        config.update_params(&remote, Direction::SendRecv);
1883
1884        let ptl = get_h266(&config)
1885            .spec()
1886            .format
1887            .h266_profile_tier_level
1888            .unwrap();
1889        assert_eq!(ptl.level_id(), 64, "sendrecv: should narrow to Level 4.0");
1890    }
1891
1892    /// Both sides sendrecv. Local Level 4.0, remote Level 6.0.
1893    /// Effective level should narrow to min(4.0, 6.0) = 4.0.
1894    #[test]
1895    fn test_h266_sendrecv_local_level_lower() {
1896        let mut config = h266_config(1, 0, 64); // Level 4.0
1897        let remote = h266_remote_ptl(1, 0, 96); // Level 6.0
1898
1899        config.update_params(&remote, Direction::SendRecv);
1900
1901        let ptl = get_h266(&config)
1902            .spec()
1903            .format
1904            .h266_profile_tier_level
1905            .unwrap();
1906        assert_eq!(ptl.level_id(), 64, "sendrecv: should narrow to Level 4.0");
1907    }
1908
1909    /// Same level on both sides. Should remain unchanged.
1910    #[test]
1911    fn test_h266_sendrecv_same_level() {
1912        let mut config = h266_config(1, 0, 64); // Level 4.0
1913        let remote = h266_remote_ptl(1, 0, 64); // Level 4.0
1914
1915        config.update_params(&remote, Direction::SendRecv);
1916
1917        let ptl = get_h266(&config)
1918            .spec()
1919            .format
1920            .h266_profile_tier_level
1921            .unwrap();
1922        assert_eq!(ptl.level_id(), 64, "Same levels should stay at Level 4.0");
1923    }
1924
1925    // sendonly: we send, remote receives.
1926
1927    /// Remote declares recvonly at Level 4.0, we offer sendonly at Level 6.0.
1928    /// Negotiated level should narrow to 4.0 (receiver wins).
1929    #[test]
1930    fn test_h266_sendonly_receiver_level_lower() {
1931        let mut config = h266_config(1, 0, 96); // Level 6.0
1932        let remote = h266_remote_ptl(1, 0, 64); // Level 4.0
1933
1934        // Direction::RecvOnly = remote is receiving (we send)
1935        config.update_params(&remote, Direction::RecvOnly);
1936
1937        let ptl = get_h266(&config)
1938            .spec()
1939            .format
1940            .h266_profile_tier_level
1941            .unwrap();
1942        assert_eq!(
1943            ptl.level_id(),
1944            64,
1945            "sendonly: should narrow to receiver's Level 4.0"
1946        );
1947    }
1948
1949    /// Remote offers only profile-id=1, no tier/level.
1950    /// Local should drop its full PTL and echo back profile-id only.
1951    #[test]
1952    fn test_h266_profile_only_remote_mirrors() {
1953        let mut config = h266_config(1, 0, 96); // Full PTL
1954        let remote = h266_remote_profile_only(1); // profile-id only
1955
1956        config.update_params(&remote, Direction::SendRecv);
1957
1958        let h266 = get_h266(&config);
1959        assert!(
1960            h266.spec().format.h266_profile_tier_level.is_none(),
1961            "Full PTL should be cleared when remote only offers profile-id"
1962        );
1963        assert_eq!(
1964            h266.spec().format.profile_id,
1965            Some(1),
1966            "profile_id should mirror the remote's value"
1967        );
1968    }
1969
1970    // no-fmtp remote.
1971
1972    /// Remote has no H.266 fmtp at all. Local should clear both fields.
1973    #[test]
1974    fn test_h266_no_fmtp_remote_clears() {
1975        let mut config = h266_config(1, 0, 96); // Full PTL
1976        let remote = h266_remote_no_fmtp();
1977
1978        config.update_params(&remote, Direction::SendRecv);
1979
1980        let h266 = get_h266(&config);
1981        assert!(
1982            h266.spec().format.h266_profile_tier_level.is_none(),
1983            "PTL should be cleared when remote has no fmtp"
1984        );
1985        assert!(
1986            h266.spec().format.profile_id.is_none(),
1987            "profile_id should be cleared when remote has no fmtp"
1988        );
1989    }
1990
1991    // profile_id field cleanup.
1992
1993    /// When remote has full PTL, the `profile_id` field must be None
1994    /// to avoid duplicate serialization (profile-id appears in both
1995    /// h266_profile_tier_level AND the VP9-style profile_id field).
1996    #[test]
1997    fn test_h266_profile_id_cleared_on_ptl_match() {
1998        let mut config = CodecConfig::empty();
1999        // Artificially set both fields to simulate a misconfigured state
2000        config.add_config(
2001            PT_H266,
2002            Some(PT_H266_RTX),
2003            Codec::H266,
2004            Frequency::NINETY_KHZ,
2005            None,
2006            FormatParams {
2007                h266_profile_tier_level: Some(H266ProfileTierLevel::new(1, 0, 96).unwrap()),
2008                profile_id: Some(1), // should be cleared after negotiation
2009                ..Default::default()
2010            },
2011        );
2012        let remote = h266_remote_ptl(1, 0, 64);
2013
2014        config.update_params(&remote, Direction::SendRecv);
2015
2016        let h266 = get_h266(&config);
2017        assert!(
2018            h266.spec().format.profile_id.is_none(),
2019            "profile_id field must be None when full PTL is present"
2020        );
2021        assert!(
2022            h266.spec().format.h266_profile_tier_level.is_some(),
2023            "PTL should still be present"
2024        );
2025    }
2026
2027    // H.266 default level.
2028
2029    /// `enable_h266(true)` should add H.266 at Main 10 / Main tier / Level 6.0.
2030    #[test]
2031    fn test_h266_enable_default_level() {
2032        let mut config = CodecConfig::empty();
2033        config.enable_h266(true);
2034
2035        let h266 = config
2036            .params()
2037            .iter()
2038            .find(|p| p.spec().codec == Codec::H266)
2039            .expect("H.266 param missing");
2040        let ptl = h266.spec().format.h266_profile_tier_level.unwrap();
2041        assert_eq!(
2042            ptl.profile_id(),
2043            1,
2044            "Default H.266 profile should be Main 10 (1)"
2045        );
2046        assert_eq!(ptl.tier_flag(), 0, "Default H.266 tier should be Main (0)");
2047        assert_eq!(ptl.level_id(), 96, "Default H.266 level should be 6.0 (96)");
2048    }
2049}