rtc 0.9.0

Sans-I/O WebRTC implementation in Rust
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
//! Media engine configuration for codecs and RTP extensions.
//!
//! The media engine manages codec registration, RTP header extensions, and media
//! capabilities negotiation for peer connections. It defines what codecs and features
//! are available for encoding/decoding media streams.
//!
//! # Overview
//!
//! - **Codec Registration** - Define supported audio/video codecs
//! - **Header Extensions** - Configure RTP header extensions
//! - **Feedback Mechanisms** - Register RTCP feedback types
//! - **Negotiation** - Codec and extension negotiation with remote peers
//!
//! # Examples
//!
//! ## Using Default Codecs
//!
//! ```
//! use rtc::peer_connection::configuration::media_engine::MediaEngine;
//!
//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let mut media_engine = MediaEngine::default();
//!
//! // Register standard WebRTC codecs
//! media_engine.register_default_codecs()?;
//! // Now supports: Opus, G722, PCMU, PCMA, VP8, VP9, H264, AV1
//! # Ok(())
//! # }
//! ```
//!
//! ## Registering Custom Codec
//!
//! ```
//! use rtc::peer_connection::configuration::media_engine::{MediaEngine, MIME_TYPE_OPUS};
//! use rtc::rtp_transceiver::rtp_sender::{RTCRtpCodec, RtpCodecKind, RTCRtpCodecParameters};
//!
//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let mut media_engine = MediaEngine::default();
//!
//! // Register Opus with custom parameters
//! let opus_codec = RTCRtpCodecParameters {
//!     rtp_codec: RTCRtpCodec {
//!         mime_type: MIME_TYPE_OPUS.to_owned(),
//!         clock_rate: 48000,
//!         channels: 2,
//!         sdp_fmtp_line: "minptime=10;useinbandfec=1;stereo=1".to_owned(),
//!         rtcp_feedback: vec![],
//!     },
//!     payload_type: 111,
//!     ..Default::default()
//! };
//!
//! media_engine.register_codec(opus_codec, RtpCodecKind::Audio)?;
//! # Ok(())
//! # }
//! ```
//!
//! ## Registering RTP Header Extension
//!
//! ```
//! use rtc::peer_connection::configuration::media_engine::MediaEngine;
//! use rtc::rtp_transceiver::rtp_sender::{RtpCodecKind, RTCRtpHeaderExtensionCapability};
//! use rtc::rtp_transceiver::RTCRtpTransceiverDirection;
//!
//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let mut media_engine = MediaEngine::default();
//!
//! // Register audio level extension
//! media_engine.register_header_extension(
//!     RTCRtpHeaderExtensionCapability {
//!         uri: "urn:ietf:params:rtp-hdrext:ssrc-audio-level".to_string(),
//!     },
//!     RtpCodecKind::Audio,
//!     Some(RTCRtpTransceiverDirection::Sendrecv),
//! )?;
//! # Ok(())
//! # }
//! ```

//TODO:#[cfg(test)]
//mod media_engine_test;

use crate::peer_connection::sdp::{
    codecs_from_media_description, rtp_extensions_from_media_description,
};
use crate::rtp_transceiver::direction::RTCRtpTransceiverDirection;
use crate::rtp_transceiver::fmtp;
use crate::rtp_transceiver::rtp_sender::rtp_codec::{
    CodecMatch, RTCRtpCodec, RtpCodecKind, codec_parameters_fuzzy_search,
    rtcp_feedback_intersection,
};
use crate::rtp_transceiver::rtp_sender::rtp_codec_parameters::RTCRtpCodecParameters;
use crate::rtp_transceiver::rtp_sender::rtp_header_extension_capability::RTCRtpHeaderExtensionCapability;
use crate::rtp_transceiver::rtp_sender::rtp_header_extension_parameters::RTCRtpHeaderExtensionParameters;
use crate::rtp_transceiver::rtp_sender::rtp_parameters::RTCRtpParameters;
use crate::rtp_transceiver::{PayloadType, rtp_sender::rtcp_parameters::RTCPFeedback};
use sdp::MediaDescription;
use sdp::description::session::SessionDescription;
use shared::error::{Error, Result};
use std::collections::HashMap;
use std::ops::Range;
use unicase::UniCase;

/// H.264 video codec MIME type.
///
/// Used for baseline, main, and high profile H.264 video encoding.
/// Note: MIME type matching is case-insensitive.
pub const MIME_TYPE_H264: &str = "video/H264";

/// H.265/HEVC video codec MIME type.
///
/// Used for High Efficiency Video Coding (HEVC/H.265) video encoding.
/// Note: MIME type matching is case-insensitive.
pub const MIME_TYPE_HEVC: &str = "video/H265";

/// Opus audio codec MIME type.
///
/// Modern, versatile audio codec with excellent quality and low latency.
/// Recommended for most WebRTC applications.
/// Note: MIME type matching is case-insensitive.
pub const MIME_TYPE_OPUS: &str = "audio/opus";

