rtci 0.2.1

A sans-I/O WebRTC implementation: peer connections with ICE, DTLS-SRTP, SCTP data channels, RTP/RTCP and JSEP negotiation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
use crate::peer_connection::configuration::UNSPECIFIED_STR;
use crate::peer_connection::configuration::media_engine::*;
use crate::rtp_transceiver::rtp_sender::rtcp_parameters::{
    RTCP_FB_ACK_CCFB, RTCP_FB_NACK_ECN, RTCPFeedback, TYPE_RTCP_FB_ACK, TYPE_RTCP_FB_CCM,
    TYPE_RTCP_FB_NACK, TYPE_RTCP_FB_TRANSPORT_CC,
};
use crate::rtp_transceiver::rtp_sender::rtp_codec_parameters::RTCRtpCodecParameters;
use crate::rtp_transceiver::rtp_sender::rtp_encoding_parameters::RTCRtpEncodingParameters;
use crate::rtp_transceiver::{PayloadType, fmtp};
use serde::{Deserialize, Serialize};
use shared::error::{Error, Result};
use std::fmt;

/// Codec kind identifying the media type.
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[non_exhaustive]
pub enum RtpCodecKind {
    /// Unspecified or unknown codec type
    #[default]
    Unspecified = 0,

    /// Audio codec
    #[serde(rename = "audio")]
    Audio = 1,

    /// Video codec
    #[serde(rename = "video")]
    Video = 2,

    /// Non-audio/video RTP-carried application data
    #[serde(rename = "application")]
    Application = 3,
}

impl From<&str> for RtpCodecKind {
    fn from(raw: &str) -> Self {
        match raw {
            "audio" => RtpCodecKind::Audio,
            "video" => RtpCodecKind::Video,
            "application" => RtpCodecKind::Application,
            _ => RtpCodecKind::Unspecified,
        }
    }
}

impl From<u8> for RtpCodecKind {
    fn from(v: u8) -> Self {
        match v {
            1 => RtpCodecKind::Audio,
            2 => RtpCodecKind::Video,
            3 => RtpCodecKind::Application,
            _ => RtpCodecKind::Unspecified,
        }
    }
}

impl fmt::Display for RtpCodecKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match *self {
            RtpCodecKind::Audio => "audio",
            RtpCodecKind::Video => "video",
            RtpCodecKind::Application => "application",
            RtpCodecKind::Unspecified => UNSPECIFIED_STR,
        };
        write!(f, "{s}")
    }
}

/// RTP codec capability providing information about supported codecs.
///
/// ## Specifications
///
/// * [W3C](https://www.w3.org/TR/webrtc/#dictionary-rtcrtpcodec-members)
#[derive(Default, Debug, Clone, PartialEq, Eq)]
pub struct RTCRtpCodec {
    /// MIME type of the codec (e.g., "video/VP8", "audio/opus")
    pub mime_type: String,
    /// Codec clock rate in Hz
    pub clock_rate: u32,
    /// Number of audio channels (0 for video codecs)
    pub channels: u16,
    /// Format-specific parameters as SDP fmtp line
    pub sdp_fmtp_line: String,
    /// RTCP feedback mechanisms supported by this codec (deprecated, will be removed)
    pub rtcp_feedback: Vec<RTCPFeedback>, //TODO: to be removed
}

impl RTCRtpCodec {
    /// Creates an RTP payloader for this codec.
    ///
    /// Returns a boxed trait object implementing the Payloader interface
    /// for packetizing media frames into RTP packets.
    ///
    /// # Errors
    ///
    /// Returns `Error::ErrNoPayloaderForCodec` if the codec is not supported.
    pub fn payloader(&self) -> Result<Box<dyn rtp::packetizer::Payloader>> {
        let mime_type = self.mime_type.to_lowercase();
        if mime_type == MIME_TYPE_H264.to_lowercase() {
            // RFC 6184 6.2: the negotiated packetization mode decides whether STAP-A and FU-A
            // may be sent at all; an absent parameter means mode 0, mode 2 is interleaved
            // (section 6.4), and a value above 2 is no mode (section 8.1).
            Ok(Box::new(
                rtp::codec::h264::H264Payloader::try_with_packetization_mode(
                    h264_packetization_mode(&self.sdp_fmtp_line),
                )?,
            ))
        } else if mime_type == MIME_TYPE_HEVC.to_lowercase() {
            Ok(Box::<rtp::codec::h265::HevcPayloader>::default())
        } else if mime_type == MIME_TYPE_VP8.to_lowercase() {
            let mut vp8_payloader = rtp::codec::vp8::Vp8Payloader::default();
            vp8_payloader.enable_picture_id = true;
            Ok(Box::new(vp8_payloader))
        } else if mime_type == MIME_TYPE_VP9.to_lowercase() {
            Ok(Box::<rtp::codec::vp9::Vp9Payloader>::default())
        } else if mime_type == MIME_TYPE_OPUS.to_lowercase() {
            Ok(Box::<rtp::codec::opus::OpusPayloader>::default())
        } else if mime_type == MIME_TYPE_G722.to_lowercase()
            || mime_type == MIME_TYPE_PCMU.to_lowercase()
            || mime_type == MIME_TYPE_PCMA.to_lowercase()
            || mime_type == MIME_TYPE_TELEPHONE_EVENT.to_lowercase()
        {
            Ok(Box::<rtp::codec::g7xx::G7xxPayloader>::default())
        } else if mime_type == MIME_TYPE_CN.to_lowercase() {
            Ok(Box::<rtp::codec::comfort_noise::ComfortNoisePayloader>::default())
        } else if mime_type == MIME_TYPE_AV1.to_lowercase() {
            Ok(Box::<rtp::codec::av1::Av1Payloader>::default())
        } else if mime_type == MIME_TYPE_SMPTE336M.to_lowercase() {
            Ok(Box::<rtp::codec::smpte336m::Smpte336mPayloader>::default())
        } else {
            Err(Error::ErrNoPayloaderForCodec)
        }
    }

    /// Creates an H.264 depacketizer for a stream received with this codec, configured from
    /// the sender's stream properties in its fmtp line: with `packetization-mode=2` NAL units
    /// leave in decoding order through a de-interleaving buffer sized by
    /// `sprop-interleaving-depth` and `sprop-max-don-diff` (RFC 6184 sections 7.2.2, 8.1).
    ///
    /// Use it on a remote track's codec: its fmtp line is the one the sender described.
    ///
    /// **This default does not follow RFC 6184 section 7.2.** The RFC initialises PDON to 0,
    /// so a NAL unit whose DON is 0 is at the largest DON distance (65536) and a stream
    /// numbered from DON 0 has its first NAL unit passed on last; here, until a NAL unit has
    /// been passed on, PDON is the DON just before the earliest one buffered (owner decision,
    /// 2026-11-26; `docs/conformance.md`, "Standing departures from a MUST").
    /// [`MediaEngine::h264_depacketizer`] with [`MediaEngine::set_h264_literal_pdon`]`(true)`,
    /// which the `StrictRfc` behaviour profile sets, gives the RFC's form
    /// ([`H264DeinterleavingBuffer::with_literal_pdon`]).
    ///
    /// [`MediaEngine::h264_depacketizer`]: crate::peer_connection::configuration::media_engine::MediaEngine::h264_depacketizer
    /// [`MediaEngine::set_h264_literal_pdon`]: crate::peer_connection::configuration::media_engine::MediaEngine::set_h264_literal_pdon
    /// [`H264DeinterleavingBuffer::with_literal_pdon`]: rtp::codec::h264::H264DeinterleavingBuffer::with_literal_pdon
    ///
    /// # Errors
    ///
    /// `Error::ErrNoPayloaderForCodec` for a codec other than H.264; an error for a
    /// `packetization-mode` other than 0, 1 or 2.
    pub fn h264_depacketizer(&self) -> Result<rtp::codec::h264::H264Packet> {
        self.h264_depacketizer_with(false)
    }

