rustpbx 0.4.2

A SIP PBX 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
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
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
use anyhow::{Result, anyhow};
use audio_codec::CodecType;
use rustrtc::{MediaKind, SdpType, SessionDescription};
use std::collections::{BTreeSet, HashMap, HashSet};

/// Parsed RTP codec information from SDP
#[derive(Debug, Clone)]
pub struct CodecInfo {
    pub payload_type: u8,
    pub codec: CodecType,
    pub clock_rate: u32,
    pub channels: u16,
}

impl CodecInfo {
    pub fn to_params(&self) -> rustrtc::RtpCodecParameters {
        rustrtc::RtpCodecParameters {
            payload_type: self.payload_type,
            clock_rate: self.clock_rate,
            channels: if self.channels > 255 {
                255
            } else {
                self.channels as u8
            },
        }
    }

    pub fn is_dtmf(&self) -> bool {
        self.codec == CodecType::TelephoneEvent
    }

    /// Convert to rustrtc AudioCapability for use in RtcConfiguration.media_capabilities
    pub fn to_audio_capability(&self) -> Option<rustrtc::config::AudioCapability> {
        use rustrtc::config::AudioCapability;
        let (codec_name, default_fmtp) = match self.codec {
            CodecType::PCMU => ("PCMU".to_string(), None),
            CodecType::PCMA => ("PCMA".to_string(), None),
            CodecType::G722 => ("G722".to_string(), None),
            CodecType::G729 => ("G729".to_string(), None),
            #[cfg(feature = "opus")]
            CodecType::Opus => (
                "opus".to_string(),
                Some("minptime=10;useinbandfec=1".to_string()),
            ),
            CodecType::TelephoneEvent => ("telephone-event".to_string(), Some("0-16".to_string())),
            #[allow(unreachable_patterns)]
            _ => return None,
        };

        Some(AudioCapability {
            payload_type: self.payload_type,
            codec_name,
            clock_rate: self.clock_rate,
            channels: if self.channels > u8::MAX as u16 {
                u8::MAX
            } else {
                self.channels as u8
            },
            fmtp: default_fmtp,
            rtcp_fbs: vec![],
        })
    }
}

#[derive(Debug, Clone, Default)]
pub struct ExtractedCodecs {
    pub audio: Vec<CodecInfo>,
    pub video: Vec<CodecInfo>,
    pub dtmf: Vec<CodecInfo>,
}

/// Complete negotiation result
#[derive(Debug, Clone)]
pub struct NegotiationResult {
    pub codec: CodecType,
    pub params: rustrtc::RtpCodecParameters,
    pub dtmf_pt: Option<u8>,
}

/// A single negotiated codec with its RTP parameters from SDP answer.
#[derive(Debug, Clone)]
pub struct NegotiatedCodec {
    pub codec: CodecType,
    pub payload_type: u8,
    pub clock_rate: u32,
    pub channels: u16,
}

/// Per-leg negotiated media profile extracted from an SDP answer.
/// Contains the selected audio codec, video codec, and the selected DTMF entry for that answer.
#[derive(Debug, Clone, Default)]
pub struct NegotiatedLegProfile {
    pub audio: Option<NegotiatedCodec>,
    pub video: Option<NegotiatedCodec>,
    pub dtmf: Option<NegotiatedCodec>,
}

/// Media negotiator for SDP parsing and codec selection
pub struct MediaNegotiator;

/// Strategy for selecting codecs when the target endpoint is WebRTC.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum CodecSelectionStrategy {
    /// Avoid transcoding: keep only codecs the caller already offers
    /// that the target transport supports. No additional codecs are added.
    #[default]
    Performance,
    /// Prefer quality: prioritize codecs by audio quality regardless of
    /// whether transcoding is required. Order: Opus > G729 > G722 > G711.
    Quality,
}

/// Quality-priority codec order (best first).
fn quality_codec_order() -> Vec<CodecType> {
    vec![
        #[cfg(feature = "opus")]
        CodecType::Opus,
        CodecType::G729,
        CodecType::G722,
        CodecType::PCMU,
        CodecType::PCMA,
    ]
}

/// Codec lists for both sides of a WebRTC↔RTP transport bridge.
#[derive(Debug, Clone)]
pub struct BridgeCodecLists {
    /// Codecs for the caller-facing side of the bridge
    pub caller_side: Vec<CodecInfo>,
    /// Codecs for the callee-facing side of the bridge
    pub callee_side: Vec<CodecInfo>,
    /// Codecs that are supported by BOTH sides (intersection of caller_side and callee_side).
    /// This preserves caller payload types for common codecs.
    pub common: Vec<CodecInfo>,
}

impl MediaNegotiator {
    fn parse_audio_section(sdp_str: &str) -> Option<rustrtc::MediaSection> {
        SessionDescription::parse(SdpType::Answer, sdp_str)
            .or_else(|_| SessionDescription::parse(SdpType::Offer, sdp_str))
            .ok()?
            .media_sections
            .into_iter()
            .find(|m| m.kind == MediaKind::Audio)
    }

    fn parse_video_section(sdp_str: &str) -> Option<rustrtc::MediaSection> {
        SessionDescription::parse(SdpType::Answer, sdp_str)
            .or_else(|_| SessionDescription::parse(SdpType::Offer, sdp_str))
            .ok()?
            .media_sections
            .into_iter()
            .find(|m| m.kind == MediaKind::Video)
    }

    fn parse_rtpmap_attributes(
        section: &rustrtc::MediaSection,
    ) -> (HashMap<u8, CodecInfo>, HashSet<u8>) {
        let mut codec_by_pt = HashMap::new();
        let mut unrecognized_pts = HashSet::new();

        for attr in &section.attributes {
            if attr.key == "rtpmap"
                && let Some(ref value) = attr.value
                && let Some((pt_str, codec_str)) = value.split_once(' ')
                && let Ok(pt) = pt_str.parse::<u8>()
            {
                let parts: Vec<&str> = codec_str.split('/').collect();
                if parts.len() >= 2 {
                    let codec_name = parts[0];
                    let clock_rate = parts[1].parse::<u32>().unwrap_or(8000);
                    let channels = if parts.len() >= 3 {
                        parts[2].parse::<u16>().unwrap_or(1)
                    } else {
                        1
                    };

                    let codec_type = match CodecType::try_from(codec_name) {
                        Ok(c) => c,
                        Err(_) => {
                            unrecognized_pts.insert(pt);
                            continue;
                        }
                    };

                    codec_by_pt.insert(
                        pt,
                        CodecInfo {
                            payload_type: pt,
                            codec: codec_type,
                            clock_rate,
                            channels,
                        },
                    );
                }
            }
        }

        (codec_by_pt, unrecognized_pts)
    }

    fn static_codec_for_payload(section: &rustrtc::MediaSection, pt: u8) -> Option<CodecInfo> {
        let static_codec = if let Ok(codec) = CodecType::try_from(pt) {
            let (rate, chans) = match codec {
                CodecType::PCMU | CodecType::PCMA | CodecType::G722 | CodecType::G729 => (8000, 1),
                #[cfg(feature = "opus")]
                CodecType::Opus => (48000, 2),
                _ => return None,
            };
            Some((codec, rate, chans))
        } else {
            #[cfg(feature = "opus")]
            if (pt == 96 || pt == 111) && section.kind == MediaKind::Audio {
                Some((CodecType::Opus, 48000, 2))
            } else {
                None
            }
            #[cfg(not(feature = "opus"))]
            None
        };

        static_codec.map(|(codec, rate, chans)| CodecInfo {
            payload_type: pt,
            codec,
            clock_rate: rate,
            channels: chans,
        })
    }

    fn extract_ordered_codecs_from_section(section: &rustrtc::MediaSection) -> Vec<CodecInfo> {
        let (mut codec_by_pt, unrecognized_pts) = Self::parse_rtpmap_attributes(section);
        let mut ordered_codecs = Vec::new();
        let mut seen_pts = HashSet::new();

        for format in &section.formats {
            let Ok(pt) = format.parse::<u8>() else {
                continue;
            };
            if !seen_pts.insert(pt) {
                continue;
            }

            if unrecognized_pts.contains(&pt) {
                continue;
            }

            let codec = codec_by_pt
                .remove(&pt)
                .or_else(|| Self::static_codec_for_payload(section, pt));
            if let Some(codec) = codec {
                ordered_codecs.push(codec);
            }
        }

        ordered_codecs
    }

    /// Parse RTP map from SDP media section in `m=` payload order.
    /// Returns: Vec<(payload_type, (codec, clock_rate, channels))>
    pub fn parse_rtp_map_from_section(
        section: &rustrtc::MediaSection,
    ) -> Vec<(u8, (CodecType, u32, u16))> {
        Self::extract_ordered_codecs_from_section(section)
            .into_iter()
            .map(|codec| {
                (
                    codec.payload_type,
                    (codec.codec, codec.clock_rate, codec.channels),
                )
            })
            .collect()
    }