/// VP8 video codec MIME type.
///
/// Open-source video codec, widely supported across all browsers.
/// Good fallback option for video conferencing.
/// Note: MIME type matching is case-insensitive.
pub const MIME_TYPE_VP8: &str = "video/VP8";

/// VP9 video codec MIME type.
///
/// Successor to VP8 with better compression efficiency.
/// Supported by modern browsers.
/// Note: MIME type matching is case-insensitive.
pub const MIME_TYPE_VP9: &str = "video/VP9";

/// AV1 video codec MIME type.
///
/// Next-generation open video codec with excellent compression.
/// Increasing browser support.
/// Note: MIME type matching is case-insensitive.
pub const MIME_TYPE_AV1: &str = "video/AV1";

/// G.722 audio codec MIME type.
///
/// Wideband audio codec (50-7000 Hz).
/// Note: MIME type matching is case-insensitive.
pub const MIME_TYPE_G722: &str = "audio/G722";

/// PCMU (G.711 μ-law) audio codec MIME type.
///
/// Standard telephony codec, primarily used in North America.
/// Note: MIME type matching is case-insensitive.
pub const MIME_TYPE_PCMU: &str = "audio/PCMU";

/// PCMA (G.711 A-law) audio codec MIME type.
///
/// Standard telephony codec, primarily used in Europe.
/// Note: MIME type matching is case-insensitive.
pub const MIME_TYPE_PCMA: &str = "audio/PCMA";

/// RTX (Retransmission) MIME type.
///
/// Used for RTP retransmission to improve reliability.
/// Note: MIME type matching is case-insensitive.
pub const MIME_TYPE_RTX: &str = "video/rtx";

/// FlexFEC forward error correction MIME type.
///
/// Note: MIME type matching is case-insensitive.
pub const MIME_TYPE_FLEX_FEC: &str = "video/flexfec";

/// FlexFEC-03 forward error correction MIME type.
///
/// Note: MIME type matching is case-insensitive.
pub const MIME_TYPE_FLEX_FEC03: &str = "video/flexfec-03";

/// ULP FEC (Uneven Level Protection Forward Error Correction) MIME type.
///
/// Note: MIME type matching is case-insensitive.
pub const MIME_TYPE_ULP_FEC: &str = "video/ulpfec";

/// Telephone-event MIME type for DTMF tones.
///
/// Used for transmitting DTMF (touch-tone) signals.
/// Note: MIME type matching is case-insensitive.
pub const MIME_TYPE_TELEPHONE_EVENT: &str = "audio/telephone-event";

const VALID_EXT_IDS: Range<u16> = 1..15;

#[derive(Default, Clone)]
pub(crate) struct MediaEngineHeaderExtension {
    pub(crate) uri: String,
    pub(crate) is_audio: bool,
    pub(crate) is_video: bool,
    pub(crate) allowed_direction: Option<RTCRtpTransceiverDirection>,
}

impl MediaEngineHeaderExtension {
    pub fn is_matching_direction(&self, dir: RTCRtpTransceiverDirection) -> bool {
        if let Some(allowed_direction) = self.allowed_direction {
            use RTCRtpTransceiverDirection::*;
            allowed_direction == Inactive && dir == Inactive
                || allowed_direction.has_send() && dir.has_send()
                || allowed_direction.has_recv() && dir.has_recv()
        } else {
            // None means all directions matches.
            true
        }
    }
}

/// Media engine managing codecs and RTP capabilities for peer connections.
///
/// MediaEngine defines which audio/video codecs are supported and how they're
/// configured. Each peer connection should have its own MediaEngine instance
/// as codec negotiation state is tracked per-connection.
///
/// # Thread Safety
///
/// ⚠️ MediaEngine is **not** safe for concurrent use during configuration.
/// Configure it completely before using in a peer connection.
///
/// # Examples
///
/// ## Default Configuration
///
/// ```
/// use rtc::peer_connection::RTCPeerConnectionBuilder;
/// use rtc::peer_connection::configuration::media_engine::MediaEngine;
///
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let mut media_engine = MediaEngine::default();
/// media_engine.register_default_codecs()?;
///
/// let pc = RTCPeerConnectionBuilder::new()
///     .with_media_engine(media_engine)
///     .build()?;
/// # Ok(())
/// # }
/// ```
///
/// ## Custom Codec Configuration
///
/// ```
/// use rtc::peer_connection::configuration::media_engine::{MediaEngine, MIME_TYPE_OPUS, MIME_TYPE_VP8};
/// use rtc::rtp_transceiver::rtp_sender::{RTCRtpCodec, RtpCodecKind, RTCRtpCodecParameters};
///
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let mut media_engine = MediaEngine::default();
///
/// // Register only specific codecs for minimal overhead
/// media_engine.register_codec(
///     RTCRtpCodecParameters {
///         rtp_codec: RTCRtpCodec {
///             mime_type: MIME_TYPE_OPUS.to_owned(),
///             clock_rate: 48000,
///             channels: 2,
///             sdp_fmtp_line: "minptime=10;useinbandfec=1".to_owned(),
///             rtcp_feedback: vec![],
///         },
///         payload_type: 111,
///         ..Default::default()
///     },
///     RtpCodecKind::Audio,
/// )?;
///
/// media_engine.register_codec(
///     RTCRtpCodecParameters {
///         rtp_codec: RTCRtpCodec {
///             mime_type: MIME_TYPE_VP8.to_owned(),
///             clock_rate: 90000,
///             channels: 0,
///             sdp_fmtp_line: "".to_owned(),
///             rtcp_feedback: vec![],
///         },
///         payload_type: 96,
///         ..Default::default()
///     },
///     RtpCodecKind::Video,
/// )?;
/// # Ok(())
/// # }
/// ```
#[derive(Default, Clone)]
pub struct MediaEngine {
    // If we have attempted to negotiate a codec type yet.
    pub(crate) negotiated_video: bool,
    pub(crate) negotiated_audio: bool,
    pub(crate) negotiate_multi_codecs: bool,