    /// [`Self::h264_depacketizer`], with RFC 6184 section 7.2.2's PDON initialised to 0 when
    /// `literal_pdon` is set.
    pub(crate) fn h264_depacketizer_with(
        &self,
        literal_pdon: bool,
    ) -> Result<rtp::codec::h264::H264Packet> {
        if !self.mime_type.eq_ignore_ascii_case(MIME_TYPE_H264) {
            return Err(Error::ErrNoPayloaderForCodec);
        }
        let packet = rtp::codec::h264::H264Packet::default();
        match h264_packetization_mode(&self.sdp_fmtp_line) {
            0 | 1 => Ok(packet),
            2 => Ok(packet.with_deinterleaving(
                rtp::codec::h264::H264DeinterleavingBuffer::new(
                    fmtp_number(&self.sdp_fmtp_line, "sprop-interleaving-depth").unwrap_or(0),
                    fmtp_number(&self.sdp_fmtp_line, "sprop-max-don-diff"),
                )
                .with_literal_pdon(literal_pdon),
            )),
            other => Err(Error::Other(format!(
                "H.264 packetization-mode is 0, 1 or 2, not {other}"
            ))),
        }
    }

    /// Creates an H.265 depacketizer for a stream received with this codec, configured from
    /// the sender's stream properties in its fmtp line: with `sprop-max-don-diff` above 0
    /// the DONL and DOND fields are read and NAL units leave in decoding order through a
    /// de-packetization buffer of `sprop-depack-buf-nalus` (RFC 7798 sections 6, 7.1).
    ///
    /// # Errors
    ///
    /// `Error::ErrNoPayloaderForCodec` for a codec other than H.265; an error for a `tx-mode`
    /// other than SRST, which the depacketizer does not do (RFC 7798 section 7.1: "If the
    /// value is equal to "MRST", MRST MUST be in use").
    pub fn h265_depacketizer(&self) -> Result<rtp::codec::h265::H265Packet> {
        if !self.mime_type.eq_ignore_ascii_case(MIME_TYPE_HEVC) {
            return Err(Error::ErrNoPayloaderForCodec);
        }
        let tx_mode = fmtp_value(&self.sdp_fmtp_line, "tx-mode");
        if tx_mode.is_some_and(|mode| !mode.eq_ignore_ascii_case("SRST")) {
            return Err(Error::Other(format!(
                "H.265 tx-mode {} is not supported, only SRST",
                tx_mode.unwrap_or_default()
            )));
        }
        let mut packet = rtp::codec::h265::H265Packet::default();
        let max_don_diff = fmtp_number(&self.sdp_fmtp_line, "sprop-max-don-diff").unwrap_or(0);
        if max_don_diff > 0 {
            packet.with_depacketization_buffer(rtp::codec::h265::H265DepacketizationBuffer::new(
                max_don_diff,
                fmtp_number(&self.sdp_fmtp_line, "sprop-depack-buf-nalus").unwrap_or(0),
            ));
        }
        Ok(packet)
    }

    /// The out-of-band parameter sets of the sender's stream, in the order the fmtp line
    /// gives them: H.264 `sprop-parameter-sets` (RFC 6184 section 8.1, base64 NAL units
    /// separated by commas), H.265 `sprop-vps`, `sprop-sps`, `sprop-pps` and `sprop-sei`
    /// (RFC 7798 section 7.1). A decoder takes them before the first NAL unit of the stream
    /// (RFC 6184 section 8.2.2, RFC 7798 section 7.2.2). Empty for another codec or a line
    /// without them.
    ///
    /// # Errors
    ///
    /// A value that is not base64.
    pub fn sprop_parameter_sets(&self) -> Result<Vec<bytes::Bytes>> {
        use base64::Engine as _;
        let keys: &[&str] = if self.mime_type.eq_ignore_ascii_case(MIME_TYPE_H264) {
            &["sprop-parameter-sets"]
        } else if self.mime_type.eq_ignore_ascii_case(MIME_TYPE_HEVC) {
            &["sprop-vps", "sprop-sps", "sprop-pps", "sprop-sei"]
        } else {
            &[]
        };
        let mut sets = vec![];
        for key in keys {
            let Some(value) = fmtp_value(&self.sdp_fmtp_line, key) else {
                continue;
            };
            for set in value.split(',').map(str::trim).filter(|s| !s.is_empty()) {
                let nal_unit = base64::engine::general_purpose::STANDARD
                    .decode(set)
                    .map_err(|e| Error::Other(format!("{key}: {e}")))?;
                sets.push(bytes::Bytes::from(nal_unit));
            }
        }
        Ok(sets)
    }
}

/// The value of an fmtp parameter, trimmed; parameter names compare without regard to case.
fn fmtp_value<'a>(sdp_fmtp_line: &'a str, key: &str) -> Option<&'a str> {
    sdp_fmtp_line
        .split(';')
        .filter_map(|parameter| parameter.trim().split_once('='))
        .find(|(k, _)| k.trim().eq_ignore_ascii_case(key))
        .map(|(_, value)| value.trim())
}

fn fmtp_number<T: std::str::FromStr>(sdp_fmtp_line: &str, key: &str) -> Option<T> {
    fmtp_value(sdp_fmtp_line, key)?.parse().ok()
}

/// The `packetization-mode` an H.264 fmtp line names, 0 when it names none (RFC 6184 8.1).
pub(crate) fn h264_packetization_mode(sdp_fmtp_line: &str) -> u8 {
    fmtp_number::<u32>(sdp_fmtp_line, "packetization-mode")
        .map_or(0, |mode| u8::try_from(mode).unwrap_or(u8::MAX))
}

/// Codec match quality result from fuzzy search.
#[derive(Default, Debug, Copy, Clone, PartialEq)]
pub(crate) enum CodecMatch {
    /// No match found
    #[default]
    None = 0,
    /// Partial match (MIME type matches)
    Partial = 1,
    /// Exact match (MIME type and format parameters match)
    Exact = 2,
}