    pub fn extract_codec_params(sdp_str: &str) -> ExtractedCodecs {
        let mut extracted = ExtractedCodecs::default();

        // Extract audio codecs
        if let Some(section) = Self::parse_audio_section(sdp_str) {
            for codec in Self::extract_ordered_codecs_from_section(&section) {
                if codec.is_dtmf() {
                    extracted.dtmf.push(codec);
                } else {
                    extracted.audio.push(codec);
                }
            }
        }

        // Extract video codecs
        if let Some(section) = Self::parse_video_section(sdp_str) {
            for codec in Self::extract_ordered_codecs_from_section(&section) {
                extracted.video.push(codec);
            }
        }

        extracted
    }

    pub fn extract_dtmf_codecs(sdp_str: &str) -> Vec<CodecInfo> {
        Self::extract_codec_params(sdp_str).dtmf
    }

    /// Select the best common codec from the remote (answerer) codec list.
    ///
    /// Rules (in order of priority):
    /// 1. Respect the remote party's SDP order (first = most preferred).
    /// 2. Skip `telephone-event` (handled separately).
    /// 3. Filter by `allow_codecs` — if empty, all codecs are allowed.
    /// 4. If the first candidate is not allowed, continue scanning the list
    ///    to find the first codec that IS in `allow_codecs`.
    pub fn select_best_codec(
        remote_codecs: &[CodecInfo],
        allowed_codecs: &[CodecType],
    ) -> Option<CodecInfo> {
        remote_codecs
            .iter()
            .filter(|c| c.codec != CodecType::TelephoneEvent)
            .find(|c| allowed_codecs.is_empty() || allowed_codecs.contains(&c.codec))
            .cloned()
    }

    /// Extract all codec information from SDP
    pub fn extract_all_codecs(sdp_str: &str) -> Vec<CodecInfo> {
        let extracted = Self::extract_codec_params(sdp_str);
        extracted.audio.into_iter().chain(extracted.dtmf).collect()
    }

    /// Negotiate codec between two SDP offers/answers
    /// Returns the selected codec info
    pub fn negotiate_codec(
        local_codecs: &[CodecType],
        remote_sdp: &str,
    ) -> Result<NegotiationResult> {
        let remote_codecs = Self::extract_all_codecs(remote_sdp);

        // Find first matching codec (prioritize local order)
        for local_codec in local_codecs {
            if let Some(remote) = remote_codecs
                .iter()
                .find(|r| r.codec == *local_codec && r.codec != CodecType::TelephoneEvent)
            {
                let params = rustrtc::RtpCodecParameters {
                    payload_type: remote.payload_type,
                    clock_rate: remote.clock_rate,
                    channels: if remote.channels > 255 {
                        255
                    } else {
                        remote.channels as u8
                    },
                };

                let remote_dtmf_codecs: Vec<_> = remote_codecs
                    .iter()
                    .filter(|r| r.codec == CodecType::TelephoneEvent)
                    .cloned()
                    .collect();

                return Ok(NegotiationResult {
                    codec: remote.codec,
                    params,
                    dtmf_pt: remote_dtmf_codecs.first().map(|codec| codec.payload_type),
                });
            }
        }

        Err(anyhow!("No compatible codec found"))
    }

    /// Build default codec list for RTP endpoints
    pub fn default_rtp_codecs() -> Vec<CodecType> {
        vec![
            #[cfg(feature = "opus")]
            CodecType::Opus,
            CodecType::G729,
            CodecType::G722,
            CodecType::PCMU,
            CodecType::PCMA,
            CodecType::TelephoneEvent,
        ]
    }

    /// Build default codec list for WebRTC endpoints
    pub fn default_webrtc_codecs() -> Vec<CodecType> {
        vec![
            #[cfg(feature = "opus")]
            CodecType::Opus,
            CodecType::G722,
            CodecType::PCMU,
            CodecType::PCMA,
            CodecType::TelephoneEvent,
        ]
    }

    fn supported_codecs_for_transport(is_webrtc: bool) -> Vec<CodecType> {
        if is_webrtc {
            Self::default_webrtc_codecs()
        } else {
            Self::default_rtp_codecs()
        }
    }

    fn allowed_supported_codecs(is_webrtc: bool, allow_codecs: &[CodecType]) -> Vec<CodecType> {
        Self::supported_codecs_for_transport(is_webrtc)
            .into_iter()
            .filter(|codec| allow_codecs.is_empty() || allow_codecs.contains(codec))
            .collect()
    }

    pub(crate) fn codec_info_for_type(codec_type: CodecType) -> CodecInfo {
        CodecInfo {
            payload_type: codec_type.payload_type(),
            codec: codec_type,
            clock_rate: codec_type.clock_rate(),
            channels: codec_type.channels(),
        }
    }

    /// Get preferred codec from a list
    pub fn get_preferred_codec(codecs: &[CodecType]) -> Option<CodecType> {
        codecs
            .iter()
            .find(|c| **c != CodecType::TelephoneEvent)
            .copied()
    }

    /// Extract a negotiated leg profile from an SDP answer.
    /// Takes the first audio codec (the selected one in an answer) and selects
    /// one DTMF entry using the current call assumptions.
    pub fn extract_leg_profile(sdp: &str) -> NegotiatedLegProfile {
        let extracted = Self::extract_codec_params(sdp);
        let audio = extracted.audio.first().map(|c| NegotiatedCodec {
            codec: c.codec,
            payload_type: c.payload_type,
            clock_rate: c.clock_rate,
            channels: c.channels,
        });
        let video = extracted.video.first().map(|c| NegotiatedCodec {
            codec: c.codec,
            payload_type: c.payload_type,
            clock_rate: c.clock_rate,
            channels: c.channels,
        });
        let dtmf = match extracted.dtmf.len() {
            0 => None,
            1 => extracted.dtmf.first().map(|c| NegotiatedCodec {
                codec: c.codec,
                payload_type: c.payload_type,
                clock_rate: c.clock_rate,
                channels: c.channels,
            }),
            _ => {
                let preferred_rate = match audio.as_ref().map(|codec| codec.codec) {
                    #[cfg(feature = "opus")]
                    Some(CodecType::Opus) => 48000,
                    _ => 8000,
                };
                extracted
                    .dtmf
                    .iter()
                    .find(|codec| codec.clock_rate == preferred_rate)
                    .or(extracted.dtmf.first())
                    .map(|c| NegotiatedCodec {
                        codec: c.codec,
                        payload_type: c.payload_type,
                        clock_rate: c.clock_rate,
                        channels: c.channels,
                    })
            }
        };

        NegotiatedLegProfile { audio, video, dtmf }
    }

    fn attr_payload_type(attr: &rustrtc::sdp::Attribute) -> Option<u8> {
        let value = attr.value.as_ref()?;
        value.split_whitespace().next()?.parse::<u8>().ok()
    }

    fn codec_signature(codec: &CodecInfo) -> String {
        format!("{:?}/{}/{}", codec.codec, codec.clock_rate, codec.channels)
    }

    /// Restrict an already-generated caller-facing SDP answer to the subset of
    /// caller codecs that also appear in the callee's answer.
    ///
    /// The generated answer stays the source of truth for WebRTC-specific SDP,
    /// ICE, DTLS, and candidates. Filtering is done by codec identity using
    /// the generated caller answer order, while preserving caller-leg payload
    /// types already chosen by create_answer().
    pub fn restrict_answer_to_callee_accepted_codecs(
        answer_sdp: &str,
        callee_answer_sdp: &str,
    ) -> Option<String> {
        let caller_answer_codecs = Self::extract_codec_params(answer_sdp);
        let callee_answer_codecs = Self::extract_codec_params(callee_answer_sdp);

        let accepted_by_callee: HashSet<String> = callee_answer_codecs
            .audio
            .iter()
            .chain(callee_answer_codecs.dtmf.iter())
            .map(Self::codec_signature)
            .collect();
        if accepted_by_callee.is_empty() {
            return None;
        }

        let mut allowed_pts = Vec::new();
        let mut seen_pts = HashSet::new();
        for codec in caller_answer_codecs
            .audio
            .iter()
            .chain(caller_answer_codecs.dtmf.iter())
        {
            let signature = Self::codec_signature(codec);
            if accepted_by_callee.contains(&signature) && seen_pts.insert(codec.payload_type) {
                allowed_pts.push(codec.payload_type);
            }
        }
        if allowed_pts.is_empty() {
            return None;
        }

        let mut desc = SessionDescription::parse(SdpType::Answer, answer_sdp).ok()?;
        let audio_section = desc
            .media_sections
            .iter_mut()
            .find(|section| section.kind == MediaKind::Audio)?;

        audio_section.formats = allowed_pts.iter().map(|pt| pt.to_string()).collect();
        audio_section
            .attributes
            .retain(|attr| match attr.key.as_str() {
                "rtpmap" | "fmtp" | "rtcp-fb" => {
                    Self::attr_payload_type(attr).is_none_or(|pt| allowed_pts.contains(&pt))
                }
                _ => true,
            });

        Some(desc.to_sdp_string())
    }

