1use 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
14pub(crate) const PREFERED_RANGES: &[RangeInclusive<usize>] = &[
16 96..=127,
18 80..=95,
21 77..=78,
22 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 None
69 }
70}
71
72#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
86pub struct PayloadParams {
87 pub(crate) pt: Pt,
89
90 pub(crate) resend: Option<Pt>,
93
94 pub(crate) spec: CodecSpec,
96
97 pub(crate) fb_transport_cc: bool,
99
100 pub(crate) fb_nack: bool,
102
103 pub(crate) fb_pli: bool,
105
106 pub(crate) fb_fir: bool,
108
109 pub(crate) fb_remb: bool,
111
112 pub(crate) red: Option<Pt>,
115
116 pub(crate) locked: bool,
122
123 #[serde(default)]
126 pub(crate) rtx_declined: bool,
127}
128
129impl 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 const EXACT_MATCH_SCORE: usize = 100;
155
156 const PROFILE_ONLY_MATCH_SCORE: usize = 90;
162
163 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 fb_transport_cc: true,
179
180 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 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 pub fn pt(&self) -> Pt {
223 self.pt
224 }
225
226 pub fn resend(&self) -> Option<Pt> {
229 self.resend
230 }
231
232 pub fn set_resend(&mut self, resend: Option<Pt>) {
235 self.resend = resend;
236 }
237
238 pub fn spec(&self) -> CodecSpec {
240 self.spec
241 }
242
243 pub fn set_fb_transport_cc(&mut self, fb_transport_cc: bool) {
245 self.fb_transport_cc = fb_transport_cc
246 }
247
248 pub fn fb_transport_cc(&self) -> bool {
250 self.fb_transport_cc
251 }
252
253 pub fn set_fb_nack(&mut self, fb_nack: bool) {
255 self.fb_nack = fb_nack
256 }
257
258 pub fn fb_nack(&self) -> bool {
260 self.fb_nack
261 }
262
263 pub fn set_fb_pli(&mut self, fb_pli: bool) {
265 self.fb_pli = fb_pli
266 }
267
268 pub fn fb_pli(&self) -> bool {
270 self.fb_pli
271 }
272
273 pub fn set_fb_fir(&mut self, fb_fir: bool) {
275 self.fb_fir = fb_fir
276 }
277
278 pub fn fb_fir(&self) -> bool {
280 self.fb_fir
281 }
282
283 pub fn set_fb_remb(&mut self, fb_remb: bool) {
285 self.fb_remb = fb_remb
286 }
287
288 pub fn fb_remb(&self) -> bool {
290 self.fb_remb
291 }
292
293 pub fn red(&self) -> Option<Pt> {
295 self.red
296 }
297
298 pub(crate) fn match_score(&self, o: &PayloadParams) -> Option<usize> {
299 let c0 = self.spec;
301 let c1 = o.spec;
302
303 if c0 == c1 && c0.codec != Codec::AmrWb {
304 return Some(Self::EXACT_MATCH_SCORE);
306 }
307
308 if c0.codec != c1.codec || (c0.codec == Codec::Unknown && c1.codec == Codec::Unknown) {
310 return None;
312 }
313
314 if c0.clock_rate != c1.clock_rate {
315 return None;
317 }
318
319 if c0.codec.is_tele() {
321 return Some(Self::EXACT_MATCH_SCORE);
322 }
323
324 if c0.codec == Codec::AmrWb {
327 return Self::match_amr_wb_score(c0, c1);
328 }
329
330 if c0.channels != c1.channels {
331 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 None
363 }
364
365 fn match_opus_score(c0: CodecSpec, c1: CodecSpec) -> usize {
366 let mut score: usize = Self::EXACT_MATCH_SCORE;
367
368 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 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 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 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 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 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 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 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 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 if c0_profile_level.profile() != c1_profile_level.profile() {
492 return None;
493 }
494
495 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 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 if c0_ptl.profile() != c1_ptl.profile() {
548 return None;
549 }
550
551 if c0_ptl.tier() != c1_ptl.tier() {
556 return None;
557 }
558
559 let level_difference: usize =
562 c0_ptl.level().ordinal().abs_diff(c1_ptl.level().ordinal());
563
564 Some(Self::EXACT_MATCH_SCORE.saturating_sub(level_difference))
566 }
567 _ => {
568 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 if c0_profile != c1_profile {
588 return None;
589 }
590
591 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 if c0_ptl.profile() != c1_ptl.profile() {
610 return None;
611 }
612
613 if c0_ptl.tier() != c1_ptl.tier() {
617 return None;
618 }
619
620 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 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 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 .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 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 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 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 self.spec.format.profile_id = None;
712 } else if let Some(profile_id) = first.spec.format.profile_id {
713 self.spec.format.h265_profile_tier_level = None;
715 self.spec.format.profile_id = Some(profile_id);
716 } else {
717 self.spec.format.h265_profile_tier_level = None;
719 self.spec.format.profile_id = None;
720 }
721
722 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 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 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 self.spec.format.profile_id = None;
744 } else if let Some(profile_id) = first.spec.format.profile_id {
745 self.spec.format.h266_profile_tier_level = None;
747 self.spec.format.profile_id = Some(profile_id);
748 } else {
749 self.spec.format.h266_profile_tier_level = None;
751 self.spec.format.profile_id = None;
752 }
753
754 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 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 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 if local_is_controlling {
798 return;
799 }
800 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 if local_is_controlling && claimed.is_claimed(remote_pt) {
824 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 if !claimed.assert_claim_once(remote_pt) {
844 return;
845 }
846 self.pt = remote_pt;
847
848 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 self.rtx_declined = self.resend.is_none();
871
872 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 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 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 debug!("No free PT for RED; dropping it");
900 remote_red = None;
901 }
902 } else {
903 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 self.fb_nack = self.fb_nack && first.fb_nack;
922
923 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 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 let mut claimed = [false; 128];
972 claimed[*red_pt as usize] = true;
973 let mut unlocked = HashSet::new();
974
975 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 Case {
1066 c0: h264_codec_spec(None, None, Some(0x42e028)), c1: h264_codec_spec(None, None, Some(0x42e028)), expected: Some(PayloadParams::EXACT_MATCH_SCORE),
1069 msg: "Same profile (CB) and same level (4.0) should match",
1070 },
1071 Case {
1073 c0: h264_codec_spec(None, None, Some(0x42e028)), c1: h264_codec_spec(None, None, Some(0x42e01f)), 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 Case {
1080 c0: h264_codec_spec(None, None, Some(0x42e01f)), c1: h264_codec_spec(None, None, Some(0x42e028)), 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 Case {
1088 c0: h264_codec_spec(None, None, Some(0x42e028)), c1: h264_codec_spec(None, None, Some(0x4d0028)), expected: None,
1091 msg: "Different profiles (CB vs Main) should NOT match even with same level",
1092 },
1093 Case {
1095 c0: h264_codec_spec(None, None, Some(0x4d002a)), c1: h264_codec_spec(None, None, Some(0x4d0028)), expected: Some(PayloadParams::EXACT_MATCH_SCORE - 2),
1098 msg: "Same profile (Main), offered level 4.0 < configured 4.2 should match",
1099 },
1100 Case {
1102 c0: h264_codec_spec(None, None, Some(0x640033)), c1: h264_codec_spec(None, None, Some(0x64001f)), expected: Some(PayloadParams::EXACT_MATCH_SCORE - 6),
1105 msg: "Same profile (High), offered level 3.1 < configured 5.1 should match",
1106 },
1107 Case {
1109 c0: h264_codec_spec(None, None, Some(0x42001f)), c1: h264_codec_spec(None, None, Some(0x420000)), expected: Some(PayloadParams::EXACT_MATCH_SCORE - 8),
1112 msg: "Same profile (Baseline), offered level 1B < configured 3.1 should match",
1113 },
1114 Case {
1116 c0: h264_codec_spec(None, None, Some(0x420000)), c1: h264_codec_spec(None, None, Some(0x42000a)), expected: Some(PayloadParams::EXACT_MATCH_SCORE - 1),
1119 msg: "Same profile (Baseline), offered level 1 < configured 1B should match",
1120 },
1121 Case {
1123 c0: h264_codec_spec(None, None, Some(0x42000a)), c1: h264_codec_spec(None, None, Some(0x420000)), expected: Some(PayloadParams::EXACT_MATCH_SCORE - 1),
1126 msg: "Same profile (Baseline), offered level 1B > configured 1 should match",
1127 },
1128 Case {
1131 c0: h264_codec_spec(Some(true), Some(1), Some(0x42e01f)), c1: h264_codec_spec(Some(true), Some(1), Some(0x42e034)), expected: Some(PayloadParams::EXACT_MATCH_SCORE - 7),
1134 msg: "Same profile (CB), offered level 5.2 > configured 3.1 should match",
1135 },
1136 Case {
1139 c0: h264_codec_spec(Some(true), Some(1), Some(0x640c1f)), c1: h264_codec_spec(Some(true), Some(1), Some(0x640c34)), expected: Some(PayloadParams::EXACT_MATCH_SCORE - 7),
1142 msg: "Same profile (Constrained High), offered level 5.2 should match",
1143 },
1144 Case {
1146 c0: h264_codec_spec(None, None, Some(0x64001f)), c1: h264_codec_spec(None, None, Some(0x640c1f)), 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]
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 Case {
1213 c0: h265_codec_spec(1, 0, 93), 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 Case {
1220 c0: h265_codec_spec(1, 0, 120), c1: h265_codec_spec(1, 0, 93), must_match: true,
1223 msg: "Same profile/tier, offered level 3.1 < configured 4.0 should match",
1224 },
1225 Case {
1227 c0: h265_codec_spec(1, 0, 93), c1: h265_codec_spec(1, 0, 120), must_match: true,
1230 msg: "Same profile/tier, offered level 4.0 > configured 3.1 should match (penalized)",
1231 },
1232 Case {
1234 c0: h265_codec_spec(1, 0, 93), c1: h265_codec_spec(2, 0, 93), must_match: false,
1237 msg: "Different profiles (Main vs Main10) should NOT match",
1238 },
1239 Case {
1241 c0: h265_codec_spec(1, 0, 93), c1: h265_codec_spec(1, 1, 93), must_match: false,
1244 msg: "Different tiers (Main vs High) should NOT match",
1245 },
1246 Case {
1248 c0: h265_codec_spec(2, 0, 153), c1: h265_codec_spec(2, 0, 120), must_match: true,
1251 msg: "Main10 profile, offered level 4.0 < configured 5.1 should match",
1252 },
1253 Case {
1255 c0: h265_codec_spec(1, 1, 153), c1: h265_codec_spec(1, 1, 93), 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]
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 Case {
1288 c0: h265_codec_spec(1, 0, 93), c1: h265_codec_spec(1, 0, 93),
1290 expected: Some(PayloadParams::EXACT_MATCH_SCORE),
1291 msg: "Exact match should return score 100",
1292 },
1293 Case {
1295 c0: h265_codec_spec(1, 0, 120), c1: h265_codec_spec(1, 0, 93), expected: Some(PayloadParams::EXACT_MATCH_SCORE - 1),
1298 msg: "One level difference should return score 99",
1299 },
1300 Case {
1302 c0: h265_codec_spec(1, 0, 123), c1: h265_codec_spec(1, 0, 93), expected: Some(PayloadParams::EXACT_MATCH_SCORE - 2),
1305 msg: "Two level difference should return score 98",
1306 },
1307 Case {
1309 c0: h265_codec_spec(1, 0, 153), c1: h265_codec_spec(1, 0, 93), expected: Some(PayloadParams::EXACT_MATCH_SCORE - 4),
1312 msg: "Four level difference (5.1 to 3.1) should return score 96",
1313 },
1314 Case {
1316 c0: h265_codec_spec(1, 0, 93), c1: h265_codec_spec(1, 0, 120), expected: Some(PayloadParams::EXACT_MATCH_SCORE - 1),
1319 msg: "Offered level one higher than configured should return score 99",
1320 },
1321 Case {
1323 c0: h265_codec_spec(1, 0, 93), c1: h265_codec_spec(2, 0, 93), expected: None,
1326 msg: "Different profiles should return None",
1327 },
1328 Case {
1330 c0: h265_codec_spec(1, 0, 93), c1: h265_codec_spec(1, 1, 93), 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]
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 Case {
1366 c0: h265_codec_spec_profile_only(1), c1: h265_codec_spec_profile_only(1), expected: Some(PayloadParams::PROFILE_ONLY_MATCH_SCORE),
1369 msg: "Profile-only match (Main) should return score 90",
1370 },
1371 Case {
1373 c0: h265_codec_spec_profile_only(1), c1: h265_codec_spec_profile_only(2), expected: None,
1376 msg: "Profile-only with different profiles should return None",
1377 },
1378 Case {
1380 c0: h265_codec_spec(1, 0, 93), c1: h265_codec_spec_profile_only(1), expected: Some(PayloadParams::PROFILE_ONLY_MATCH_SCORE),
1383 msg: "Mixed PTL and profile-only with matching profile should return score 90",
1384 },
1385 Case {
1387 c0: h265_codec_spec(1, 0, 93), c1: h265_codec_spec_profile_only(2), expected: None,
1390 msg: "Mixed PTL and profile-only with different profiles should return None",
1391 },
1392 Case {
1394 c0: h265_codec_spec_profile_only(1), c1: h265_codec_spec(1, 0, 93), 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]
1418 fn test_negative_cases() {
1419 struct Case {
1420 c0: CodecSpec,
1421 c1: CodecSpec,
1422 msg: &'static str,
1423 }
1424
1425 let cases = [
1426 Case {
1428 c0: h265_codec_spec(1, 0, 93), c1: h265_codec_spec(2, 0, 93), msg: "Profile mismatch (Main vs Main10) must not match",
1431 },
1432 Case {
1434 c0: h265_codec_spec(1, 0, 93), c1: h265_codec_spec(1, 1, 93), msg: "Tier mismatch (Main vs High) must not match",
1437 },
1438 Case {
1440 c0: h265_codec_spec(1, 0, 93), c1: h265_codec_spec(2, 1, 153), msg: "Profile and tier different must not match",
1443 },
1444 Case {
1446 c0: h265_codec_spec_profile_only(1), c1: h265_codec_spec_profile_only(2), msg: "Profile-only mismatch must not match",
1449 },
1450 Case {
1452 c0: h265_codec_spec(2, 0, 93), c1: h265_codec_spec_profile_only(1), 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]
1470 fn test_sprop_max_don_diff_negotiation_enables_donl() {
1471 use crate::packet::{CodecDepacketizer, CodecPacketizer};
1472
1473 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 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 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, &mut unlocked,
1502 );
1503
1504 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 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 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, "Packetized output should include 2-byte DONL field"
1534 );
1535
1536 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 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 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]
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 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 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 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]
1606 fn test_sprop_max_don_diff_absent_preserves_local() {
1607 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 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 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]
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 Case {
1683 c0: h266_codec_spec(1, 0, 51), 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 Case {
1690 c0: h266_codec_spec(1, 0, 64), c1: h266_codec_spec(1, 0, 51), must_match: true,
1693 msg: "Same profile/tier, offered level 3.1 < configured 4.0 should match",
1694 },
1695 Case {
1697 c0: h266_codec_spec(1, 0, 51), c1: h266_codec_spec(1, 0, 64), must_match: true,
1700 msg: "Same profile/tier, offered level 4.0 > configured 3.1 should match (penalized)",
1701 },
1702 Case {
1704 c0: h266_codec_spec(1, 0, 51), c1: h266_codec_spec(33, 0, 51), must_match: false,
1707 msg: "Different profiles (Main vs Main10) should NOT match",
1708 },
1709 Case {
1711 c0: h266_codec_spec(1, 0, 51), c1: h266_codec_spec(1, 1, 51), must_match: false,
1714 msg: "Different tiers (Main vs High) should NOT match",
1715 },
1716 Case {
1718 c0: h266_codec_spec(33, 0, 83), c1: h266_codec_spec(33, 0, 64), must_match: true,
1721 msg: "Main10 profile, offered level 4.0 < configured 5.1 should match",
1722 },
1723 Case {
1725 c0: h266_codec_spec(1, 1, 83), c1: h266_codec_spec(1, 1, 51), 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]
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 Case {
1758 c0: h266_codec_spec(1, 0, 51), c1: h266_codec_spec(1, 0, 51),
1760 expected: Some(PayloadParams::EXACT_MATCH_SCORE),
1761 msg: "Exact match should return score 100",
1762 },
1763 Case {
1765 c0: h266_codec_spec(1, 0, 64), c1: h266_codec_spec(1, 0, 51), expected: Some(PayloadParams::EXACT_MATCH_SCORE - 1),
1768 msg: "One level difference should return score 99",
1769 },
1770 Case {
1772 c0: h266_codec_spec(1, 0, 67), c1: h266_codec_spec(1, 0, 51), expected: Some(PayloadParams::EXACT_MATCH_SCORE - 2),
1775 msg: "Two level difference should return score 98",
1776 },
1777 Case {
1779 c0: h266_codec_spec(1, 0, 83), c1: h266_codec_spec(1, 0, 51), expected: Some(PayloadParams::EXACT_MATCH_SCORE - 4),
1782 msg: "Four level difference (5.1 to 3.1) should return score 96",
1783 },
1784 Case {
1786 c0: h266_codec_spec(1, 0, 51), c1: h266_codec_spec(1, 0, 64), expected: Some(PayloadParams::EXACT_MATCH_SCORE - 1),
1789 msg: "Offered level one higher than configured should return score 99",
1790 },
1791 Case {
1793 c0: h266_codec_spec(1, 0, 51), c1: h266_codec_spec(33, 0, 51), expected: None,
1796 msg: "Different profiles should return None",
1797 },
1798 Case {
1800 c0: h266_codec_spec(1, 0, 51), c1: h266_codec_spec(1, 1, 51), 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]
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 Case {
1836 c0: h266_codec_spec_profile_only(1), c1: h266_codec_spec_profile_only(1), expected: Some(PayloadParams::PROFILE_ONLY_MATCH_SCORE),
1839 msg: "Profile-only match (Main) should return score 90",
1840 },
1841 Case {
1843 c0: h266_codec_spec_profile_only(1), c1: h266_codec_spec_profile_only(33), expected: None,
1846 msg: "Profile-only with different profiles should return None",
1847 },
1848 Case {
1850 c0: h266_codec_spec(1, 0, 51), c1: h266_codec_spec_profile_only(1), expected: Some(PayloadParams::PROFILE_ONLY_MATCH_SCORE),
1853 msg: "Mixed PTL and profile-only with matching profile should return score 90",
1854 },
1855 Case {
1857 c0: h266_codec_spec(1, 0, 51), c1: h266_codec_spec_profile_only(33), expected: None,
1860 msg: "Mixed PTL and profile-only with different profiles should return None",
1861 },
1862 Case {
1864 c0: h266_codec_spec_profile_only(1), c1: h266_codec_spec(1, 0, 51), 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]
1888 fn test_negative_cases() {
1889 struct Case {
1890 c0: CodecSpec,
1891 c1: CodecSpec,
1892 msg: &'static str,
1893 }
1894
1895 let cases = [
1896 Case {
1898 c0: h266_codec_spec(1, 0, 51), c1: h266_codec_spec(33, 0, 51), msg: "Profile mismatch (Main vs Main10) must not match",
1901 },
1902 Case {
1904 c0: h266_codec_spec(1, 0, 51), c1: h266_codec_spec(1, 1, 51), msg: "Tier mismatch (Main vs High) must not match",
1907 },
1908 Case {
1910 c0: h266_codec_spec(1, 0, 51), c1: h266_codec_spec(33, 1, 83), msg: "Profile and tier different must not match",
1913 },
1914 Case {
1916 c0: h266_codec_spec_profile_only(1), c1: h266_codec_spec_profile_only(33), msg: "Profile-only mismatch must not match",
1919 },
1920 Case {
1922 c0: h266_codec_spec(33, 0, 51), c1: h266_codec_spec_profile_only(1), 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]
1940 fn test_sprop_max_don_diff_negotiation_enables_donl() {
1941 use crate::packet::{CodecDepacketizer, CodecPacketizer};
1942
1943 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 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 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, &mut unlocked,
1972 );
1973
1974 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 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 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, "Packetized output should include 2-byte DONL field"
2004 );
2005
2006 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 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 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]
2031 fn test_sprop_max_don_diff_absent_preserves_local() {
2032 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 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 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]
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 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 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 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}