/// Performs fuzzy search for a codec in a list of available codecs.
///
/// First attempts an exact match on both MIME type and format parameters,
/// then falls back to matching only the MIME type.
///
/// # Parameters
///
/// * `needle_rtp_codec` - The codec to search for
/// * `haystack` - List of available codecs to search in
///
/// # Returns
///
/// A tuple of (matched codec parameters, match quality)
pub(crate) fn codec_parameters_fuzzy_search(
    needle_rtp_codec: &RTCRtpCodec,
    haystack: &[RTCRtpCodecParameters],
) -> (RTCRtpCodecParameters, CodecMatch) {
    let needle_fmtp = fmtp::parse(&needle_rtp_codec.mime_type, &needle_rtp_codec.sdp_fmtp_line);
    // A format is its encoding name and its clock rate (RFC 8866 section 6.6, `a=rtpmap`):
    // `telephone-event/8000` and `telephone-event/48000` are two formats. A needle that
    // states no clock rate (an encoding that leaves its codec to negotiation) matches any.
    // So are its encoding parameters, the channel count of an audio format (`opus/48000/2`;
    // RFC 7587 section 7: Opus "MUST" be `opus/48000/2`): two formats that state different
    // counts are different formats. One that states none matches any.
    let same_clock_rate = |c: &RTCRtpCodecParameters| {
        (needle_rtp_codec.clock_rate == 0
            || c.rtp_codec.clock_rate == 0
            || c.rtp_codec.clock_rate == needle_rtp_codec.clock_rate)
            && (needle_rtp_codec.channels == 0
                || c.rtp_codec.channels == 0
                || c.rtp_codec.channels == needle_rtp_codec.channels)
    };

    // First attempt to match on mime_type + sdpfmtp_line
    for c in haystack.iter().filter(|c| same_clock_rate(c)) {
        let cfmpt = fmtp::parse(&c.rtp_codec.mime_type, &c.rtp_codec.sdp_fmtp_line);
        if needle_fmtp.match_fmtp(&*cfmpt) {
            return (c.clone(), CodecMatch::Exact);
        }
    }

    // Fallback to just mime_type
    for c in haystack.iter().filter(|c| same_clock_rate(c)) {
        // MIME types are ASCII-only; eq_ignore_ascii_case is sufficient and allocation-free.
        if c.rtp_codec
            .mime_type
            .eq_ignore_ascii_case(&needle_rtp_codec.mime_type)
        {
            return (c.clone(), CodecMatch::Partial);
        }
    }

    (RTCRtpCodecParameters::default(), CodecMatch::None)
}

/// [`codec_parameters_fuzzy_search`], taking among the formats of `haystack` it matches
/// exactly the one that is the needle's own.
///
/// The exact match of the fuzzy search compares a format's configuration only (H.264 profile
/// and `packetization-mode`, RFC 6184 section 8.2.2, where the level may differ; VP9
/// `profile-id`; AV1 `profile`; H.265 profile and tier), so several registered formats of one
/// configuration that differ in level or in another parameter all match, and the first
/// one would stand for all of them (an offer gave the payload types of H.264 High levels 4.0
/// to 5.1 the line of Level 5.0). Among the exact matches this takes, in order:
///
/// 1. one with the same parameters (W3C webrtc 5.4 codec dictionary match, asymmetrical
///    parameters included) and the payload type `payload_type`,
/// 2. one with the same parameters,
/// 3. one with the payload type `payload_type`,
/// 4. the first, as [`codec_parameters_fuzzy_search`] does.
///
/// A partial match or none is the fuzzy search's.
pub(crate) fn codec_parameters_search(
    needle_rtp_codec: &RTCRtpCodec,
    payload_type: Option<PayloadType>,
    haystack: &[RTCRtpCodecParameters],
) -> (RTCRtpCodecParameters, CodecMatch) {
    let (first, matched) = codec_parameters_fuzzy_search(needle_rtp_codec, haystack);
    if matched != CodecMatch::Exact {
        return (first, matched);
    }
    let exact: Vec<&RTCRtpCodecParameters> = haystack
        .iter()
        .filter(|c| {
            codec_parameters_fuzzy_search(needle_rtp_codec, std::slice::from_ref(*c)).1
                == CodecMatch::Exact
        })
        .collect();
    let same_payload_type = |c: &&&RTCRtpCodecParameters| Some(c.payload_type) == payload_type;
    let same_parameters =
        |c: &&&RTCRtpCodecParameters| codec_dictionary_match(needle_rtp_codec, &c.rtp_codec);
    let own = exact
        .iter()
        .find(|c| same_parameters(c) && same_payload_type(c))
        .or_else(|| exact.iter().find(same_parameters))
        .or_else(|| exact.iter().find(same_payload_type));
    match own {
        Some(own) => ((*own).clone(), CodecMatch::Exact),
        None => (first, matched),
    }
}

/// W3C webrtc 5.4 "codec dictionary match" with `ignoreAsymmetricalParameters` false (its
/// default): see [`codec_dictionary_match_with`].
pub(crate) fn codec_dictionary_match(first: &RTCRtpCodec, second: &RTCRtpCodec) -> bool {
    codec_dictionary_match_with(first, second, false)
}

/// W3C webrtc 5.4 "codec dictionary match": whether two codec dictionaries name the same
/// codec. The MIME types are equal without regard to case, the clock rates equal, the
/// channels both absent (0) or equal, and the `sdpFmtpLine`s both absent (empty) or
/// matching. Lines that are not in key-value format are compared as strings. Key-value
/// lines must agree on the format's symmetrical parameters (`fmtp::match_fmtp`: H.264
/// profile and packetization mode, H.265 profile, VP9 profile, AV1 nothing, and so on); with
/// `ignore_asymmetrical_parameters` false every parameter must be equal too, a parameter
/// left out counting as its default where the format infers one ("In some cases a parameter
/// can be omitted and still be inferred").
pub(crate) fn codec_dictionary_match_with(
    first: &RTCRtpCodec,
    second: &RTCRtpCodec,
    ignore_asymmetrical_parameters: bool,
) -> bool {
    if !first.mime_type.eq_ignore_ascii_case(&second.mime_type)
        || first.clock_rate != second.clock_rate
        || first.channels != second.channels
    {
        return false;
    }
    let (first_fmtp, second_fmtp) = (first.sdp_fmtp_line.trim(), second.sdp_fmtp_line.trim());
    if first_fmtp.is_empty() != second_fmtp.is_empty() {
        return false;
    }
    if first_fmtp.is_empty() {
        return true;
    }
    if !first_fmtp.contains('=') || !second_fmtp.contains('=') {
        return first_fmtp == second_fmtp;
    }
    if !fmtp::parse(&first.mime_type, first_fmtp)
        .match_fmtp(&*fmtp::parse(&second.mime_type, second_fmtp))
    {
        return false;
    }
    ignore_asymmetrical_parameters
        || media_format(&first.mime_type, first_fmtp)
            == media_format(&second.mime_type, second_fmtp)
}