    /// Build codec list for callee offer in anchored media mode.
    ///
    /// Strategy:
    /// 1. Keep caller's codecs that PBX supports (preserving caller's order and PT)
    /// 2. Append PBX-supported codecs not already present (with default PT)
    /// 3. For DTMF: if the caller offered telephone-event, keep compatible
    ///    telephone-event entries and append missing variants required by audio codecs
    ///    (8000 for narrowband codecs, 48000 for Opus)
    pub fn build_callee_codec_offer(caller_sdp: &str, is_webrtc: bool) -> Vec<CodecInfo> {
        Self::build_callee_codec_offer_with_allow(
            caller_sdp,
            is_webrtc,
            &[],
            CodecSelectionStrategy::default(),
        )
    }

    pub fn build_callee_codec_offer_with_allow(
        caller_sdp: &str,
        is_webrtc: bool,
        allow_codecs: &[CodecType],
        strategy: CodecSelectionStrategy,
    ) -> Vec<CodecInfo> {
        let extracted = Self::extract_codec_params(caller_sdp);
        let supported = Self::allowed_supported_codecs(is_webrtc, allow_codecs);

        let mut result: Vec<CodecInfo> = Vec::new();
        let mut seen_codecs: BTreeSet<CodecType> = BTreeSet::new();

        // 1. Keep caller's audio codecs that PBX supports (preserve order & PT)
        for codec in &extracted.audio {
            if supported.contains(&codec.codec) {
                result.push(codec.clone());
                seen_codecs.insert(codec.codec);
            }
        }

        // 2. Append PBX-supported audio codecs not already present
        //    Skip this for Performance strategy to avoid transcoding.
        if strategy == CodecSelectionStrategy::Quality {
            for codec_type in &supported {
                if *codec_type == CodecType::TelephoneEvent {
                    continue; // handle DTMF separately
                }
                if !seen_codecs.contains(codec_type) {
                    result.push(Self::codec_info_for_type(*codec_type));
                    seen_codecs.insert(*codec_type);
                }
            }

            // Reorder by quality priority: Opus > G729 > G722 > G711
            let quality_order = quality_codec_order();
            let mut audio: Vec<CodecInfo> = Vec::new();
            let mut dtmf: Vec<CodecInfo> = Vec::new();
            for c in result.drain(..) {
                if c.is_dtmf() {
                    dtmf.push(c);
                } else {
                    audio.push(c);
                }
            }
            audio.sort_by(|a, b| {
                let pa = quality_order
                    .iter()
                    .position(|c| *c == a.codec)
                    .unwrap_or(usize::MAX);
                let pb = quality_order
                    .iter()
                    .position(|c| *c == b.codec)
                    .unwrap_or(usize::MAX);
                pa.cmp(&pb)
            });
            // Audio codecs first (in quality order), DTMF at the end
            result = audio;
            result.extend(dtmf);
        }

        // 3. DTMF: if caller offered telephone-event and policy allows it, keep
        //    caller DTMF entries and add required clock rates for the callee offer.
        if supported.contains(&CodecType::TelephoneEvent) && !extracted.dtmf.is_empty() {
            let mut seen_dtmf_rates: HashSet<u32> = HashSet::new();
            for dtmf in &extracted.dtmf {
                result.push(dtmf.clone());
                seen_dtmf_rates.insert(dtmf.clock_rate);
            }

            let has_opus = result.iter().any(|c| c.codec == CodecType::Opus);
            let has_narrowband = result
                .iter()
                .any(|c| c.codec.is_audio() && c.codec != CodecType::Opus);

            let mut needed_rates: Vec<u32> = Vec::new();
            if has_narrowband && !seen_dtmf_rates.contains(&8000) {
                needed_rates.push(8000);
            }
            if has_opus && !seen_dtmf_rates.contains(&48000) {
                needed_rates.push(48000);
            }

            let mut used_pts: HashSet<u8> = result.iter().map(|c| c.payload_type).collect();
            for rate in needed_rates {
                let default_pt = CodecType::TelephoneEvent.payload_type();
                let pt = if !used_pts.contains(&default_pt) {
                    default_pt
                } else {
                    (96..=127)
                        .find(|p| !used_pts.contains(p))
                        .unwrap_or(default_pt)
                };
                used_pts.insert(pt);
                result.push(CodecInfo {
                    payload_type: pt,
                    clock_rate: rate,
                    channels: 1,
                    codec: CodecType::TelephoneEvent,
                });
            }
        }

        result
    }

    /// Build codec list for answering the caller in anchored media mode.
    ///
    /// Unlike the callee offer builder, this must stay a strict subset of the
    /// caller's original offer so the generated answer never advertises a codec
    /// the caller did not offer. PT values are preserved from the caller's SDP.
    pub fn build_caller_answer_codec_list(caller_sdp: &str, is_webrtc: bool) -> Vec<CodecInfo> {
        Self::build_caller_answer_codec_list_with_allow(caller_sdp, is_webrtc, &[])
    }

    pub fn build_caller_answer_codec_list_with_allow(
        caller_sdp: &str,
        is_webrtc: bool,
        allow_codecs: &[CodecType],
    ) -> Vec<CodecInfo> {
        let extracted = Self::extract_codec_params(caller_sdp);
        let supported = Self::allowed_supported_codecs(is_webrtc, allow_codecs);

        let mut result = Vec::new();
        for codec in extracted.audio.into_iter().chain(extracted.dtmf) {
            if supported.contains(&codec.codec) {
                result.push(codec);
            }
        }

        result
    }

    /// Build codec lists for a transport bridge (WebRTC↔RTP).
    ///
    /// Strategy:
    /// 1. Caller side is a strict subset of the caller offer, filtered by transport support and `allow_codecs`
    /// 2. Callee side is built according to `strategy`:
    ///    - `Performance`: caller's supported codecs only (no transcode)
    ///    - `Quality`: caller's supported codecs + quality-priority order
    /// 3. Compute the intersection (common) for codec-aligned fallback paths
    pub fn build_bridge_codec_lists(
        caller_sdp: &str,
        caller_is_webrtc: bool,
        callee_is_webrtc: bool,
        allow_codecs: &[CodecType],
        strategy: CodecSelectionStrategy,
    ) -> BridgeCodecLists {
        let caller_side = Self::build_caller_answer_codec_list_with_allow(
            caller_sdp,
            caller_is_webrtc,
            allow_codecs,
        );
        let callee_side = Self::build_callee_codec_offer_with_allow(
            caller_sdp,
            callee_is_webrtc,
            allow_codecs,
            strategy,
        );

        // Keep caller payload types for common codecs; side-specific lists can differ
        // when the bridge configures transcoders after both legs answer.
        let common: Vec<CodecInfo> = caller_side
            .iter()
            .filter(|c| callee_side.iter().any(|cc| cc.codec == c.codec))
            .cloned()
            .collect();

        BridgeCodecLists {
            caller_side,
            callee_side,
            common,
        }
    }