    pub(crate) video_codecs: Vec<RTCRtpCodecParameters>,
    pub(crate) audio_codecs: Vec<RTCRtpCodecParameters>,
    pub(crate) negotiated_video_codecs: Vec<RTCRtpCodecParameters>,
    pub(crate) negotiated_audio_codecs: Vec<RTCRtpCodecParameters>,

    pub(crate) header_extensions: Vec<MediaEngineHeaderExtension>,
    pub(crate) negotiated_header_extensions: HashMap<u16, MediaEngineHeaderExtension>,
}

impl MediaEngine {
    /// Registers standard WebRTC codecs for audio and video.
    ///
    /// This convenience method registers all codecs commonly supported by WebRTC implementations:
    ///
    /// **Audio Codecs:**
    /// - Opus (48kHz, stereo, with FEC)
    /// - G.722 (8kHz wideband)
    /// - PCMU/G.711 μ-law (8kHz)
    /// - PCMA/G.711 A-law (8kHz)
    ///
    /// **Video Codecs:**
    /// - VP8 with RTCP feedback
    /// - VP9 (multiple profiles) with RTCP feedback
    /// - H.264 (multiple profiles/packetization modes) with RTCP feedback
    /// - AV1 with RTCP feedback  
    /// - H.265/HEVC with RTCP feedback
    /// - ULP FEC (forward error correction)
    ///
    /// # Thread Safety
    ///
    /// ⚠️ Not safe for concurrent use. Call before using MediaEngine in a peer connection.
    ///
    /// # Examples
    ///
    /// ```
    /// use rtc::peer_connection::configuration::media_engine::MediaEngine;
    ///
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut media_engine = MediaEngine::default();
    /// media_engine.register_default_codecs()?;
    /// // Media engine now supports all standard WebRTC codecs
    /// # Ok(())
    /// # }
    /// ```
    pub fn register_default_codecs(&mut self) -> Result<()> {
        // Default Audio Codecs
        for codec in [
            RTCRtpCodecParameters {
                rtp_codec: RTCRtpCodec {
                    mime_type: MIME_TYPE_OPUS.to_owned(),
                    clock_rate: 48000,
                    channels: 2,
                    sdp_fmtp_line: "minptime=10;useinbandfec=1".to_owned(),
                    rtcp_feedback: vec![],
                },
                payload_type: 111,
            },
            RTCRtpCodecParameters {
                rtp_codec: RTCRtpCodec {
                    mime_type: MIME_TYPE_G722.to_owned(),
                    clock_rate: 8000,
                    channels: 0,
                    sdp_fmtp_line: "".to_owned(),
                    rtcp_feedback: vec![],
                },
                payload_type: 9,
            },
            RTCRtpCodecParameters {
                rtp_codec: RTCRtpCodec {
                    mime_type: MIME_TYPE_PCMU.to_owned(),
                    clock_rate: 8000,
                    channels: 0,
                    sdp_fmtp_line: "".to_owned(),
                    rtcp_feedback: vec![],
                },
                payload_type: 0,
            },
            RTCRtpCodecParameters {
                rtp_codec: RTCRtpCodec {
                    mime_type: MIME_TYPE_PCMA.to_owned(),
                    clock_rate: 8000,
                    channels: 0,
                    sdp_fmtp_line: "".to_owned(),
                    rtcp_feedback: vec![],
                },
                payload_type: 8,
            },
        ] {
            self.register_codec(codec, RtpCodecKind::Audio)?;
        }

        let video_rtcp_feedback = vec![
            RTCPFeedback {
                typ: "goog-remb".to_owned(),
                parameter: "".to_owned(),
            },
            RTCPFeedback {
                typ: "ccm".to_owned(),
                parameter: "fir".to_owned(),
            },
            RTCPFeedback {
                typ: "nack".to_owned(),
                parameter: "".to_owned(),
            },
            RTCPFeedback {
                typ: "nack".to_owned(),
                parameter: "pli".to_owned(),
            },
        ];
        for codec in vec![
            RTCRtpCodecParameters {
                rtp_codec: RTCRtpCodec {
                    mime_type: MIME_TYPE_VP8.to_owned(),
                    clock_rate: 90000,
                    channels: 0,
                    sdp_fmtp_line: "".to_owned(),
                    rtcp_feedback: video_rtcp_feedback.clone(),
                },
                payload_type: 96,
            },
            RTCRtpCodecParameters {
                rtp_codec: RTCRtpCodec {
                    mime_type: MIME_TYPE_VP9.to_owned(),
                    clock_rate: 90000,
                    channels: 0,
                    sdp_fmtp_line: "profile-id=0".to_owned(),
                    rtcp_feedback: video_rtcp_feedback.clone(),
                },
                payload_type: 98,
            },
            RTCRtpCodecParameters {
                rtp_codec: RTCRtpCodec {
                    mime_type: MIME_TYPE_VP9.to_owned(),
                    clock_rate: 90000,
                    channels: 0,
                    sdp_fmtp_line: "profile-id=1".to_owned(),
                    rtcp_feedback: video_rtcp_feedback.clone(),
                },
                payload_type: 100,
            },
            RTCRtpCodecParameters {
                rtp_codec: RTCRtpCodec {
                    mime_type: MIME_TYPE_H264.to_owned(),
                    clock_rate: 90000,
                    channels: 0,
                    sdp_fmtp_line:
                        "level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42001f"
                            .to_owned(),
                    rtcp_feedback: video_rtcp_feedback.clone(),
                },
                payload_type: 102,
            },
            RTCRtpCodecParameters {
                rtp_codec: RTCRtpCodec {
                    mime_type: MIME_TYPE_H264.to_owned(),
                    clock_rate: 90000,
                    channels: 0,
                    sdp_fmtp_line:
                        "level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=42001f"
                            .to_owned(),
                    rtcp_feedback: video_rtcp_feedback.clone(),
                },
                payload_type: 127,
            },
            RTCRtpCodecParameters {
                rtp_codec: RTCRtpCodec {
                    mime_type: MIME_TYPE_H264.to_owned(),
                    clock_rate: 90000,
                    channels: 0,
                    sdp_fmtp_line:
                        "level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f"
                            .to_owned(),
                    rtcp_feedback: video_rtcp_feedback.clone(),
                },
                payload_type: 125,
            },
            RTCRtpCodecParameters {
                rtp_codec: RTCRtpCodec {
                    mime_type: MIME_TYPE_H264.to_owned(),
                    clock_rate: 90000,
                    channels: 0,
                    sdp_fmtp_line:
                        "level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=42e01f"
                            .to_owned(),
                    rtcp_feedback: video_rtcp_feedback.clone(),
                },
                payload_type: 108,
            },
            RTCRtpCodecParameters {
                rtp_codec: RTCRtpCodec {
                    mime_type: MIME_TYPE_H264.to_owned(),
                    clock_rate: 90000,
                    channels: 0,
                    sdp_fmtp_line:
                        "level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=42001f"
                            .to_owned(),
                    rtcp_feedback: video_rtcp_feedback.clone(),
                },
                payload_type: 127,
            },
            RTCRtpCodecParameters {
                rtp_codec: RTCRtpCodec {
                    mime_type: MIME_TYPE_H264.to_owned(),
                    clock_rate: 90000,
                    channels: 0,
                    sdp_fmtp_line:
                        "level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=640032"
                            .to_owned(),
                    rtcp_feedback: video_rtcp_feedback.clone(),
                },
                payload_type: 123,
            },
            RTCRtpCodecParameters {
                rtp_codec: RTCRtpCodec {
                    mime_type: MIME_TYPE_AV1.to_owned(),
                    clock_rate: 90000,
                    channels: 0,
                    sdp_fmtp_line: "profile-id=0".to_owned(),
                    rtcp_feedback: video_rtcp_feedback.clone(),
                },
                payload_type: 41,
            },
            RTCRtpCodecParameters {
                rtp_codec: RTCRtpCodec {
                    mime_type: MIME_TYPE_HEVC.to_owned(),
                    clock_rate: 90000,
                    channels: 0,
                    sdp_fmtp_line: "".to_owned(),
                    rtcp_feedback: video_rtcp_feedback,
                },
                payload_type: 126,
            },
            RTCRtpCodecParameters {
                rtp_codec: RTCRtpCodec {
                    mime_type: "video/ulpfec".to_owned(),
                    clock_rate: 90000,
                    channels: 0,
                    sdp_fmtp_line: "".to_owned(),
                    rtcp_feedback: vec![],
                },
                payload_type: 116,
            },
        ] {
            self.register_codec(codec, RtpCodecKind::Video)?;
        }

        Ok(())
    }