/// The media format of a key-value `sdpFmtpLine` (W3C webrtc 5.4): each parameter by its
/// lower-case name, with the defaults the format infers for one left out.
fn media_format(mime_type: &str, fmtp: &str) -> std::collections::BTreeMap<String, String> {
    let mut parameters: std::collections::BTreeMap<String, String> = fmtp
        .split(';')
        .filter_map(|p| {
            let (key, value) = p.split_once('=')?;
            Some((key.trim().to_ascii_lowercase(), value.trim().to_owned()))
        })
        .collect();
    let defaults: &[(&str, &str)] = match mime_type.to_ascii_lowercase().as_str() {
        // RFC 6184 section 8.1.
        "video/h264" => &[
            ("packetization-mode", "0"),
            ("level-asymmetry-allowed", "0"),
        ],
        // RFC 7798 section 7.1.
        "video/h265" => &[("profile-id", "1"), ("tier-flag", "0"), ("level-id", "93")],
        // RTP payload format for VP9, section 6.
        "video/vp9" => &[("profile-id", "0")],
        // AV1 RTP payload format, section 7.2.
        "video/av1" => &[("profile", "0"), ("level-idx", "5"), ("tier", "0")],
        _ => &[],
    };
    for (key, value) in defaults {
        parameters
            .entry((*key).to_owned())
            .or_insert_with(|| (*value).to_owned());
    }
    parameters
}

/// The negotiated codec an encoding is sent with.
///
/// An encoding that names a codec is sent with the negotiated codec matching it
/// ([`codec_parameters_fuzzy_search`]). One that names none (an empty `codec`, the
/// `RTCRtpCodec` default: W3C `addTransceiver` lets `sendEncodings` leave the codec to
/// negotiation) is sent with the first media codec of the negotiated list, the codec the
/// sender's parameters prefer; repair formats (RTX, RED, ULPFEC, FlexFEC) only accompany
/// a media codec and are never it.
///
/// # Returns
///
/// `None` when the encoding names a codec that was not negotiated, or names none and the
/// negotiated list has no media codec.
pub(crate) fn encoding_send_codec(
    codec: &RTCRtpCodec,
    negotiated: &[RTCRtpCodecParameters],
) -> Option<RTCRtpCodecParameters> {
    if codec.mime_type.is_empty() {
        return negotiated
            .iter()
            .find(|c| !c.rtp_codec.mime_type.is_empty() && !is_repair_codec(&c.rtp_codec))
            .cloned();
    }
    // W3C webrtc 4.4.1.6: an encoding's codec is the negotiated one it matches by the codec
    // dictionary match with `ignoreAsymmetricalParameters` true (no mime-type-only match).
    negotiated
        .iter()
        .find(|c| codec_dictionary_match_with(codec, &c.rtp_codec, true))
        .cloned()
}

/// Searches for a matching encoding in available codecs.
///
/// Iterates through encodings looking for the best codec match, preferring exact matches.
///
/// # Parameters
///
/// * `encodings` - List of encoding parameters to search through
/// * `haystack` - List of available codec parameters
///
/// # Returns
///
/// A tuple of (matched encoding, match quality)
pub(crate) fn encoding_parameters_fuzzy_search(
    encodings: &[RTCRtpEncodingParameters],
    haystack: &[RTCRtpCodecParameters],
) -> (RTCRtpEncodingParameters, CodecMatch) {
    let mut result = None;
    for encoding in encodings {
        let (_, codec_match_type) = codec_parameters_fuzzy_search(&encoding.codec, haystack);
        if codec_match_type == CodecMatch::Exact {
            return (encoding.clone(), codec_match_type);
        } else if result.is_none() {
            result = Some((encoding.clone(), CodecMatch::Partial));
        }
    }

    if let Some((encoding, code_match_type)) = result {
        (encoding, code_match_type)
    } else {
        (RTCRtpEncodingParameters::default(), CodecMatch::None)
    }
}

/// Finds the RTX payload type associated with a given payload type.
///
/// Searches for an RTX codec with the matching APT (Associated Payload Type) parameter.
///
/// # Parameters
///
/// * `needle` - The primary payload type to find RTX for
/// * `haystack` - List of codec parameters to search
///
/// # Returns
///
/// The RTX payload type if found, None otherwise
pub(crate) fn find_rtx_payload_type(
    needle: PayloadType,
    haystack: &[RTCRtpCodecParameters],
) -> Option<PayloadType> {
    for c in haystack {
        // Match on the parsed `apt` value rather than the whole fmtp line, so an
        // RTX codec carrying extra parameters (e.g. `apt=96;rtx-time=3000`, RFC
        // 4588 §8.1) is still associated with its primary.
        if parse_rtx_apt(&c.rtp_codec.sdp_fmtp_line) == Some(needle) {
            return Some(c.payload_type);
        }
    }

    None
}

/// Parses the associated payload type (`apt`) from an RTX codec's fmtp line.
///
/// RFC 4588 §8.1 defines the `apt` parameter, which maps a retransmission
/// payload type to the payload type of the stream it repairs. The fmtp line may
/// carry additional parameters (e.g. `apt=96;rtx-time=3000`), so the value is
/// extracted from the `apt=` token rather than compared against the whole line.
///
/// # Parameters
///
/// * `sdp_fmtp_line` - The RTX codec's fmtp line, e.g. `"apt=96"`
///
/// # Returns
///
/// The associated (primary) payload type if an `apt=` token is present, else None.
pub(crate) fn parse_rtx_apt(sdp_fmtp_line: &str) -> Option<PayloadType> {
    sdp_fmtp_line
        .split(';')
        .filter_map(|param| param.trim().strip_prefix("apt="))
        .find_map(|value| value.trim().parse::<PayloadType>().ok())
}

/// The `rtx-time` of a retransmission format's fmtp line (RFC 4588 section 8.1: "the time in
/// milliseconds (measured from the time a packet was first sent) that the sender keeps an RTP
/// packet in its buffers available for retransmission"), e.g. of `"apt=96;rtx-time=3000"`.
pub(crate) fn parse_rtx_time(sdp_fmtp_line: &str) -> Option<std::time::Duration> {
    sdp_fmtp_line
        .split(';')
        .filter_map(|param| param.trim().strip_prefix("rtx-time="))
        .find_map(|value| value.trim().parse::<u64>().ok())
        .map(std::time::Duration::from_millis)
}

/// Whether `mime_type` is a retransmission format (`audio/rtx`, `video/rtx`; RFC 4588
/// section 8).
pub(crate) fn is_rtx_mime_type(mime_type: &str) -> bool {
    mime_type
        .split_once('/')
        .is_some_and(|(_, subtype)| subtype.eq_ignore_ascii_case("rtx"))
}

/// Whether `codec` repairs another stream rather than carrying media of its own.
///
/// Covers retransmission (RTX, RFC 4588) and forward error correction (FlexFEC, ULPFEC, RED).
/// These are not alternative media formats a peer chooses between — they accompany whichever
/// primary codec was chosen — which is why codec preferences leave them in place. See
/// [setCodecPreferences](https://www.w3.org/TR/webrtc/#dom-rtcrtptransceiver-setcodecpreferences):
///
/// > Codecs of type RTX, RED and FEC are always supported […] and are not affected by this method.
pub(crate) fn is_repair_codec(codec: &RTCRtpCodec) -> bool {
    let mime_type = codec.mime_type.to_lowercase();
    let subtype = mime_type
        .split_once('/')
        .map_or(mime_type.as_str(), |(_, subtype)| subtype);

    matches!(subtype, "rtx" | "ulpfec" | "red") || subtype.starts_with("flexfec")
}