    pub fn extract_ssrc(sdp: &str) -> Option<u32> {
        // Try parsing as Answer first, then Offer if it fails (though usually it's Answer)
        let session = SessionDescription::parse(SdpType::Answer, sdp)
            .or_else(|_| SessionDescription::parse(SdpType::Offer, sdp))
            .ok()?;

        for section in session.media_sections {
            if section.kind == MediaKind::Audio {
                for attr in section.attributes {
                    if attr.key == "ssrc"
                        && let Some(value) = attr.value
                    {
                        // value format: "12345 cname:..." or just "12345"
                        let ssrc_str = value.split_whitespace().next()?;
                        if let Ok(ssrc) = ssrc_str.parse::<u32>() {
                            return Some(ssrc);
                        }
                    }
                }
            }
        }
        None
    }
}

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

    #[test]
    fn test_parse_rtp_map() {
        let sdp = "v=0\r\n\
            o=- 1234 1234 IN IP4 127.0.0.1\r\n\
            s=-\r\n\
            t=0 0\r\n\
            m=audio 10000 RTP/AVP 0 8 101\r\n\
            a=rtpmap:0 PCMU/8000\r\n\
            a=rtpmap:8 PCMA/8000\r\n\
            a=rtpmap:101 telephone-event/8000\r\n";

        let desc = SessionDescription::parse(SdpType::Offer, sdp).unwrap();
        let section = desc
            .media_sections
            .iter()
            .find(|m| m.kind == MediaKind::Audio)
            .unwrap();

        let rtp_map = MediaNegotiator::parse_rtp_map_from_section(section);

        assert_eq!(rtp_map.len(), 3);
        assert!(
            rtp_map
                .iter()
                .any(|(pt, (c, _, _))| *pt == 0 && *c == CodecType::PCMU)
        );
        assert!(
            rtp_map
                .iter()
                .any(|(pt, (c, _, _))| *pt == 8 && *c == CodecType::PCMA)
        );
        assert!(
            rtp_map
                .iter()
                .any(|(pt, (c, _, _))| *pt == 101 && *c == CodecType::TelephoneEvent)
        );
    }

    #[test]
    fn test_extract_codec_params() {
        let sdp = "v=0\r\n\
            o=- 1234 1234 IN IP4 127.0.0.1\r\n\
            s=-\r\n\
            t=0 0\r\n\
            m=audio 10000 RTP/AVP 0 101\r\n\
            a=rtpmap:0 PCMU/8000\r\n\
            a=rtpmap:101 telephone-event/8000\r\n";

        let codecs = MediaNegotiator::extract_codec_params(sdp);
        let first = &codecs.audio[0];
        let params = first.to_params();

        assert_eq!(first.codec, CodecType::PCMU);
        assert_eq!(params.payload_type, 0);
        assert_eq!(params.clock_rate, 8000);
        assert_eq!(
            codecs
                .dtmf
                .iter()
                .map(|codec| codec.payload_type)
                .collect::<Vec<_>>(),
            vec![101]
        );
    }

    #[test]
    fn test_extract_codec_params_preserves_dtmf_offer_order() {
        let sdp = "v=0\r\n\
            o=- 1234 1234 IN IP4 127.0.0.1\r\n\
            s=-\r\n\
            t=0 0\r\n\
            m=audio 10000 RTP/AVP 96 110 126\r\n\
            a=rtpmap:96 opus/48000/2\r\n\
            a=rtpmap:110 telephone-event/48000\r\n\
            a=rtpmap:126 telephone-event/8000\r\n";

        let codecs = MediaNegotiator::extract_codec_params(sdp);

        assert_eq!(
            codecs
                .dtmf
                .iter()
                .map(|codec| (codec.payload_type, codec.clock_rate))
                .collect::<Vec<_>>(),
            vec![(110, 48000), (126, 8000)]
        );
    }

    #[test]
    fn test_negotiate_codec() {
        let local_codecs = vec![CodecType::PCMU, CodecType::PCMA];

        let remote_sdp = "v=0\r\n\
            o=- 1234 1234 IN IP4 127.0.0.1\r\n\
            s=-\r\n\
            t=0 0\r\n\
            m=audio 10000 RTP/AVP 8 101\r\n\
            a=rtpmap:8 PCMA/8000\r\n\
            a=rtpmap:101 telephone-event/8000\r\n";

        let result = MediaNegotiator::negotiate_codec(&local_codecs, remote_sdp).unwrap();

        assert_eq!(result.codec, CodecType::PCMA);
        assert_eq!(result.params.payload_type, 8);
        assert_eq!(result.dtmf_pt, Some(101));
    }

    #[test]
    fn test_negotiate_codec_no_match() {
        let local_codecs = vec![CodecType::Opus];

        let remote_sdp = "v=0\r\n\
            o=- 1234 1234 IN IP4 127.0.0.1\r\n\
            s=-\r\n\
            t=0 0\r\n\
            m=audio 10000 RTP/AVP 0\r\n\
            a=rtpmap:0 PCMU/8000\r\n";

        let result = MediaNegotiator::negotiate_codec(&local_codecs, remote_sdp);
        assert!(result.is_err());
    }

    #[test]
    fn test_default_codecs() {
        let rtp_codecs = MediaNegotiator::default_rtp_codecs();
        assert!(rtp_codecs.contains(&CodecType::PCMU));
        assert!(rtp_codecs.contains(&CodecType::PCMA));

        let webrtc_codecs = MediaNegotiator::default_webrtc_codecs();
        assert!(webrtc_codecs.contains(&CodecType::PCMU));
    }

    #[test]
    fn test_parse_static_payload_types() {
        let sdp = "v=0\r\n\
            o=- 1234 1234 IN IP4 127.0.0.1\r\n\
            s=-\r\n\
            t=0 0\r\n\
            m=audio 10000 RTP/AVP 0 8 101\r\n\
            a=rtpmap:101 telephone-event/8000\r\n";

        let desc = SessionDescription::parse(SdpType::Offer, sdp).unwrap();
        let section = desc
            .media_sections
            .iter()
            .find(|m| m.kind == MediaKind::Audio)
            .unwrap();
        let rtp_map = MediaNegotiator::parse_rtp_map_from_section(section);

        println!("RTP MAP: {:?}", rtp_map);

        // Should find PCMU (0) and PCMA (8) even without rtpmap
        assert!(
            rtp_map
                .iter()
                .any(|(pt, (codec, _, _))| *pt == 0 && *codec == CodecType::PCMU),
            "Missing PCMU (0)"
        );
        assert!(
            rtp_map
                .iter()
                .any(|(pt, (codec, _, _))| *pt == 8 && *codec == CodecType::PCMA),
            "Missing PCMA (8)"
        );
    }

    #[test]
    fn test_parse_dynamic_payload_type_fallback() {
        // Test handling of common dynamic payload types when rtpmap is missing (e.g. Opus as 96)
        let sdp = "v=0\r\n\
            o=- 1234 1234 IN IP4 127.0.0.1\r\n\
            s=-\r\n\
            t=0 0\r\n\
            m=audio 10000 RTP/AVP 96\r\n"; // 96 without rtpmap

        let desc = SessionDescription::parse(SdpType::Offer, sdp).unwrap();
        let section = desc
            .media_sections
            .iter()
            .find(|m| m.kind == MediaKind::Audio)
            .unwrap();
        let rtp_map = MediaNegotiator::parse_rtp_map_from_section(section);

        // This expects the permissive behavior we are about to implement
        assert!(
            rtp_map.iter().any(|(pt, (codec, rate, chans))| *pt == 96
                && *codec == CodecType::Opus
                && *rate == 48000
                && *chans == 2),
            "Missing fallback for Opus (96)"
        );
    }

    #[test]
    fn test_parse_dynamic_payload_type_fallback_111() {
        // Test handling of dynamic payload type 111 for Opus fallback
        let sdp = "v=0\r\n\
            o=- 1234 1234 IN IP4 127.0.0.1\r\n\
            s=-\r\n\
            t=0 0\r\n\
            m=audio 10000 RTP/AVP 111\r\n"; // 111 without rtpmap

        let desc = SessionDescription::parse(SdpType::Offer, sdp).unwrap();
        let section = desc
            .media_sections
            .iter()
            .find(|m| m.kind == MediaKind::Audio)
            .unwrap();
        let rtp_map = MediaNegotiator::parse_rtp_map_from_section(section);

        assert!(
            rtp_map.iter().any(|(pt, (codec, rate, chans))| *pt == 111
                && *codec == CodecType::Opus
                && *rate == 48000
                && *chans == 2),
            "Missing fallback for Opus (111)"
        );
    }

    #[test]
    fn test_extract_codec_params_order_preference() {
        // PCMU(0) is first, G722(9) is later.
        // We should pick PCMU because it's first in the Answer.
        let sdp = "v=0\r\no=- 123456 123456 IN IP4 127.0.0.1\r\ns=-\r\nc=IN IP4 127.0.0.1\r\nt=0 0\r\nm=audio 4000 RTP/AVP 0 101 8 9\r\na=rtpmap:0 PCMU/8000\r\na=rtpmap:101 telephone-event/8000\r\na=rtpmap:8 PCMA/8000\r\na=rtpmap:9 G722/8000\r\n";
        let codecs = MediaNegotiator::extract_codec_params(sdp);
        assert_eq!(
            codecs.audio[0].codec,
            CodecType::PCMU,
            "Should have picked PCMU (the first codec)"
        );
    }

    #[test]
    fn test_select_best_codec_with_preference() {
        // Simulating Answer codecs where remote peer chose G722 first, then PCMU
        let codecs = vec![
            CodecInfo {
                payload_type: 9,
                codec: CodecType::G722,
                clock_rate: 8000,
                channels: 1,
            },
            CodecInfo {
                payload_type: 0,
                codec: CodecType::PCMU,
                clock_rate: 8000,
                channels: 1,
            },
        ];

        // RFC 3264: Respect remote (answerer's) preference
        // Even if our preference is [PCMU, G722], we should respect the Answer order
        let allowed = vec![CodecType::PCMU, CodecType::G722];
        let best = MediaNegotiator::select_best_codec(&codecs, &allowed).unwrap();
        // Should pick G722 because it's first in the Answer (remote preference)
        assert_eq!(best.codec, CodecType::G722);

        // If our allowed list is [G722, PCMU], still pick G722 (first in remote)
        let allowed = vec![CodecType::G722, CodecType::PCMU];
        let best = MediaNegotiator::select_best_codec(&codecs, &allowed).unwrap();
        assert_eq!(best.codec, CodecType::G722);

        // Only allow PCMU - should scan past G722 to find PCMU
        let allowed = vec![CodecType::PCMU];
        let best = MediaNegotiator::select_best_codec(&codecs, &allowed).unwrap();
        assert_eq!(best.codec, CodecType::PCMU);

        // Empty allowed list - should follow remote order (first codec)
        let allowed = vec![];
        let best = MediaNegotiator::select_best_codec(&codecs, &allowed).unwrap();
        assert_eq!(best.codec, CodecType::G722);
    }

    #[test]
    fn test_select_best_codec_skips_telephone_event() {
        // Simulating Answer with TelephoneEvent as first codec (should be skipped)
        let codecs = vec![
            CodecInfo {
                payload_type: 101,
                codec: CodecType::TelephoneEvent,
                clock_rate: 8000,
                channels: 1,
            },
            CodecInfo {
                payload_type: 0,
                codec: CodecType::PCMU,
                clock_rate: 8000,
                channels: 1,
            },
            CodecInfo {
                payload_type: 8,
                codec: CodecType::PCMA,
                clock_rate: 8000,
                channels: 1,
            },
        ];

        // Should skip TelephoneEvent and pick PCMU (first audio codec)
        let allowed = vec![CodecType::PCMU, CodecType::PCMA];
        let best = MediaNegotiator::select_best_codec(&codecs, &allowed).unwrap();
        assert_eq!(best.codec, CodecType::PCMU);
        assert_ne!(best.codec, CodecType::TelephoneEvent);

        // Empty allowed list - should skip TelephoneEvent and pick first audio codec
        let allowed = vec![];
        let best = MediaNegotiator::select_best_codec(&codecs, &allowed).unwrap();
        assert_eq!(best.codec, CodecType::PCMU);
        assert_ne!(best.codec, CodecType::TelephoneEvent);
    }

    #[test]
    fn test_g722_clock_rate_preserves_sdp_value() {
        let sdp = "v=0\r\n\
            o=- 1769236545 1769236546 IN IP4 192.168.3.211\r\n\
            s=-\r\n\
            c=IN IP4 192.168.3.211\r\n\
            t=0 0\r\n\
            m=audio 51624 RTP/AVP 0 8 9 18 111\r\n\
            a=mid:0\r\n\
            a=sendrecv\r\n\
            a=rtcp-mux\r\n\
            a=rtpmap:0 PCMU/8000/1\r\n\
            a=rtpmap:8 PCMA/8000/1\r\n\
            a=rtpmap:9 G722/16000/1\r\n\
            a=rtpmap:18 G729/8000/1\r\n\
            a=rtpmap:111 opus/48000/2\r\n";

        let codecs = MediaNegotiator::extract_codec_params(sdp);

        // Find G722 codec
        let g722_info = codecs.audio.iter().find(|c| c.codec == CodecType::G722);
        assert!(g722_info.is_some(), "G722 should be parsed");

        let g722_info = g722_info.unwrap();
        assert_eq!(
            g722_info.clock_rate, 16000,
            "G722 clock rate should now follow the SDP value as offered"
        );
        assert_eq!(g722_info.payload_type, 9);
        assert_eq!(g722_info.channels, 1);

        // Verify other codecs are not affected
        let g729_info = codecs.audio.iter().find(|c| c.codec == CodecType::G729);
        assert!(g729_info.is_some());
        assert_eq!(g729_info.unwrap().clock_rate, 8000);
    }

    #[test]
    fn test_answer_codec_selection_respects_answerer_preference() {
        // Simulating the scenario from user's log:
        // rustpbx sent INVITE with: 96(G729), 9(G722), 0(PCMU), 8(PCMA), 111(Opus)
        // alice answered with:     0(PCMU), 8(PCMA), 9(G722), 18(G729), 111(Opus)
        // RFC 3264: We MUST use PCMU (alice's first choice), not G729 (our first choice)

        let answer_codecs = vec![
            CodecInfo {
                payload_type: 0,
                codec: CodecType::PCMU,
                clock_rate: 8000,
                channels: 1,
            },
            CodecInfo {
                payload_type: 8,
                codec: CodecType::PCMA,
                clock_rate: 8000,
                channels: 1,
            },
            CodecInfo {
                payload_type: 9,
                codec: CodecType::G722,
                clock_rate: 8000,
                channels: 1,
            },
            CodecInfo {
                payload_type: 18,
                codec: CodecType::G729,
                clock_rate: 8000,
                channels: 1,
            },
        ];

        // Our preference was G729 first, but we should respect alice's choice (PCMU)
        let our_offer_order = vec![
            CodecType::G729,
            CodecType::G722,
            CodecType::PCMU,
            CodecType::PCMA,
        ];

        let selected = MediaNegotiator::select_best_codec(&answer_codecs, &our_offer_order);
        assert!(selected.is_some(), "Should find a matching codec");

        let selected = selected.unwrap();
        assert_eq!(
            selected.codec,
            CodecType::PCMU,
            "Must use PCMU (answerer's first choice), not G729 (offerer's first choice)"
        );
        assert_eq!(selected.payload_type, 0);
    }

    // ── Bridge codec list tests ──────────────────────────────────

    /// WebRTC caller offers Opus+PCMU, allow_codecs=[PCMU] →
    /// caller side keeps PCMU only, callee side offers PCMU only (no transcode needed)
    #[test]
    fn test_bridge_codecs_webrtc_caller_rtp_callee_pcmu_only() {
        let caller_sdp = "v=0\r\n\
o=- 1 1 IN IP4 127.0.0.1\r\n\
s=-\r\n\
t=0 0\r\n\
m=audio 12345 UDP/TLS/RTP/SAVPF 111 0 101\r\n\
a=rtpmap:111 opus/48000/2\r\n\
a=rtpmap:0 PCMU/8000\r\n\
a=rtpmap:101 telephone-event/8000\r\n";

        let lists = MediaNegotiator::build_bridge_codec_lists(
            caller_sdp,
            true,  // caller is WebRTC
            false, // callee is RTP
            &[CodecType::PCMU, CodecType::TelephoneEvent],
            CodecSelectionStrategy::default(),
        );

        // Caller side: Opus offered but filtered out (not in allow_codecs), PCMU kept
        assert!(lists.caller_side.iter().any(|c| c.codec == CodecType::PCMU));
        assert!(
            !lists.caller_side.iter().any(|c| c.codec == CodecType::Opus),
            "Opus not in allow_codecs"
        );
        assert!(
            lists
                .caller_side
                .iter()
                .any(|c| c.codec == CodecType::TelephoneEvent)
        );

        // Callee side: only PCMU + telephone-event
        assert!(lists.callee_side.iter().any(|c| c.codec == CodecType::PCMU));
        assert!(!lists.callee_side.iter().any(|c| c.codec == CodecType::Opus));
        assert!(
            lists
                .callee_side
                .iter()
                .any(|c| c.codec == CodecType::TelephoneEvent)
        );
    }

    /// WebRTC caller offers Opus+PCMU, allow_codecs=[Opus,PCMU] →
    /// both sides keep Opus as first codec (no transcode)
    #[test]
    fn test_bridge_codecs_prefer_no_transcode_opus() {
        let caller_sdp = "v=0\r\n\
o=- 1 1 IN IP4 127.0.0.1\r\n\
s=-\r\n\
t=0 0\r\n\
m=audio 12345 UDP/TLS/RTP/SAVPF 111 0 101\r\n\
a=rtpmap:111 opus/48000/2\r\n\
a=rtpmap:0 PCMU/8000\r\n\
a=rtpmap:101 telephone-event/8000\r\n";

        let lists = MediaNegotiator::build_bridge_codec_lists(
            caller_sdp,
            true,  // caller is WebRTC
            false, // callee is RTP
            &[CodecType::Opus, CodecType::PCMU, CodecType::TelephoneEvent],
            CodecSelectionStrategy::default(),
        );

        // Caller side: Opus first (caller offered it, it's in allow_codecs)
        let caller_audio: Vec<_> = lists.caller_side.iter().filter(|c| !c.is_dtmf()).collect();
        assert_eq!(
            caller_audio[0].codec,
            CodecType::Opus,
            "Opus should be first on caller side"
        );
        assert_eq!(
            caller_audio[1].codec,
            CodecType::PCMU,
            "PCMU should be second"
        );

        // Callee side: Opus first per allow_codecs order
        let callee_audio: Vec<_> = lists.callee_side.iter().filter(|c| !c.is_dtmf()).collect();
        assert_eq!(
            callee_audio[0].codec,
            CodecType::Opus,
            "Opus should be first on callee side"
        );
        assert_eq!(callee_audio[1].codec, CodecType::PCMU);
    }

    /// RTP caller offers G729+PCMU, callee is WebRTC →
    /// G729 is NOT in WebRTC supported set, so callee side drops G729
    #[test]
    fn test_bridge_codecs_g729_dropped_for_webrtc_side() {
        let caller_sdp = "v=0\r\n\
o=- 1 1 IN IP4 127.0.0.1\r\n\
s=-\r\n\
t=0 0\r\n\
m=audio 10000 RTP/AVP 18 0 101\r\n\
a=rtpmap:18 G729/8000\r\n\
a=rtpmap:0 PCMU/8000\r\n\
a=rtpmap:101 telephone-event/8000\r\n";

        let lists = MediaNegotiator::build_bridge_codec_lists(
            caller_sdp,
            false, // caller is RTP
            true,  // callee is WebRTC
            &[CodecType::G729, CodecType::PCMU, CodecType::TelephoneEvent],
            CodecSelectionStrategy::default(),
        );

        // Caller side (RTP): G729 is in allow_codecs and supported for RTP
        assert!(
            lists.caller_side.iter().any(|c| c.codec == CodecType::G729),
            "G729 OK on RTP caller side"
        );
        assert!(lists.caller_side.iter().any(|c| c.codec == CodecType::PCMU));

        // Callee side (WebRTC): G729 NOT in WebRTC supported set → dropped
        assert!(
            !lists.callee_side.iter().any(|c| c.codec == CodecType::G729),
            "G729 dropped on WebRTC callee side"
        );
        assert!(
            lists.callee_side.iter().any(|c| c.codec == CodecType::PCMU),
            "PCMU kept on WebRTC callee side"
        );
    }

    /// allow_codecs=[] → each side is filtered only by its own transport support.
    #[test]
    fn test_bridge_codecs_empty_allow_codecs_fallback() {
        let caller_sdp = "v=0\r\n\
o=- 1 1 IN IP4 127.0.0.1\r\n\
s=-\r\n\
t=0 0\r\n\
m=audio 10000 RTP/AVP 0 101\r\n\
a=rtpmap:0 PCMU/8000\r\n\
a=rtpmap:101 telephone-event/8000\r\n";

        let lists = MediaNegotiator::build_bridge_codec_lists(
            caller_sdp,
            false,                           // caller is RTP
            true,                            // callee is WebRTC
            &[],                             // empty allow_codecs
            CodecSelectionStrategy::Quality, // append missing WebRTC codecs
        );

        let caller_audio: Vec<_> = lists.caller_side.iter().filter(|c| !c.is_dtmf()).collect();
        assert_eq!(caller_audio.len(), 1);
        assert_eq!(caller_audio[0].codec, CodecType::PCMU);

        let callee_audio: Vec<_> = lists.callee_side.iter().filter(|c| !c.is_dtmf()).collect();
        assert!(
            callee_audio
                .iter()
                .any(|codec| codec.codec == CodecType::PCMU),
            "Callee side should include supported PCMU"
        );
        assert!(
            callee_audio
                .iter()
                .any(|codec| codec.codec == CodecType::G722),
            "Callee side should include generated WebRTC-supported codecs"
        );
    }

    /// Caller offers PCMU at PT 0 → both sides preserve caller PT 0.
    #[test]
    fn test_bridge_codecs_preserves_caller_payload_type() {
        let caller_sdp = "v=0\r\n\
o=- 1 1 IN IP4 127.0.0.1\r\n\
s=-\r\n\
t=0 0\r\n\
m=audio 10000 RTP/AVP 0 101\r\n\
a=rtpmap:0 PCMU/8000\r\n\
a=rtpmap:101 telephone-event/8000\r\n";

        let lists = MediaNegotiator::build_bridge_codec_lists(
            caller_sdp,
            false, // caller is RTP
            false, // callee is RTP
            &[CodecType::PCMU, CodecType::TelephoneEvent],
            CodecSelectionStrategy::default(),
        );

        let caller_pcmu = lists
            .caller_side
            .iter()
            .find(|c| c.codec == CodecType::PCMU)
            .unwrap();
        assert_eq!(
            caller_pcmu.payload_type, 0,
            "Caller side should preserve caller PT 0"
        );

        let callee_pcmu = lists
            .callee_side
            .iter()
            .find(|c| c.codec == CodecType::PCMU)
            .unwrap();
        assert_eq!(
            callee_pcmu.payload_type, 0,
            "Callee side should preserve caller PT 0"
        );
    }

    /// Caller-side DTMF payload types and sample rates must come from the caller SDP.
    /// Callee-side DTMF is generated from callee transport/policy.
    #[test]
    fn test_bridge_codecs_preserves_caller_dtmf_payload_types_and_rates() {
        let caller_sdp = "v=0\r\n\
o=- 1 1 IN IP4 127.0.0.1\r\n\
s=-\r\n\
t=0 0\r\n\
m=audio 12345 UDP/TLS/RTP/SAVPF 111 101 110\r\n\
a=rtpmap:111 opus/48000/2\r\n\
a=rtpmap:101 telephone-event/8000\r\n\
a=rtpmap:110 telephone-event/48000\r\n";

        let lists = MediaNegotiator::build_bridge_codec_lists(
            caller_sdp,
            true,  // caller is WebRTC
            false, // callee is RTP
            &[CodecType::Opus, CodecType::TelephoneEvent],
            CodecSelectionStrategy::default(),
        );

        let caller_dtmf: Vec<_> = lists
            .caller_side
            .iter()
            .filter(|c| c.codec == CodecType::TelephoneEvent)
            .collect();
        assert_eq!(caller_dtmf.len(), 2);
        assert_eq!(caller_dtmf[0].payload_type, 101);
        assert_eq!(caller_dtmf[0].clock_rate, 8000);
        assert_eq!(caller_dtmf[1].payload_type, 110);
        assert_eq!(caller_dtmf[1].clock_rate, 48000);

        let callee_dtmf: Vec<_> = lists
            .callee_side
            .iter()
            .filter(|c| c.codec == CodecType::TelephoneEvent)
            .collect();
        assert_eq!(callee_dtmf.len(), 2);
        assert_eq!(callee_dtmf[0].clock_rate, 8000);
        assert_eq!(callee_dtmf[1].clock_rate, 48000);
    }

    /// Reverse direction: RTP caller → WebRTC callee
    /// Caller offers PCMA first, allow_codecs=[Opus,PCMU,PCMA] →
    /// caller side keeps caller-offered codecs, callee side keeps that order and appends missing codecs.
    #[test]
    fn test_bridge_codecs_rtp_caller_webrtc_callee() {
        let caller_sdp = "v=0\r\n\
o=- 1 1 IN IP4 127.0.0.1\r\n\
s=-\r\n\
t=0 0\r\n\
m=audio 10000 RTP/AVP 8 0 101\r\n\
a=rtpmap:8 PCMA/8000\r\n\
a=rtpmap:0 PCMU/8000\r\n\
a=rtpmap:101 telephone-event/8000\r\n";

        let lists = MediaNegotiator::build_bridge_codec_lists(
            caller_sdp,
            false, // caller is RTP
            true,  // callee is WebRTC
            &[
                CodecType::Opus,
                CodecType::PCMU,
                CodecType::PCMA,
                CodecType::TelephoneEvent,
            ],
            CodecSelectionStrategy::Quality, // append Opus for WebRTC callee
        );

        let caller_audio: Vec<_> = lists.caller_side.iter().filter(|c| !c.is_dtmf()).collect();
        assert_eq!(
            caller_audio[0].codec,
            CodecType::PCMA,
            "Caller side preserves PCMA first from caller SDP"
        );
        assert_eq!(caller_audio[1].codec, CodecType::PCMU);
        assert_eq!(caller_audio.len(), 2);
        assert!(!lists.caller_side.iter().any(|c| c.codec == CodecType::Opus));

        let callee_audio: Vec<_> = lists.callee_side.iter().filter(|c| !c.is_dtmf()).collect();
        // Quality order: Opus > G729 > G722 > G711 → Opus first
        assert_eq!(callee_audio[0].codec, CodecType::Opus);
        assert_eq!(callee_audio[1].codec, CodecType::PCMU);
        assert_eq!(callee_audio[2].codec, CodecType::PCMA);
        assert_eq!(callee_audio.len(), 3);
    }

    #[test]
    fn test_restrict_answer_to_callee_accepted_codecs_preserves_caller_payload_types() {
        let answer_sdp = "v=0\r\n\
o=- 1 1 IN IP4 127.0.0.1\r\n\
s=-\r\n\
t=0 0\r\n\
m=audio 9 UDP/TLS/RTP/SAVPF 96 0 110 126\r\n\
c=IN IP4 0.0.0.0\r\n\
a=mid:0\r\n\
a=sendrecv\r\n\
a=rtcp-mux\r\n\
a=rtpmap:96 opus/48000/2\r\n\
a=fmtp:96 minptime=10;useinbandfec=1\r\n\
a=rtpmap:0 PCMU/8000\r\n\
a=rtpmap:110 telephone-event/48000\r\n\
a=fmtp:110 0-16\r\n\
a=rtpmap:126 telephone-event/8000\r\n\
a=fmtp:126 0-16\r\n";

        let callee_answer = "v=0\r\n\
o=- 1 1 IN IP4 127.0.0.1\r\n\
s=-\r\n\
t=0 0\r\n\
m=audio 9 RTP/AVP 111 0 101\r\n\
c=IN IP4 0.0.0.0\r\n\
a=rtpmap:111 opus/48000/2\r\n\
a=fmtp:111 useinbandfec=1\r\n\
a=rtpmap:0 PCMU/8000\r\n\
a=rtpmap:101 telephone-event/8000\r\n\
a=fmtp:101 0-16\r\n";

        let filtered =
            MediaNegotiator::restrict_answer_to_callee_accepted_codecs(answer_sdp, callee_answer)
                .unwrap();

        assert!(filtered.contains("m=audio 9 UDP/TLS/RTP/SAVPF 96 0 126"));
        assert!(filtered.contains("a=rtpmap:96 opus/48000/2"));
        assert!(filtered.contains("a=rtpmap:0 PCMU/8000"));
        assert!(filtered.contains("a=rtpmap:126 telephone-event/8000"));
        assert!(!filtered.contains("a=rtpmap:110 telephone-event/48000"));
        assert!(!filtered.contains("a=rtpmap:101 telephone-event/8000"));
    }

    /// to_audio_capability converts all known codecs
    #[test]
    fn test_codec_info_to_audio_capability() {
        let codecs = vec![
            CodecInfo {
                payload_type: 0,
                codec: CodecType::PCMU,
                clock_rate: 8000,
                channels: 1,
            },
            CodecInfo {
                payload_type: 8,
                codec: CodecType::PCMA,
                clock_rate: 8000,
                channels: 1,
            },
            CodecInfo {
                payload_type: 9,
                codec: CodecType::G722,
                clock_rate: 8000,
                channels: 1,
            },
            CodecInfo {
                payload_type: 18,
                codec: CodecType::G729,
                clock_rate: 8000,
                channels: 1,
            },
            CodecInfo {
                payload_type: 101,
                codec: CodecType::TelephoneEvent,
                clock_rate: 8000,
                channels: 1,
            },
        ];
        for ci in &codecs {
            assert!(
                ci.to_audio_capability().is_some(),
                "{:?} should convert to AudioCapability",
                ci.codec
            );
        }
    }

    /// RTP caller offers G729+PCMU, WebRTC callee.
    /// common must exclude G729 because WebRTC does not support it.
    #[test]
    fn test_bridge_codecs_common_excludes_transport_unsupported() {
        let caller_sdp = "v=0\r\n\
o=- 1 1 IN IP4 127.0.0.1\r\n\
s=-\r\n\
t=0 0\r\n\
m=audio 10000 RTP/AVP 18 0 101\r\n\
a=rtpmap:18 G729/8000\r\n\
a=rtpmap:0 PCMU/8000\r\n\
a=rtpmap:101 telephone-event/8000\r\n";

        let lists = MediaNegotiator::build_bridge_codec_lists(
            caller_sdp,
            false, // caller is RTP
            true,  // callee is WebRTC
            &[],
            CodecSelectionStrategy::default(),
        );

        // common: only PCMU (both sides support it) + telephone-event
        assert!(
            !lists.common.iter().any(|c| c.codec == CodecType::G729),
            "G729 must NOT be in common (WebRTC does not support it)"
        );
        assert!(
            lists.common.iter().any(|c| c.codec == CodecType::PCMU),
            "PCMU must be in common (both sides support it)"
        );
        assert!(
            lists
                .common
                .iter()
                .any(|c| c.codec == CodecType::TelephoneEvent),
            "TelephoneEvent must be in common"
        );

        let first_audio = lists.common.iter().find(|c| !c.is_dtmf());
        assert!(
            first_audio.is_some(),
            "Common must have at least one audio codec"
        );
        assert_eq!(
            first_audio.unwrap().codec,
            CodecType::PCMU,
            "First common audio codec should be PCMU (G729 excluded)"
        );
    }

    /// RTP caller offers G729+PCMA+PCMU, WebRTC callee.
    /// common should preserve caller's ordering: G729 excluded, PCMA first.
    #[test]
    fn test_bridge_codecs_common_preserves_caller_ordering() {
        let caller_sdp = "v=0\r\n\
o=- 1 1 IN IP4 127.0.0.1\r\n\
s=-\r\n\
t=0 0\r\n\
m=audio 10000 RTP/AVP 18 8 0 101\r\n\
a=rtpmap:18 G729/8000\r\n\
a=rtpmap:8 PCMA/8000\r\n\
a=rtpmap:0 PCMU/8000\r\n\
a=rtpmap:101 telephone-event/8000\r\n";

        let lists = MediaNegotiator::build_bridge_codec_lists(
            caller_sdp,
            false, // caller is RTP
            true,  // callee is WebRTC
            &[],
            CodecSelectionStrategy::default(),
        );

        let common_audio: Vec<_> = lists.common.iter().filter(|c| !c.is_dtmf()).collect();
        assert_eq!(common_audio.len(), 2, "2 common audio codecs: PCMA + PCMU");
        assert_eq!(
            common_audio[0].codec,
            CodecType::PCMA,
            "PCMA must be first in common (caller ordered PCMA before PCMU)"
        );
        assert_eq!(
            common_audio[1].codec,
            CodecType::PCMU,
            "PCMU must be second in common"
        );
        assert!(
            !lists.common.iter().any(|c| c.codec == CodecType::G729),
            "G729 excluded from common"
        );
    }

    /// When both sides are the same transport type, common follows the caller offer
    /// while callee_side can still include additional policy-generated codecs.
    #[test]
    fn test_bridge_codecs_common_identical_when_same_transport() {
        let caller_sdp = "v=0\r\n\
o=- 1 1 IN IP4 127.0.0.1\r\n\
s=-\r\n\
t=0 0\r\n\
m=audio 9 UDP/TLS/RTP/SAVPF 111 0 101\r\n\
a=rtpmap:111 opus/48000/2\r\n\
a=rtpmap:0 PCMU/8000\r\n\
a=rtpmap:101 telephone-event/8000\r\n";

        let lists = MediaNegotiator::build_bridge_codec_lists(
            caller_sdp,
            true, // caller is WebRTC
            true, // callee is WebRTC
            &[],
            CodecSelectionStrategy::default(),
        );

        let common_audio: Vec<_> = lists.common.iter().filter(|c| !c.is_dtmf()).collect();
        let caller_audio: Vec<_> = lists.caller_side.iter().filter(|c| !c.is_dtmf()).collect();
        let callee_audio: Vec<_> = lists.callee_side.iter().filter(|c| !c.is_dtmf()).collect();

        assert_eq!(common_audio.len(), caller_audio.len());
        for (c, a) in common_audio.iter().zip(caller_audio.iter()) {
            assert_eq!(c.codec, a.codec, "common and caller_side must match");
        }
        assert!(
            callee_audio.len() >= common_audio.len(),
            "callee_side can include additional generated codecs"
        );
    }

    /// When allow_codecs explicitly filters to a subset, common should
    /// also reflect that filtering.
    #[test]
    fn test_bridge_codecs_common_respects_allow_codecs() {
        let caller_sdp = "v=0\r\n\
o=- 1 1 IN IP4 127.0.0.1\r\n\
s=-\r\n\
t=0 0\r\n\
m=audio 10000 RTP/AVP 18 8 0 101\r\n\
a=rtpmap:18 G729/8000\r\n\
a=rtpmap:8 PCMA/8000\r\n\
a=rtpmap:0 PCMU/8000\r\n\
a=rtpmap:101 telephone-event/8000\r\n";

        // Only allow PCMU + telephone-event
        let lists = MediaNegotiator::build_bridge_codec_lists(
            caller_sdp,
            false, // caller is RTP
            true,  // callee is WebRTC
            &[CodecType::PCMU, CodecType::TelephoneEvent],
            CodecSelectionStrategy::default(),
        );

        let common_audio: Vec<_> = lists.common.iter().filter(|c| !c.is_dtmf()).collect();
        assert_eq!(
            common_audio.len(),
            1,
            "Only PCMU allowed, so only PCMU in common"
        );
        assert_eq!(common_audio[0].codec, CodecType::PCMU);
        assert!(!lists.common.iter().any(|c| c.codec == CodecType::G729));
        assert!(!lists.common.iter().any(|c| c.codec == CodecType::PCMA));
    }

    /// PSTN caller offers AMR/EVS codecs at dynamic PTs 96/111.
    /// These PTs already have rtpmap entries with unrecognized codec names.
    /// The codec parser must NOT fall back to mapping PT 96/111 to Opus,
    /// because the PTs were already assigned by the caller.
    #[test]
    fn test_bridge_codecs_ignores_unrecognized_rtpmap_entries() {
        let caller_sdp = "v=0\r\n\
o=- 1777370486 1777370486 IN IP4 58.246.19.74\r\n\
s=-\r\n\
c=IN IP4 58.246.19.74\r\n\
t=0 0\r\n\
m=audio 16844 RTP/AVP 98 96 111 106 18 8 0 100\r\n\
a=rtpmap:98 AMR-WB/16000/1\r\n\
a=rtpmap:96 AMR/8000/1\r\n\
a=rtpmap:111 EVS/16000\r\n\
a=rtpmap:106 EVS/16000\r\n\
a=rtpmap:18 G729/8000\r\n\
a=rtpmap:8 PCMA/8000\r\n\
a=rtpmap:0 PCMU/8000\r\n\
a=rtpmap:100 telephone-event/8000\r\n";

        let lists = MediaNegotiator::build_bridge_codec_lists(
            caller_sdp,
            false, // caller is RTP (PSTN)
            true,  // callee is WebRTC
            &[],
            CodecSelectionStrategy::default(),
        );

        assert!(
            !lists.caller_side.iter().any(|c| c.payload_type == 96),
            "PT 96 must NOT appear (it was AMR, not Opus)"
        );
        assert!(
            !lists.caller_side.iter().any(|c| c.payload_type == 111),
            "PT 111 must NOT appear (it was EVS, not Opus)"
        );
        assert!(
            !lists.caller_side.iter().any(|c| c.payload_type == 98),
            "PT 98 must NOT appear (it was AMR-WB)"
        );
        assert!(
            !lists.caller_side.iter().any(|c| c.payload_type == 106),
            "PT 106 must NOT appear (it was EVS)"
        );
        assert!(
            !lists.common.iter().any(|c| c.payload_type == 96),
            "Common must NOT include PT 96"
        );
        assert!(
            !lists.common.iter().any(|c| c.payload_type == 111),
            "Common must NOT include PT 111"
        );

        // Supported codecs must appear with correct caller PTs
        let has_g729 = lists
            .caller_side
            .iter()
            .any(|c| c.codec == CodecType::G729 && c.payload_type == 18);
        assert!(has_g729, "G729 at PT 18 must appear in caller_side");
        let has_pcma = lists
            .caller_side
            .iter()
            .any(|c| c.codec == CodecType::PCMA && c.payload_type == 8);
        assert!(has_pcma, "PCMA at PT 8 must appear in caller_side");
        let has_pcmu = lists
            .caller_side
            .iter()
            .any(|c| c.codec == CodecType::PCMU && c.payload_type == 0);
        assert!(has_pcmu, "PCMU at PT 0 must appear in caller_side");

        // common excludes G729 (WebRTC doesn't support it)
        let common_g729 = lists.common.iter().any(|c| c.codec == CodecType::G729);
        assert!(!common_g729, "G729 must NOT be in common (WebRTC callee)");
        let common_pcma = lists.common.iter().any(|c| c.codec == CodecType::PCMA);
        assert!(common_pcma, "PCMA must be in common");
        let common_pcmu = lists.common.iter().any(|c| c.codec == CodecType::PCMU);
        assert!(common_pcmu, "PCMU must be in common");
        let common_dtmf = lists
            .common
            .iter()
            .any(|c| c.codec == CodecType::TelephoneEvent);
        assert!(common_dtmf, "TelephoneEvent must be in common");

        // Verify no Opus codecs are created from PT 96/111
        assert!(
            !lists.caller_side.iter().any(|c| c.codec == CodecType::Opus),
            "Opus must NOT appear in caller_side (PSTN didn't offer Opus)"
        );
        assert!(
            !lists.common.iter().any(|c| c.codec == CodecType::Opus),
            "Opus must NOT appear in common (PSTN didn't offer Opus)"
        );
    }

    #[test]
    fn test_codec_selection_strategy_serde() {
        // Verify serialization round-trip
        let perf = CodecSelectionStrategy::Performance;
        let json = serde_json::to_string(&perf).unwrap();
        assert_eq!(json, "\"performance\"");
        let back: CodecSelectionStrategy = serde_json::from_str(&json).unwrap();
        assert_eq!(back, CodecSelectionStrategy::Performance);

        let qual = CodecSelectionStrategy::Quality;
        let json = serde_json::to_string(&qual).unwrap();
        assert_eq!(json, "\"quality\"");
        let back: CodecSelectionStrategy = serde_json::from_str(&json).unwrap();
        assert_eq!(back, CodecSelectionStrategy::Quality);
    }

    #[test]
    fn test_performance_strategy_keeps_only_caller_codecs() {
        let caller_sdp = "v=0\r\n\
o=- 1 1 IN IP4 127.0.0.1\r\n\
s=-\r\n\
t=0 0\r\n\
m=audio 10000 RTP/AVP 0 8 101\r\n\
a=rtpmap:0 PCMU/8000\r\n\
a=rtpmap:8 PCMA/8000\r\n\
a=rtpmap:101 telephone-event/8000\r\n";

        // Performance (default): keep only caller's codecs
        let lists = MediaNegotiator::build_bridge_codec_lists(
            caller_sdp,
            false, // caller RTP
            false, // callee RTP
            &[CodecType::PCMU, CodecType::PCMA, CodecType::TelephoneEvent],
            CodecSelectionStrategy::Performance,
        );

        let callee_audio: Vec<_> = lists.callee_side.iter().filter(|c| !c.is_dtmf()).collect();
        assert_eq!(callee_audio.len(), 2, "Performance: only caller's codecs");
        assert_eq!(
            callee_audio[0].codec,
            CodecType::PCMU,
            "PCMU first (caller order)"
        );
        assert_eq!(
            callee_audio[1].codec,
            CodecType::PCMA,
            "PCMA second (caller order)"
        );
        // G722/G729 should NOT appear (not offered by caller)
        assert!(!callee_audio.iter().any(|c| c.codec == CodecType::G722));
        assert!(!callee_audio.iter().any(|c| c.codec == CodecType::G729));
    }

    #[test]
    fn test_quality_strategy_appends_and_orders() {
        let caller_sdp = "v=0\r\n\
o=- 1 1 IN IP4 127.0.0.1\r\n\
s=-\r\n\
t=0 0\r\n\
m=audio 10000 RTP/AVP 0 8 101\r\n\
a=rtpmap:0 PCMU/8000\r\n\
a=rtpmap:8 PCMA/8000\r\n\
a=rtpmap:101 telephone-event/8000\r\n";

        // Quality: append missing codecs, order by quality
        let lists = MediaNegotiator::build_bridge_codec_lists(
            caller_sdp,
            false, // caller RTP
            false, // callee RTP
            &[
                CodecType::PCMU,
                CodecType::PCMA,
                CodecType::G722,
                CodecType::TelephoneEvent,
            ],
            CodecSelectionStrategy::Quality,
        );

        let callee_audio: Vec<_> = lists.callee_side.iter().filter(|c| !c.is_dtmf()).collect();
        // Caller offered PCMU, PCMA; quality appends G722
        // Quality order: G722 > PCMU > PCMA
        assert_eq!(
            callee_audio.len(),
            3,
            "Quality: caller codecs + appended G722"
        );
        assert_eq!(
            callee_audio[0].codec,
            CodecType::G722,
            "G722 first (quality order)"
        );
        assert_eq!(callee_audio[1].codec, CodecType::PCMU, "PCMU second");
        assert_eq!(callee_audio[2].codec, CodecType::PCMA, "PCMA third");
    }
}