    /// add_codec will append codec if it not exists
    fn add_codec(codecs: &mut Vec<RTCRtpCodecParameters>, codec: RTCRtpCodecParameters) {
        for c in codecs.iter() {
            if c.rtp_codec.mime_type == codec.rtp_codec.mime_type
                && c.payload_type == codec.payload_type
            {
                return;
            }
        }
        codecs.push(codec);
    }

    /// Registers a custom codec for use in this peer connection.
    ///
    /// Adds a codec to the list of supported codecs. During SDP negotiation, only
    /// codecs registered here will be offered/accepted.
    ///
    /// # Parameters
    ///
    /// * `codec` - The codec parameters including MIME type, clock rate, and payload type
    /// * `typ` - Whether this is an audio or video codec
    ///
    /// # Thread Safety
    ///
    /// ⚠️ Not safe for concurrent use. Register all codecs before using in a peer connection.
    ///
    /// # Examples
    ///
    /// ```
    /// use rtc::peer_connection::configuration::media_engine::{MediaEngine, MIME_TYPE_OPUS};
    /// use rtc::rtp_transceiver::rtp_sender::{RTCRtpCodec, RtpCodecKind, RTCRtpCodecParameters};
    ///
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut media_engine = MediaEngine::default();
    ///
    /// // Register Opus with custom fmtp parameters
    /// media_engine.register_codec(
    ///     RTCRtpCodecParameters {
    ///         rtp_codec: RTCRtpCodec {
    ///             mime_type: MIME_TYPE_OPUS.to_owned(),
    ///             clock_rate: 48000,
    ///             channels: 2,
    ///             sdp_fmtp_line: "minptime=10;useinbandfec=1;stereo=1".to_owned(),
    ///             rtcp_feedback: vec![],
    ///         },
    ///         payload_type: 111,
    ///         ..Default::default()
    ///     },
    ///     RtpCodecKind::Audio,
    /// )?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn register_codec(
        &mut self,
        codec: RTCRtpCodecParameters,
        typ: RtpCodecKind,
    ) -> Result<()> {
        match typ {
            RtpCodecKind::Audio => {
                MediaEngine::add_codec(&mut self.audio_codecs, codec);
                Ok(())
            }
            RtpCodecKind::Video => {
                MediaEngine::add_codec(&mut self.video_codecs, codec);
                Ok(())
            }
            _ => Err(Error::ErrUnknownType),
        }
    }

    /// Adds a header extension to the MediaEngine
    /// To determine the negotiated value use [`MediaEngine::get_header_extension_id`] after signaling is complete.
    ///
    /// The `allowed_direction` controls for which transceiver directions the extension matches. If
    /// set to `None` it matches all directions. The `SendRecv` direction would match all transceiver
    /// directions apart from `Inactive`. Inactive only matches inactive.
    pub fn register_header_extension(
        &mut self,
        extension: RTCRtpHeaderExtensionCapability,
        typ: RtpCodecKind,
        allowed_direction: Option<RTCRtpTransceiverDirection>,
    ) -> Result<()> {
        if let Some(direction) = &allowed_direction
            && (direction == &RTCRtpTransceiverDirection::Unspecified
                || direction == &RTCRtpTransceiverDirection::Inactive)
        {
            return Err(Error::ErrRegisterHeaderExtensionInvalidDirection);
        }

        let ext = {
            match self
                .header_extensions
                .iter_mut()
                .find(|ext| ext.uri == extension.uri)
            {
                Some(ext) => ext,
                None => {
                    // We have registered too many extensions
                    if self.header_extensions.len() > VALID_EXT_IDS.end as usize {
                        return Err(Error::ErrRegisterHeaderExtensionNoFreeID);
                    }
                    self.header_extensions
                        .push(MediaEngineHeaderExtension::default());

                    // Unwrap is fine because we just pushed
                    self.header_extensions.last_mut().unwrap()
                }
            }
        };

        if typ == RtpCodecKind::Audio {
            ext.is_audio = true;
        } else if typ == RtpCodecKind::Video {
            ext.is_video = true;
        }

        ext.uri = extension.uri;
        ext.allowed_direction = allowed_direction;

        Ok(())
    }

    /// register_feedback adds feedback mechanism to already registered codecs.
    pub fn register_feedback(&mut self, feedback: RTCPFeedback, typ: RtpCodecKind) {
        match typ {
            RtpCodecKind::Video => {
                for v in &mut self.video_codecs {
                    v.rtp_codec.rtcp_feedback.push(feedback.clone());
                }
            }
            RtpCodecKind::Audio => {
                for a in &mut self.audio_codecs {
                    a.rtp_codec.rtcp_feedback.push(feedback.clone());
                }
            }
            _ => {}
        }
    }

    /// get_header_extension_id returns the negotiated ID for a header extension.
    /// If the Header Extension isn't enabled ok will be false
    pub fn get_header_extension_id(
        &self,
        extension: RTCRtpHeaderExtensionCapability,
    ) -> (u16, bool, bool) {
        if self.negotiated_header_extensions.is_empty() {
            return (0, false, false);
        }

        for (id, h) in &self.negotiated_header_extensions {
            if extension.uri == h.uri {
                return (*id, h.is_audio, h.is_video);
            }
        }

        (0, false, false)
    }

    /// clone_to copies any user modifiable state of the MediaEngine
    /// all internal state is reset
    pub(crate) fn clone_to(&self) -> Self {
        MediaEngine {
            video_codecs: self.video_codecs.clone(),
            audio_codecs: self.audio_codecs.clone(),
            header_extensions: self.header_extensions.clone(),
            ..Default::default()
        }
    }

    /// set_multi_codec_negotiation enables or disables the negotiation of multiple codecs.
    pub(crate) fn set_multi_codec_negotiation(&mut self, negotiate_multi_codecs: bool) {
        self.negotiate_multi_codecs = negotiate_multi_codecs;
    }

    /// multi_codec_negotiation returns the current state of the negotiation of multiple codecs.
    pub(crate) fn multi_codec_negotiation(&self) -> bool {
        self.negotiate_multi_codecs
    }

    pub(crate) fn get_codec_by_payload(
        &self,
        payload_type: PayloadType,
    ) -> Result<(RTCRtpCodecParameters, RtpCodecKind)> {
        if self.negotiated_video {
            for codec in &self.negotiated_video_codecs {
                if codec.payload_type == payload_type {
                    return Ok((codec.clone(), RtpCodecKind::Video));
                }
            }
        }
        if self.negotiated_audio {
            for codec in &self.negotiated_audio_codecs {
                if codec.payload_type == payload_type {
                    return Ok((codec.clone(), RtpCodecKind::Audio));
                }
            }
        }
        if !self.negotiated_video {
            for codec in &self.video_codecs {
                if codec.payload_type == payload_type {
                    return Ok((codec.clone(), RtpCodecKind::Video));
                }
            }
        }
        if !self.negotiated_audio {
            for codec in &self.audio_codecs {
                if codec.payload_type == payload_type {
                    return Ok((codec.clone(), RtpCodecKind::Audio));
                }
            }
        }

        Err(Error::ErrCodecNotFound)
    }

    /// Look up a codec and enable if it exists
    pub(crate) fn match_remote_codec(
        &self,
        remote_codec: &RTCRtpCodecParameters,
        typ: RtpCodecKind,
        exact_matches: &[RTCRtpCodecParameters],
        partial_matches: &[RTCRtpCodecParameters],
    ) -> Result<(RTCRtpCodecParameters, CodecMatch)> {
        let codecs = if typ == RtpCodecKind::Audio {
            &self.audio_codecs
        } else {
            &self.video_codecs
        };

        let remote_fmtp = fmtp::parse(
            &remote_codec.rtp_codec.mime_type,
            remote_codec.rtp_codec.sdp_fmtp_line.as_str(),
        );
        if let Some(apt) = remote_fmtp.parameter("apt") {
            let payload_type = apt.parse::<u8>()?;

            let mut apt_match = CodecMatch::None;
            let mut apt_codec = None;
            for codec in exact_matches {
                if codec.payload_type == payload_type {
                    apt_match = CodecMatch::Exact;
                    apt_codec = Some(codec);
                    break;
                }
            }

            if apt_match == CodecMatch::None {
                for codec in partial_matches {
                    if codec.payload_type == payload_type {
                        apt_match = CodecMatch::Partial;
                        apt_codec = Some(codec);
                        break;
                    }
                }
            }

            if apt_match == CodecMatch::None {
                return Ok((RTCRtpCodecParameters::default(), CodecMatch::None));
                // not an error, we just ignore this codec we don't support
            }

            // replace the apt value with the original codec's payload type
            let mut to_match_codec = remote_codec.clone();
            if let Some(apt_codec) = apt_codec {
                let (apt_matched, mt) = codec_parameters_fuzzy_search(&apt_codec.rtp_codec, codecs);
                if mt == apt_match {
                    to_match_codec.rtp_codec.sdp_fmtp_line =
                        to_match_codec.rtp_codec.sdp_fmtp_line.replacen(
                            &format!("apt={payload_type}"),
                            &format!("apt={}", apt_matched.payload_type),
                            1,
                        );
                }
            }

            // if apt's media codec is partial match, then apt codec must be partial match too
            let (local_codec, mut match_type) =
                codec_parameters_fuzzy_search(&to_match_codec.rtp_codec, codecs);
            if match_type == CodecMatch::Exact && apt_match == CodecMatch::Partial {
                match_type = CodecMatch::Partial;
            }
            return Ok((local_codec, match_type));
        }

        let (local_codec, match_type) =
            codec_parameters_fuzzy_search(&remote_codec.rtp_codec, codecs);
        Ok((local_codec, match_type))
    }

    // Update header extensions from a remote media section.
    fn update_header_extension_from_media_section(
        &mut self,
        media: &MediaDescription,
    ) -> Result<()> {
        let typ = if media.media_name.media.to_lowercase() == "audio" {
            RtpCodecKind::Audio
        } else if media.media_name.media.to_lowercase() == "video" {
            RtpCodecKind::Video
        } else {
            return Ok(());
        };

        let extensions = rtp_extensions_from_media_description(media)?;

        for (extension, id) in extensions {
            self.update_header_extension(id, extension.as_str(), typ)?;
        }

        Ok(())
    }

    /// Look up a header extension and enable if it exists
    pub(crate) fn update_header_extension(
        &mut self,
        id: u16,
        extension: &str,
        typ: RtpCodecKind,
    ) -> Result<()> {
        for local_extension in &self.header_extensions {
            if local_extension.uri == extension {
                if let Some(existing_extension) = self.negotiated_header_extensions.get_mut(&id) {
                    if local_extension.is_audio && typ == RtpCodecKind::Audio {
                        existing_extension.is_audio = true;
                    }
                    if local_extension.is_video && typ == RtpCodecKind::Video {
                        existing_extension.is_video = true;
                    }
                } else {
                    self.negotiated_header_extensions.insert(
                        id,
                        MediaEngineHeaderExtension {
                            uri: extension.to_owned(),
                            is_audio: local_extension.is_audio && typ == RtpCodecKind::Audio,
                            is_video: local_extension.is_video && typ == RtpCodecKind::Video,
                            allowed_direction: local_extension.allowed_direction,
                        },
                    );
                }
            }
        }
        Ok(())
    }

    pub(crate) fn push_codecs(&mut self, codecs: Vec<RTCRtpCodecParameters>, typ: RtpCodecKind) {
        for codec in codecs {
            if typ == RtpCodecKind::Audio {
                MediaEngine::add_codec(&mut self.negotiated_audio_codecs, codec);
            } else if typ == RtpCodecKind::Video {
                MediaEngine::add_codec(&mut self.negotiated_video_codecs, codec);
            }
        }
    }

    /// Update the MediaEngine from a remote description
    pub(crate) fn update_from_remote_description(
        &mut self,
        desc: &SessionDescription,
    ) -> Result<()> {
        for media in &desc.media_descriptions {
            let typ = if media.media_name.media.to_lowercase() == "audio" {
                RtpCodecKind::Audio
            } else if media.media_name.media.to_lowercase() == "video" {
                RtpCodecKind::Video
            } else {
                RtpCodecKind::Unspecified
            };

            if !self.negotiated_audio && typ == RtpCodecKind::Audio {
                self.negotiated_audio = true;
            } else if !self.negotiated_video && typ == RtpCodecKind::Video {
                self.negotiated_video = true;
            } else {
                // update header extesions from remote sdp if codec is negotiated, Firefox
                // would send updated header extension in renegotiation.
                // e.g. publish first track without simucalst ->negotiated-> publish second track with simucalst
                // then the two media secontions have different rtp header extensions in offer
                self.update_header_extension_from_media_section(media)?;

                if !self.negotiate_multi_codecs
                    || (typ != RtpCodecKind::Audio && typ != RtpCodecKind::Video)
                {
                    continue;
                }
            }

            let mut codecs = codecs_from_media_description(media)?;

            let add_if_new = |existing_codecs: &mut Vec<RTCRtpCodecParameters>,
                              codec: &RTCRtpCodecParameters| {
                let mut found = false;
                for existing_codec in existing_codecs.iter() {
                    if existing_codec.payload_type == codec.payload_type {
                        found = true;
                        break;
                    }
                }

                if !found {
                    existing_codecs.push(codec.clone());
                }
            };

            let mut exact_matches = vec![];
            let mut partial_matches = vec![];

            for remote_codec in &mut codecs {
                let (local_codec, match_type) =
                    self.match_remote_codec(remote_codec, typ, &exact_matches, &partial_matches)?;

                remote_codec.rtp_codec.rtcp_feedback = rtcp_feedback_intersection(
                    &local_codec.rtp_codec.rtcp_feedback,
                    &remote_codec.rtp_codec.rtcp_feedback,
                );

                if match_type == CodecMatch::Exact {
                    add_if_new(&mut exact_matches, remote_codec);
                } else if match_type == CodecMatch::Partial {
                    add_if_new(&mut partial_matches, remote_codec);
                }
            }
            // second pass in case there were missed RTX codecs
            for remote_codec in &mut codecs {
                let (local_codec, match_type) =
                    self.match_remote_codec(remote_codec, typ, &exact_matches, &partial_matches)?;

                remote_codec.rtp_codec.rtcp_feedback = rtcp_feedback_intersection(
                    &local_codec.rtp_codec.rtcp_feedback,
                    &remote_codec.rtp_codec.rtcp_feedback,
                );

                if match_type == CodecMatch::Exact {
                    add_if_new(&mut exact_matches, remote_codec);
                } else if match_type == CodecMatch::Partial {
                    add_if_new(&mut partial_matches, remote_codec);
                }
            }

            // use exact matches when they exist, otherwise fall back to partial
            if !exact_matches.is_empty() {
                self.push_codecs(exact_matches, typ);
            } else if !partial_matches.is_empty() {
                self.push_codecs(partial_matches, typ);
            } else {
                // no match, not negotiated
                continue;
            }

            self.update_header_extension_from_media_section(media)?;
        }

        Ok(())
    }

    pub(crate) fn get_codecs_by_kind(&self, typ: RtpCodecKind) -> Vec<RTCRtpCodecParameters> {
        if typ == RtpCodecKind::Video {
            if self.negotiated_video {
                self.negotiated_video_codecs.clone()
            } else {
                self.video_codecs.clone()
            }
        } else if typ == RtpCodecKind::Audio {
            if self.negotiated_audio {
                self.negotiated_audio_codecs.clone()
            } else {
                self.audio_codecs.clone()
            }
        } else {
            vec![]
        }
    }

    pub(crate) fn get_rtp_parameters_by_kind(
        &self,
        typ: RtpCodecKind,
        direction: RTCRtpTransceiverDirection,
    ) -> RTCRtpParameters {
        let mut header_extensions = vec![];

        let found_codecs = self.get_codecs_by_kind(typ);

        if self.negotiated_video && typ == RtpCodecKind::Video
            || self.negotiated_audio && typ == RtpCodecKind::Audio
        {
            for (id, e) in &self.negotiated_header_extensions {
                if e.is_matching_direction(direction)
                    && (e.is_audio && typ == RtpCodecKind::Audio
                        || e.is_video && typ == RtpCodecKind::Video)
                {
                    header_extensions.push(RTCRtpHeaderExtensionParameters {
                        id: *id,
                        uri: e.uri.clone(),
                        ..Default::default()
                    });
                }
            }
        } else {
            let mut media_header_extensions = HashMap::new();

            for ext in &self.header_extensions {
                let mut using_negotiated_id = false;
                for (id, negotiated_extension) in &self.negotiated_header_extensions {
                    if negotiated_extension.uri == ext.uri {
                        using_negotiated_id = true;
                        media_header_extensions.insert(*id, ext);
                        break;
                    }
                }
                if !using_negotiated_id {
                    for id in 1..15 {
                        let mut id_available = true;
                        if media_header_extensions.contains_key(&id) {
                            id_available = false
                        }
                        if id_available && !self.negotiated_header_extensions.contains_key(&id) {
                            media_header_extensions.insert(id, ext);
                            break;
                        }
                    }
                }
            }

            for (id, e) in media_header_extensions {
                if e.is_matching_direction(direction)
                    && (e.is_audio && typ == RtpCodecKind::Audio
                        || e.is_video && typ == RtpCodecKind::Video)
                {
                    header_extensions.push(RTCRtpHeaderExtensionParameters {
                        id,
                        uri: e.uri.clone(),
                        ..Default::default()
                    })
                }
            }
        }

        RTCRtpParameters {
            header_extensions,
            codecs: found_codecs,
            ..Default::default()
        }
    }

    pub(crate) fn get_rtp_parameters_by_payload_type(
        &self,
        payload_type: PayloadType,
    ) -> Result<RTCRtpParameters> {
        let (codec, typ) = self.get_codec_by_payload(payload_type)?;

        let mut header_extensions = vec![];
        for (id, e) in &self.negotiated_header_extensions {
            if e.is_audio && typ == RtpCodecKind::Audio || e.is_video && typ == RtpCodecKind::Video
            {
                header_extensions.push(RTCRtpHeaderExtensionParameters {
                    uri: e.uri.clone(),
                    id: *id,
                    ..Default::default()
                });
            }
        }

        Ok(RTCRtpParameters {
            header_extensions,
            codecs: vec![codec],
            ..Default::default()
        })
    }

    pub(crate) fn is_rtx_enabled(
        &self,
        kind: RtpCodecKind,
        direction: RTCRtpTransceiverDirection,
    ) -> bool {
        for codec in &self.get_rtp_parameters_by_kind(kind, direction).codecs {
            if UniCase::new(codec.rtp_codec.mime_type.as_str()) == UniCase::new(MIME_TYPE_RTX) {
                return true;
            }
        }

        false
    }

    pub(crate) fn is_fec_enabled(
        &self,
        kind: RtpCodecKind,
        direction: RTCRtpTransceiverDirection,
    ) -> bool {
        for codec in &self.get_rtp_parameters_by_kind(kind, direction).codecs {
            if UniCase::new(codec.rtp_codec.mime_type.as_str())
                .contains(*UniCase::new(MIME_TYPE_FLEX_FEC))
            {
                return true;
            }
        }

        false
    }
}