/// The kind of a repair format: `"rtx"`, `"ulpfec"`, `"red"` or `"flexfec"` (any FlexFEC
/// draft); `""` for a media codec.
pub(crate) fn repair_family(codec: &RTCRtpCodec) -> &'static str {
    let mime_type = codec.mime_type.to_lowercase();
    let subtype = mime_type
        .split_once('/')
        .map_or(mime_type.as_str(), |(_, subtype)| subtype);
    match subtype {
        "rtx" => "rtx",
        "ulpfec" => "ulpfec",
        "red" => "red",
        s if s.starts_with("flexfec") => "flexfec",
        _ => "",
    }
}

/// Whether `mime_type` names FlexFEC draft-ietf-payload-flexible-fec-scheme-03
/// (`video/flexfec-03`), matched exactly.
///
/// RFC 8627's `video/flexfec` is a different wire format (its own header layout and masks), so a
/// substring match, which also took `video/flexfec`, handed RFC 8627 packets to the draft-03
/// coder.
pub(crate) fn is_flexfec03_mime_type(mime_type: &str) -> bool {
    mime_type.eq_ignore_ascii_case(MIME_TYPE_FLEX_FEC03)
}

/// Whether `mime_type` names RFC 8627 FlexFEC (`video/flexfec`), matched exactly: never
/// `video/flexfec-03`, which is the draft-03 coder's.
pub(crate) fn is_flexfec_mime_type(mime_type: &str) -> bool {
    mime_type.eq_ignore_ascii_case(MIME_TYPE_FLEX_FEC)
}

/// Whether `mime_type` names a FEC format the engine has a coder for: FlexFEC draft-03
/// (`video/flexfec-03`) or RFC 8627 (`video/flexfec`).
pub(crate) fn is_fec_mime_type(mime_type: &str) -> bool {
    is_flexfec03_mime_type(mime_type) || is_flexfec_mime_type(mime_type)
}

/// The FEC format a stream's repair flow uses: its payload type and what selects and
/// configures the coder (the interceptors read the MIME type and the `a=fmtp` line).
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct FecFormat {
    pub(crate) payload_type: PayloadType,
    pub(crate) mime_type: String,
    pub(crate) sdp_fmtp_line: String,
}

/// The FEC format of `haystack`: FlexFEC draft-03 when it is there (what browsers send), else
/// RFC 8627 FlexFEC.
pub(crate) fn find_fec_format(haystack: &[RTCRtpCodecParameters]) -> Option<FecFormat> {
    haystack
        .iter()
        .find(|c| is_flexfec03_mime_type(&c.rtp_codec.mime_type))
        .or_else(|| {
            haystack
                .iter()
                .find(|c| is_flexfec_mime_type(&c.rtp_codec.mime_type))
        })
        .map(|c| FecFormat {
            payload_type: c.payload_type,
            mime_type: c.rtp_codec.mime_type.clone(),
            sdp_fmtp_line: c.rtp_codec.sdp_fmtp_line.clone(),
        })
}

/// The FEC format of a remote stream's `FEC-FR` repair flow in `haystack`: as
/// [`find_fec_format`], and else ULPFEC (`video/ulpfec`) as a stream of its own (RFC 5109
/// section 14.1, SSRC-multiplexed in the session as RFC 5956 section 4.3 groups it). Only the
/// receive side reads it: the engine sends ULPFEC in RED unless the application builds the
/// separate stream itself, so a local ULPFEC registration mints no repair SSRC.
pub(crate) fn find_receive_fec_format(haystack: &[RTCRtpCodecParameters]) -> Option<FecFormat> {
    find_fec_format(haystack).or_else(|| {
        haystack
            .iter()
            .find(|c| {
                c.rtp_codec.mime_type.eq_ignore_ascii_case(
                    crate::peer_connection::configuration::media_engine::MIME_TYPE_ULP_FEC,
                )
            })
            .map(|c| FecFormat {
                payload_type: c.payload_type,
                mime_type: c.rtp_codec.mime_type.clone(),
                sdp_fmtp_line: c.rtp_codec.sdp_fmtp_line.clone(),
            })
    })
}

/// The payload type of the FEC format in `haystack` ([`find_fec_format`]).
#[cfg(test)]
pub(crate) fn find_fec_payload_type(haystack: &[RTCRtpCodecParameters]) -> Option<PayloadType> {
    find_fec_format(haystack).map(|format| format.payload_type)
}

/// The RTCP feedback a packet is, as the `a=rtcp-fb` entry (type, first word of the
/// parameter) that negotiates it: NACK, PLI, SLI, RPSI (RFC 4585), FIR, TMMBR / TMMBN, TSTR /
/// TSTN, VBCM (RFC 5104), LRR (`ccm lrr`), REMB (`goog-remb`), transport-wide congestion
/// control (`transport-cc`), RFC 8888 (`ack ccfb`) and the RFC 6679 ECN feedback (`nack ecn`).
/// `None` for what is not feedback (SR, RR, SDES, BYE, APP, XR) and for feedback this endpoint
/// has no negotiation rule for.
pub(crate) fn feedback_negotiating(
    packet: &dyn rtcp::Packet,
) -> Option<(&'static str, &'static str)> {
    use rtcp::payload_feedbacks::{
        full_intra_request::FullIntraRequest,
        layer_refresh_request::LayerRefreshRequest,
        picture_loss_indication::PictureLossIndication,
        receiver_estimated_maximum_bitrate::ReceiverEstimatedMaximumBitrate,
        reference_picture_selection_indication::ReferencePictureSelectionIndication,
        slice_loss_indication::SliceLossIndication,
        temporal_spatial_tradeoff::{
            TemporalSpatialTradeoffNotification, TemporalSpatialTradeoffRequest,
        },
        video_back_channel_message::VideoBackChannelMessage,
    };
    use rtcp::transport_feedbacks::{
        cc_feedback_report::CcFeedbackReport,
        ecn_feedback::EcnFeedback,
        tmmb::{TemporaryMaximumBitrateNotification, TemporaryMaximumBitrateRequest},
        transport_layer_cc::TransportLayerCc,
        transport_layer_nack::TransportLayerNack,
    };
    let any = packet.as_any();
    Some(if any.is::<TransportLayerNack>() {
        ("nack", "")
    } else if any.is::<PictureLossIndication>() {
        ("nack", "pli")
    } else if any.is::<SliceLossIndication>() {
        ("nack", "sli")
    } else if any.is::<ReferencePictureSelectionIndication>() {
        ("nack", "rpsi")
    } else if any.is::<EcnFeedback>() {
        ("nack", "ecn")
    } else if any.is::<FullIntraRequest>() {
        ("ccm", "fir")
    } else if any.is::<TemporaryMaximumBitrateRequest>()
        || any.is::<TemporaryMaximumBitrateNotification>()
    {
        ("ccm", "tmmbr")
    } else if any.is::<TemporalSpatialTradeoffRequest>()
        || any.is::<TemporalSpatialTradeoffNotification>()
    {
        ("ccm", "tstr")
    } else if any.is::<VideoBackChannelMessage>() {
        ("ccm", "vbcm")
    } else if any.is::<LayerRefreshRequest>() {
        ("ccm", "lrr")
    } else if any.is::<ReceiverEstimatedMaximumBitrate>() {
        ("goog-remb", "")
    } else if any.is::<TransportLayerCc>() {
        ("transport-cc", "")
    } else if any.is::<CcFeedbackReport>() {
        ("ack", "ccfb")
    } else {
        return None;
    })
}

/// RFC 4585 section 4.2 ("no feedback messages other than those listed ... MUST be used") and
/// RFC 5104 section 7.2 ("MUST NOT use other CCM messages than those indicated"): the first
/// of `packets` whose feedback type `negotiated` (the feedback of a section's negotiated
/// codecs) does not list, as its `a=rtcp-fb` type and parameter.
pub(crate) fn unnegotiated_feedback(
    packets: &[Box<dyn rtcp::Packet>],
    negotiated: &[RTCRtpCodecParameters],
) -> Option<(&'static str, &'static str)> {
    packets
        .iter()
        .filter_map(|packet| feedback_negotiating(packet.as_ref()))
        .find(|(typ, parameter)| {
            !negotiated
                .iter()
                .flat_map(|codec| &codec.rtp_codec.rtcp_feedback)
                .any(|f| {
                    f.typ.eq_ignore_ascii_case(typ)
                        && f.parameter
                            .split_whitespace()
                            .next()
                            .unwrap_or("")
                            .eq_ignore_ascii_case(parameter)
                })
        })
}

/// Computes the intersection of two RTCP feedback lists.
///
/// Returns feedback mechanisms that are supported by both lists,
/// matching on both type and parameter fields.
///
/// `trr-int` matches on the type alone and keeps the parameter of `a`: its number is each
/// endpoint's own minimum interval between regular RTCP packets (RFC 4585 section 4.2), not
/// a capability the two have to agree on, so an answer states its own.
///
/// # Parameters
///
/// * `a` - First feedback list
/// * `b` - Second feedback list
///
/// # Returns
///
/// Vector of common feedback mechanisms
/// `ccm tmmbr` of both lists, whatever their `smaxpr` (RFC 5104 section 7.1: "tmmbr
/// smaxpr=<n>", the session maximum packet rate). Section 7.2: "the highest value from offer
/// and answer SHALL be used. If the session maximum packet rate parameter is not present in an
/// offer, it SHALL NOT be included by the answerer": `b` is the remote side's list, and
/// without its `smaxpr` the result has none. `None` when the two are not both `ccm tmmbr`.
fn tmmbr_intersection(a: &RTCPFeedback, b: &RTCPFeedback) -> Option<RTCPFeedback> {
    let smaxpr = |f: &RTCPFeedback| -> Option<Option<u64>> {
        if f.typ != TYPE_RTCP_FB_CCM {
            return None;
        }
        let mut tokens = f.parameter.split_whitespace();
        if tokens.next() != Some("tmmbr") {
            return None;
        }
        Some(tokens.find_map(|t| t.strip_prefix("smaxpr=")?.parse().ok()))
    };
    let (ours, theirs) = (smaxpr(a)?, smaxpr(b)?);
    Some(RTCPFeedback {
        typ: TYPE_RTCP_FB_CCM.to_owned(),
        parameter: match theirs {
            Some(theirs) => format!("tmmbr smaxpr={}", ours.unwrap_or(0).max(theirs)),
            None => "tmmbr".to_owned(),
        },
    })
}

/// `Some` when `a` (this endpoint's) and `b` (the peer's) are both `ccm pause` lines: the
/// negotiated line (RFC 7728 section 9.1), or `None` when the peer's cannot be answered.
fn pause_intersection(a: &RTCPFeedback, b: &RTCPFeedback) -> Option<Option<RTCPFeedback>> {
    if a.typ != TYPE_RTCP_FB_CCM || b.typ != TYPE_RTCP_FB_CCM {
        return None;
    }
    let (ours, theirs) = (
        interceptor::PauseCapability::parse(&a.parameter)?,
        interceptor::PauseCapability::parse(&b.parameter),
    );
    let Some(theirs) = theirs else {
        return b
            .parameter
            .split_whitespace()
            .next()
            .is_some_and(|word| word.eq_ignore_ascii_case(interceptor::RTCP_FB_CCM_PAUSE))
            .then_some(None);
    };
    Some(
        interceptor::PauseCapability::negotiate(&ours, &theirs).map(|negotiated| RTCPFeedback {
            typ: TYPE_RTCP_FB_CCM.to_owned(),
            parameter: negotiated.parameter(),
        }),
    )
}

pub(crate) fn rtcp_feedback_intersection(
    a: &[RTCPFeedback],
    b: &[RTCPFeedback],
) -> Vec<RTCPFeedback> {
    let mut out = vec![];
    for a_feedback in a {
        for b_feeback in b {
            // RFC 7728 section 9.1: `ccm pause` is answered with the complementary `config`
            // and `nowait` only when both sides have it; a `config` the section does not
            // define removes the line.
            if let Some(pause) = pause_intersection(a_feedback, b_feeback) {
                if let Some(pause) = pause {
                    out.push(pause);
                }
                break;
            }
            if a_feedback.typ == b_feeback.typ
                && (a_feedback.parameter == b_feeback.parameter || a_feedback.typ == "trr-int")
            {
                out.push(a_feedback.clone());
                break;
            }
            // Receiver reference times, from an `a=rtcp-fb ... rrtr` line or from
            // `a=rtcp-xr:rcvr-rtt` (RFC 3611 section 5.1): the remote side's form is kept, so
            // that an answer repeats the form the offer used.
            if a_feedback.typ == interceptor::RTCP_FB_RRTR && b_feeback.typ == a_feedback.typ {
                out.push(b_feeback.clone());
                break;
            }
            if let Some(tmmbr) = tmmbr_intersection(a_feedback, b_feeback) {
                out.push(tmmbr);
                break;
            }
        }
    }

    // RFC 8888 section 6: of several congestion control feedback mechanisms "that offer
    // substantially the same semantics", the answer SHOULD include only one, and the same one
    // in a later answer to the same offer. RFC 8888 is kept and transport-wide congestion
    // control dropped, which is also what the interceptors run a stream on when a peer
    // answered both (`interceptor::negotiated_congestion_feedback`).
    //
    // RFC 8888 section 7: "If an SDP offer signals support for both RTP Congestion Control
    // Feedback Packets and the RTCP ECN Feedback Packet, the answering party SHOULD signal
    // support for one, but not both": the RFC 6679 ECN feedback (`nack ecn`) duplicates what
    // the RFC 8888 report carries per packet, and goes as well.
    let is_ccfb = |f: &RTCPFeedback| f.typ == TYPE_RTCP_FB_ACK && f.parameter == RTCP_FB_ACK_CCFB;
    if out.iter().any(is_ccfb) {
        out.retain(|f| {
            f.typ != TYPE_RTCP_FB_TRANSPORT_CC
                && !(f.typ == TYPE_RTCP_FB_NACK && f.parameter == RTCP_FB_NACK_ECN)
        });
    }

    out
}

#[cfg(test)]
mod congestion_feedback_answer_test {
    use super::*;

    fn feedback(typ: &str, parameter: &str) -> RTCPFeedback {
        RTCPFeedback {
            typ: typ.to_owned(),
            parameter: parameter.to_owned(),
        }
    }

    /// RFC 8888 section 6: offered RFC 8888 and transport-wide congestion control together,
    /// the answer keeps one of them, RFC 8888, and the same one every time.
    #[test]
    fn an_answer_keeps_one_congestion_feedback_mechanism() {
        let ours = [
            feedback("nack", ""),
            feedback("transport-cc", ""),
            feedback("ack", "ccfb"),
        ];
        let offered_both = [
            feedback("ack", "ccfb"),
            feedback("transport-cc", ""),
            feedback("nack", ""),
        ];
        let expected = vec![feedback("nack", ""), feedback("ack", "ccfb")];
        assert_eq!(expected, rtcp_feedback_intersection(&ours, &offered_both));
        assert_eq!(
            expected,
            rtcp_feedback_intersection(&ours, &offered_both),
            "a later answer to the same offer chooses the same mechanism"
        );
    }

    /// RFC 8888 section 7: offered RFC 8888 feedback and the RFC 6679 ECN feedback packet
    /// (`nack ecn`) together, the answer signals one, RFC 8888, even where the answerer
    /// registered both; plain `nack` is another matter and stays.
    #[test]
    fn an_offer_of_ccfb_and_nack_ecn_is_answered_with_ccfb_only() {
        let ours = [
            feedback("nack", ""),
            feedback("nack", "ecn"),
            feedback("ack", "ccfb"),
        ];
        let offered = [
            feedback("nack", "ecn"),
            feedback("ack", "ccfb"),
            feedback("nack", ""),
        ];
        assert_eq!(
            vec![feedback("nack", ""), feedback("ack", "ccfb")],
            rtcp_feedback_intersection(&ours, &offered)
        );
        // Without RFC 8888 in the answer, `nack ecn` is the ECN feedback and is kept.
        assert_eq!(
            vec![feedback("nack", "ecn")],
            rtcp_feedback_intersection(&ours[1..2], &offered)
        );
    }

    /// A peer that offers transport-wide congestion control alone, as browsers do, gets it.
    #[test]
    fn transport_cc_is_answered_when_rfc8888_was_not_offered() {
        let ours = [feedback("transport-cc", ""), feedback("ack", "ccfb")];
        let offered = [feedback("transport-cc", ""), feedback("nack", "")];
        assert_eq!(
            vec![feedback("transport-cc", "")],
            rtcp_feedback_intersection(&ours, &offered)
        );
    }
}

#[cfg(test)]
#[path = "rtp_codec_packetization_test.rs"]
mod rtp_codec_packetization_test;

#[cfg(test)]
#[path = "rtp_codec_flexfec_test.rs"]
mod rtp_codec_flexfec_test;

#[cfg(test)]
mod rtx_apt_test {
    use super::{
        RTCRtpCodec, RTCRtpCodecParameters, encoding_send_codec, find_rtx_payload_type,
        is_rtx_mime_type, parse_rtx_apt, parse_rtx_time,
    };

    fn media(mime_type: &str, payload_type: u8) -> RTCRtpCodecParameters {
        RTCRtpCodecParameters {
            rtp_codec: RTCRtpCodec {
                mime_type: mime_type.to_owned(),
                clock_rate: 90000,
                ..Default::default()
            },
            payload_type,
        }
    }

    #[test]
    fn an_encoding_without_a_codec_is_sent_with_the_first_media_codec() {
        // Repair formats only accompany a media codec: one listed first is passed over.
        let negotiated = vec![
            rtx(97, "apt=96"),
            media("video/red", 63),
            media("video/ulpfec", 116),
            media("video/flexfec-03", 118),
            media("video/VP8", 96),
            media("video/H264", 102),
        ];
        let chosen = encoding_send_codec(&RTCRtpCodec::default(), &negotiated);
        assert_eq!(chosen.map(|c| c.payload_type), Some(96));
        assert_eq!(
            encoding_send_codec(&RTCRtpCodec::default(), &[rtx(97, "apt=96")]),
            None,
            "nothing to send with"
        );
    }

    #[test]
    fn an_encoding_naming_a_codec_is_sent_with_that_codec_or_not_at_all() {
        let negotiated = vec![media("video/VP8", 96), media("video/H264", 102)];
        let h264 = RTCRtpCodec {
            mime_type: "video/H264".to_owned(),
            clock_rate: 90000,
            ..Default::default()
        };
        assert_eq!(
            encoding_send_codec(&h264, &negotiated).map(|c| c.payload_type),
            Some(102)
        );
        let vp9 = RTCRtpCodec {
            mime_type: "video/VP9".to_owned(),
            clock_rate: 90000,
            ..Default::default()
        };
        assert_eq!(
            encoding_send_codec(&vp9, &negotiated),
            None,
            "a codec that was not negotiated is not replaced by another"
        );
    }

    fn rtx(payload_type: u8, fmtp: &str) -> RTCRtpCodecParameters {
        RTCRtpCodecParameters {
            rtp_codec: RTCRtpCodec {
                mime_type: "video/rtx".to_owned(),
                clock_rate: 90000,
                channels: 0,
                sdp_fmtp_line: fmtp.to_owned(),
                rtcp_feedback: vec![],
            },
            payload_type,
        }
    }

    #[test]
    fn find_rtx_payload_type_tolerates_extra_apt_params() {
        // A remote may append rtx-time to the apt fmtp (RFC 4588 §8.1); the
        // association must still succeed rather than dropping RTX from the answer.
        let haystack = vec![rtx(97, "apt=96;rtx-time=3000"), rtx(99, "apt=98")];
        assert_eq!(find_rtx_payload_type(96, &haystack), Some(97));
        assert_eq!(find_rtx_payload_type(98, &haystack), Some(99));
        assert_eq!(find_rtx_payload_type(100, &haystack), None);
    }

    #[test]
    fn parses_plain_apt() {
        assert_eq!(parse_rtx_apt("apt=96"), Some(96));
        assert_eq!(parse_rtx_apt("apt=127"), Some(127));
        assert_eq!(parse_rtx_apt("apt=0"), Some(0));
    }

    #[test]
    fn parses_apt_with_extra_params() {
        // RFC 4588 §8.1 allows an optional rtx-time parameter alongside apt.
        assert_eq!(parse_rtx_apt("apt=96;rtx-time=3000"), Some(96));
        assert_eq!(parse_rtx_apt("rtx-time=3000;apt=102"), Some(102));
        assert_eq!(parse_rtx_apt("apt=98 ; rtx-time=1000"), Some(98));
        let ms = std::time::Duration::from_millis;
        assert_eq!(parse_rtx_time("apt=96;rtx-time=3000"), Some(ms(3000)));
        assert_eq!(parse_rtx_time("rtx-time=250; apt=102"), Some(ms(250)));
        assert_eq!(parse_rtx_time("apt=96"), None);
        assert_eq!(parse_rtx_time("apt=96;rtx-time=soon"), None);
        assert!(is_rtx_mime_type("video/rtx") && is_rtx_mime_type("audio/RTX"));
        assert!(!is_rtx_mime_type("video/VP8"));
    }

    #[test]
    fn returns_none_without_apt() {
        assert_eq!(parse_rtx_apt(""), None);
        assert_eq!(parse_rtx_apt("profile-id=0"), None);
        assert_eq!(parse_rtx_apt("apt="), None);
        assert_eq!(parse_rtx_apt("apt=notanumber"), None);
        // Out of the u8 payload-type range.
        assert_eq!(parse_rtx_apt("apt=300"), None);
    }

    fn tmmbr(parameter: &str) -> Vec<super::RTCPFeedback> {
        vec![super::RTCPFeedback {
            typ: super::TYPE_RTCP_FB_CCM.to_owned(),
            parameter: parameter.to_owned(),
        }]
    }

    /// RFC 5104 section 7.2: "the highest value from offer and answer SHALL be used", and
    /// section 7.1: without `smaxpr` the rate "defaults to infinity". This endpoint's offered
    /// `smaxpr` against a remote answer: a higher answered value wins, a lower one loses, and
    /// an answer without one leaves the session without a limit (infinity is the highest).
    #[test]
    fn the_session_maximum_packet_rate_is_the_highest_of_offer_and_answer() {
        let ours = tmmbr("tmmbr smaxpr=120");
        assert_eq!(
            super::rtcp_feedback_intersection(&ours, &tmmbr("tmmbr smaxpr=200")),
            tmmbr("tmmbr smaxpr=200")
        );
        assert_eq!(
            super::rtcp_feedback_intersection(&ours, &tmmbr("tmmbr smaxpr=60")),
            tmmbr("tmmbr smaxpr=120")
        );
        assert_eq!(
            super::rtcp_feedback_intersection(&ours, &tmmbr("tmmbr")),
            tmmbr("tmmbr")
        );
        // An answerer without a limit of its own keeps the offered one: the highest of the
        // two is the offer's, which it states (section 7.2 forbids only adding one).
        assert_eq!(
            super::rtcp_feedback_intersection(&tmmbr("tmmbr"), &tmmbr("tmmbr smaxpr=120")),
            tmmbr("tmmbr smaxpr=120")
        );
    }

    /// RFC 3611 section 5.1: `rcvr-rtt=<mode>[:<max size>]` reaches the stream as the remote
    /// side signalled it, mode and maximum DLRR size included, whatever form this endpoint
    /// registered, so that the RTCP session keeps its DLRR blocks within the peer's maximum.
    #[test]
    fn the_remote_rcvr_rtt_mode_and_maximum_are_negotiated() {
        let rrtr = |parameter: &str| {
            vec![super::RTCPFeedback {
                typ: interceptor::RTCP_FB_RRTR.to_owned(),
                parameter: parameter.to_owned(),
            }]
        };
        assert_eq!(
            super::rtcp_feedback_intersection(&rrtr("rcvr-rtt=all"), &rrtr("rcvr-rtt=sender:64")),
            rrtr("rcvr-rtt=sender:64")
        );
    }
}

#[cfg(test)]
mod codec_dictionary_match_test {
    use super::{
        RTCRtpCodec, RTCRtpCodecParameters, codec_dictionary_match_with, encoding_send_codec,
    };

    fn h264(fmtp: &str) -> RTCRtpCodec {
        RTCRtpCodec {
            mime_type: "video/H264".to_owned(),
            clock_rate: 90000,
            channels: 0,
            sdp_fmtp_line: fmtp.to_owned(),
            rtcp_feedback: vec![],
        }
    }

    /// W3C webrtc 5.4 "codec dictionary match": an `sdpFmtpLine` on one side only is no
    /// match; lines that are not key-value are compared as strings; symmetrical parameters
    /// (H.264 profile, packetization mode) must be equal; the asymmetrical ones (the H.264
    /// level) too unless `ignoreAsymmetricalParameters`; a parameter left out is its
    /// inferred default.
    #[test]
    fn the_codec_dictionary_match_follows_the_w3c_algorithm() {
        let base = "level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f";
        let cases = [
            (base, base, true, true),
            // Order and case of the parameter names do not matter.
            (
                base,
                "PROFILE-LEVEL-ID=42e01f;packetization-mode=1;level-asymmetry-allowed=1",
                true,
                true,
            ),
            // Another level: asymmetrical.
            (
                base,
                "level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e034",
                false,
                true,
            ),
            // Another packetization mode: symmetrical.
            (
                base,
                "level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=42e01f",
                false,
                false,
            ),
            // Another profile: symmetrical.
            (
                base,
                "level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=640c1f",
                false,
                false,
            ),
            // An inferred default: packetization-mode=0 left out.
            (
                "packetization-mode=0;profile-level-id=42e01f",
                "profile-level-id=42e01f",
                true,
                true,
            ),
            // On one side only.
            (base, "", false, false),
        ];
        for (first, second, strict, ignoring) in cases {
            assert_eq!(
                codec_dictionary_match_with(&h264(first), &h264(second), false),
                strict,
                "{first} / {second}"
            );
            assert_eq!(
                codec_dictionary_match_with(&h264(first), &h264(second), true),
                ignoring,
                "{first} / {second}, ignoring asymmetrical parameters"
            );
        }
        let red = |fmtp: &str| RTCRtpCodec {
            mime_type: "audio/red".to_owned(),
            clock_rate: 48000,
            channels: 2,
            sdp_fmtp_line: fmtp.to_owned(),
            rtcp_feedback: vec![],
        };
        assert!(codec_dictionary_match_with(
            &red("111/111"),
            &red("111/111"),
            false
        ));
        assert!(!codec_dictionary_match_with(
            &red("111/111"),
            &red("111/111/111"),
            true
        ));
    }

    /// W3C webrtc 4.4.1.6: an encoding's codec is the negotiated codec it matches with
    /// `ignoreAsymmetricalParameters` true. A codec of the same MIME type with another
    /// profile is no match (the mime-type-only fallback is gone); another level is.
    #[test]
    fn an_encoding_codec_matches_a_negotiated_one_by_the_dictionary_match() {
        let negotiated = vec![RTCRtpCodecParameters {
            rtp_codec: h264(
                "level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f",
            ),
            payload_type: 102,
        }];
        let other_level =
            h264("level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e034");
        assert_eq!(
            encoding_send_codec(&other_level, &negotiated).map(|c| c.payload_type),
            Some(102)
        );
        let other_profile =
            h264("level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=640c1f");
        assert_eq!(encoding_send_codec(&other_profile, &negotiated), None);
    }
}