str0m 0.18.0

WebRTC library in Sans-IO style
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
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
//! Strategy that amends the [`Rtc`] via SDP OFFER/ANSWER negotiation.

use std::fmt;
use std::ops::{Deref, DerefMut};

use crate::Rtc;
use crate::RtcError;
use crate::channel::ChannelId;
use crate::crypto::Fingerprint;
use crate::format::CodecConfig;
use crate::format::PayloadParams;
use crate::media::{Media, Rids, Simulcast};
use crate::packet::MediaKind;
use crate::rtp_::MidRid;
use crate::rtp_::Rid;
use crate::rtp_::{Direction, Extension, ExtensionMap, Mid, Pt, Ssrc};
use crate::sctp::ChannelConfig;
use crate::sctp::RtcSctp;
use crate::sdp::{self, MediaAttribute, MediaLine, MediaType, Msid, Sdp};
use crate::sdp::{Proto, SessionAttribute, Setup, SimulcastGroups};
use crate::session::Session;
use crate::{Candidate, IceCreds};
use str0m_proto::Id;

pub use crate::sdp::{SdpAnswer, SdpOffer};
use crate::streams::{DEFAULT_RTX_CACHE_DURATION, DEFAULT_RTX_RATIO_CAP, Streams};

/// Changes to the Rtc via SDP Offer/Answer dance.
pub struct SdpApi<'a> {
    rtc: &'a mut Rtc,
    changes: Changes,
}

impl<'a> SdpApi<'a> {
    pub(crate) fn new(rtc: &'a mut Rtc) -> Self {
        SdpApi {
            rtc,
            changes: Changes::default(),
        }
    }

    /// Accept an [`SdpOffer`] from the remote peer. If this call returns successfully, the
    /// changes will have been made to the session. The resulting [`SdpAnswer`] should be
    /// sent to the remote peer.
    ///
    /// <b>Note. Pending changes from a previous non-completed [`SdpApi`][super::SdpApi] will be
    /// considered rolled back when calling this function.</b>
    ///
    /// The incoming SDP is validated in various ways which can cause this call to fail.
    /// Example of such problems would be an SDP without any m-lines, missing `a=fingerprint`
    /// or if `a=group` doesn't match the number of m-lines.
    ///
    /// ```no_run
    /// # use std::time::Instant;
    /// # use str0m::Rtc;
    /// # use str0m::change::{SdpOffer};
    /// // obtain offer from remote peer.
    /// let json_offer: &[u8] = todo!();
    /// let offer: SdpOffer = serde_json::from_slice(json_offer).unwrap();
    ///
    /// let mut rtc = Rtc::new(Instant::now());
    /// let answer = rtc.sdp_api().accept_offer(offer).unwrap();
    ///
    /// // send json_answer to remote peer.
    /// let json_answer = serde_json::to_vec(&answer).unwrap();
    /// ```
    pub fn accept_offer(self, offer: SdpOffer) -> Result<SdpAnswer, RtcError> {
        debug!("Accept offer");

        // Invalidate any outstanding PendingOffer.
        self.rtc.next_change_id();

        if offer.media_lines.is_empty() {
            return Err(RtcError::RemoteSdp("No m-lines in offer".into()));
        }

        if self.rtc.ice.ice_lite() && offer.session.ice_lite() {
            return Err(RtcError::RemoteSdp(
                "Both peers being ICE-Lite not supported".into(),
            ));
        }

        add_ice_details(self.rtc, &offer, None)?;

        if self.rtc.remote_fingerprint.is_none() {
            if let Some(f) = offer.fingerprint() {
                self.rtc.remote_fingerprint = Some(f);
            } else {
                self.rtc.disconnect();
                return Err(RtcError::RemoteSdp("missing a=fingerprint".into()));
            }
        }

        if !self.rtc.dtls.is_inited() {
            // The side that makes the first offer is the controlling side, unless they
            // are ICE Lite, in which case the roles are reversed (see RFC 5245).
            self.rtc.ice.set_controlling(offer.session.ice_lite());
        }

        // Ensure setup=active/passive is corresponding remote and init dtls.
        init_dtls(self.rtc, &offer)?;

        // Extract a=sctp-init from remote offer before apply_offer consumes it.
        let remote_sctp_init = offer.sctp_init().map(|v| v.to_owned());

        let has_snap = process_remote_sctp_init(&mut self.rtc.sctp, remote_sctp_init.as_deref())?;

        // Modify session with offer.
        apply_offer(&mut self.rtc.session, offer)?;

        // Handle potentially new m=application line.
        let client = self.rtc.dtls.is_active().expect("DTLS active to be set");

        // Generate local sctp-init for the answer:
        // When the remote included a=sctp-init, we reciprocate (§5.4).
        if has_snap && !self.rtc.sctp.is_inited() && !self.rtc.sctp.ensure_local_snap_init() {
            warn!("Failed to generate SNAP INIT chunk, degrading to non-SNAP");
        }

        if self.rtc.session.app().is_some() {
            let init_data = self.rtc.sctp.build_snap_init_data();
            self.rtc.try_init_sctp(client, init_data)?;
        }

        let params = AsSdpParams::new(self.rtc, None);
        let sdp = as_sdp(&self.rtc.session, params);

        debug!("Create answer");
        Ok(sdp.into())
    }

    /// Accept an answer to a previously created [`SdpOffer`].
    ///
    /// This function returns an [`RtcError::ChangesOutOfOrder`] if we have created and applied another
    /// [`SdpApi`][super::SdpApi] before calling this. The same also happens if we use
    /// [`SdpApi::accept_offer()`] before using this pending instance.
    ///
    /// ```no_run
    /// # use std::time::Instant;
    /// # use str0m::Rtc;
    /// # use str0m::media::{MediaKind, Direction};
    /// # use str0m::change::SdpAnswer;
    /// let mut rtc = Rtc::new(Instant::now());
    ///
    /// let mut changes = rtc.sdp_api();
    /// let mid = changes.add_media(MediaKind::Audio, Direction::SendOnly, None, None, None);
    /// let (offer, pending) = changes.apply().unwrap();
    ///
    /// // send offer to remote peer, receive answer back
    /// let answer: SdpAnswer = todo!();
    ///
    /// rtc.sdp_api().accept_answer(pending, answer).unwrap();
    /// ```
    pub fn accept_answer(
        self,
        mut pending: SdpPendingOffer,
        answer: SdpAnswer,
    ) -> Result<(), RtcError> {
        debug!("Accept answer");

        // Ensure we don't use the wrong changes below. We must use that of pending.
        drop(self.changes);

        if !self.rtc.is_correct_change_id(pending.change_id) {
            return Err(RtcError::ChangesOutOfOrder);
        }

        if self.rtc.ice.ice_lite() && answer.session.ice_lite() {
            return Err(RtcError::RemoteSdp(
                "Both peers being ICE-Lite not supported".into(),
            ));
        }

        add_ice_details(self.rtc, &answer, Some(&pending))?;

        // Ensure setup=active/passive is corresponding remote and init dtls.
        init_dtls(self.rtc, &answer)?;

        if self.rtc.remote_fingerprint.is_none() {
            if let Some(f) = answer.fingerprint() {
                self.rtc.remote_fingerprint = Some(f);
            } else {
                self.rtc.disconnect();
                return Err(RtcError::RemoteSdp("missing a=fingerprint".into()));
            }
        }

        // Extract a=sctp-init from remote answer before apply_answer consumes it.
        let remote_sctp_init = answer.sctp_init().map(|v| v.to_owned());

        let expected_snap_answer =
            !self.rtc.sctp.is_inited() && self.rtc.sctp.local_sctp_init_for_sdp().is_some();

        // Validate or cache the remote value before mutating the session. This
        // keeps a bad re-offer/re-answer from partially applying local state.
        let has_snap = process_remote_sctp_init(&mut self.rtc.sctp, remote_sctp_init.as_deref())?;

        // Split out new channels, since that is not handled by the Session.
        let new_channels = pending.changes.take_new_channels();

        // Modify session with answer
        apply_answer(&mut self.rtc.session, pending.changes, answer)?;

        // Handle potentially new m=application line.
        let client = self.rtc.dtls.is_active().expect("DTLS to be inited");

        if expected_snap_answer && !has_snap {
            debug!("Remote answer did not accept SNAP, falling back to regular SCTP handshake");
            self.rtc.sctp.disable_pending_snap();
        }

        if self.rtc.session.app().is_some() {
            let init_data = self.rtc.sctp.build_snap_init_data();
            self.rtc.try_init_sctp(client, init_data)?;
        }

        for (id, config) in new_channels {
            self.rtc.chan.confirm(id, config);
        }

        Ok(())
    }

    /// Test if any changes have been made.
    ///
    /// If changes have been made, nothing happens until we call [`SdpApi::apply()`].
    ///
    /// ```
    /// # #[cfg(feature = "openssl")] {
    /// # use std::time::Instant;
    /// # use str0m::{Rtc, media::MediaKind, media::Direction};
    /// let mut rtc = Rtc::new(Instant::now());
    ///
    /// let mut changes = rtc.sdp_api();
    /// assert!(!changes.has_changes());
    ///
    /// let mid = changes.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None);
    /// assert!(changes.has_changes());
    /// # }
    /// ```
    pub fn has_changes(&self) -> bool {
        !self.changes.0.is_empty()
    }

    /// Add audio or video media and get the `mid` that will be used.
    ///
    /// Each call will result in a new m-line in the offer identified by the [`Mid`].
    ///
    /// The mid is not valid to use until the SDP offer-answer dance is complete and
    /// the mid been advertised via [`Event::MediaAdded`][crate::Event::MediaAdded].
    ///
    /// * `stream_id` is used to synchronize media. It is `a=msid-semantic: WMS <streamId>` line in SDP.
    /// * `track_id` is becomes both the track id in `a=msid <streamId> <trackId>` as well as the
    ///   CNAME in the RTP SDES.
    ///
    /// ```
    /// # #[cfg(feature = "openssl")] {
    /// # use std::time::Instant;
    /// # use str0m::{Rtc, media::MediaKind, media::Direction};
    /// let mut rtc = Rtc::new(Instant::now());
    ///
    /// let mut changes = rtc.sdp_api();
    ///
    /// let mid = changes.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None);
    /// # }
    /// ```
    pub fn add_media(
        &mut self,
        kind: MediaKind,
        dir: Direction,
        stream_id: Option<String>,
        track_id: Option<String>,
        simulcast: Option<crate::media::Simulcast>,
    ) -> Mid {
        let mid = self.rtc.new_mid();

        // https://www.rfc-editor.org/rfc/rfc8830
        // msid-id = 1*64token-char
        fn is_token_char(c: &char) -> bool {
            // token-char = %x21 / %x23-27 / %x2A-2B / %x2D-2E / %x30-39
            // / %x41-5A / %x5E-7E
            let u = *c as u32;
            u == 0x21
                || (0x23..=0x27).contains(&u)
                || (0x2a..=0x2b).contains(&u)
                || (0x2d..=0x2e).contains(&u)
                || (0x30..=0x39).contains(&u)
                || (0x41..=0x5a).contains(&u)
                || (0x5e..0x7e).contains(&u)
        }

        let stream_id = if let Some(stream_id) = stream_id {
            stream_id.chars().filter(is_token_char).take(64).collect()
        } else {
            Id::<20>::random().to_string()
        };

        let track_id = if let Some(track_id) = track_id {
            track_id.chars().filter(is_token_char).take(64).collect()
        } else {
            Id::<20>::random().to_string()
        };

        let mut ssrcs = Vec::new();

        // Main SSRC, not counting RTX.
        let main_ssrc_count = simulcast.as_ref().map(|s| s.send.len()).unwrap_or(1);

        for _ in 0..main_ssrc_count {
            let rtx = kind.is_video().then(|| self.rtc.session.streams.new_ssrc());
            ssrcs.push((self.rtc.session.streams.new_ssrc(), rtx));
        }

        // TODO: let user configure stream/track name.
        let msid = Msid {
            stream_id,
            track_id: track_id.clone(),
        };

        let add = AddMedia {
            mid,
            cname: track_id,
            msid,
            kind,
            dir,
            ssrcs,
            simulcast,

            // Added later
            pts: vec![],
            exts: ExtensionMap::empty(),
            index: 0,
        };

        self.changes.0.push(Change::AddMedia(add));
        mid
    }

    /// Change the direction of an already existing media.
    ///
    /// All media have a direction. The media can be added by this side via
    /// [`SdpApi::add_media()`] or by the remote peer. Either way, the direction
    /// of the line can be changed at any time.
    ///
    /// It's possible to set the direction [`Direction::Inactive`] for media that
    /// will not be used by the session anymore.
    ///
    /// If the direction is set for media that doesn't exist, or if the direction is
    /// the same that's already set [`SdpApi::apply()`] not require a negotiation.
    pub fn set_direction(&mut self, mid: Mid, dir: Direction) {
        let changed = self.rtc.session.set_direction(mid, dir);

        if changed {
            self.changes.0.push(Change::Direction(mid, dir));
        }
    }

    /// Add a new reliable ordered data channel and get the `id` that will be used.
    ///
    /// Use `add_channel_with_config` when unreliable or unordered data channels are preferred.
    ///
    /// The first ever data channel added to a WebRTC session results in a media
    /// of a special "application" type in the SDP. The m-line is for a SCTP association over
    /// DTLS, and all data channels are multiplexed over this single association.
    ///
    /// That means only the first ever `add_channel` will result in an [`SdpOffer`].
    /// Consecutive channels will be opened without needing a negotiation.
    ///
    /// The label is used to identify the data channel to the remote peer. This is mostly
    /// useful when multiple channels are in use at the same time.
    ///
    /// ```
    /// # #[cfg(feature = "openssl")] {
    /// # use std::time::Instant;
    /// # use str0m::Rtc;
    /// let mut rtc = Rtc::new(Instant::now());
    ///
    /// let mut changes = rtc.sdp_api();
    ///
    /// let cid = changes.add_channel("my special channel".to_string());
    /// # }
    /// ```
    pub fn add_channel(&mut self, label: String) -> ChannelId {
        self.add_channel_with_config(ChannelConfig {
            label,
            ..Default::default()
        })
    }

    /// Add a new data channel with a given configuration and get the `id` that will be used.
    ///
    /// Refer to `add_channel` for more details.
    ///
    /// ```
    /// # #[cfg(feature = "openssl")] {
    /// # use std::time::Instant;
    /// # use str0m::{channel::{ChannelConfig, Reliability}, Rtc};
    /// let mut rtc = Rtc::new(Instant::now());
    ///
    /// let mut changes = rtc.sdp_api();
    ///
    /// let cid = changes.add_channel_with_config(ChannelConfig {
    ///     label: "my special channel".to_string(),
    ///     reliability: Reliability::MaxRetransmits{ retransmits: 0 },
    ///     ordered: false,
    ///     ..Default::default()
    /// });
    /// # }
    /// ```
    pub fn add_channel_with_config(&mut self, config: ChannelConfig) -> ChannelId {
        let has_media = self.rtc.session.app().is_some();
        let changes_contains_add_app = self.changes.contains_add_app();

        if !has_media && !changes_contains_add_app {
            let mid = self.rtc.new_mid();
            self.changes.0.push(Change::AddApp(mid));
        }

        let id = self.rtc.chan.new_channel(&config);

        self.changes.0.push(Change::AddChannel((id, config)));

        id
    }

    /// Perform an ICE restart.
    ///
    /// Only one ICE restart can be pending at the time. Calling this repeatedly removes any other
    /// pending ICE restart.
    ///
    /// The local ICE candidates can be kept as is, or be cleared out, in which case new ice
    /// candidates must be added via [`Rtc::add_local_candidate`] before connectivity can be
    /// re-established.
    ///
    /// Returns the new ICE credentials that will be used going forward.
    pub fn ice_restart(&mut self, keep_local_candidates: bool) -> IceCreds {
        self.changes
            .retain(|c| !matches!(c, Change::IceRestart(_, _)));

        let new_creds = IceCreds::new();
        self.changes
            .push(Change::IceRestart(new_creds.clone(), keep_local_candidates));

        new_creds
    }

    /// Attempt to apply the changes made.
    ///
    /// If this returns [`SdpOffer`], the caller the changes are
    /// not happening straight away, and the caller is expected to do a negotiation with the remote
    /// peer and apply the answer using [`SdpPendingOffer`].
    ///
    /// In case this returns `None`, there either were no changes, or the changes could be applied
    /// without doing a negotiation. Specifically for additional [`SdpApi::add_channel()`]
    /// after the first, there is no negotiation needed.
    ///
    /// The [`SdpPendingOffer`] is valid until the next time we call this function, at which
    /// point using it will raise an error. Using [`SdpApi::accept_offer()`] will also invalidate
    /// the current [`SdpPendingOffer`].
    ///
    /// ```
    /// # #[cfg(feature = "openssl")] {
    /// # use std::time::Instant;
    /// # use str0m::Rtc;
    /// let mut rtc = Rtc::new(Instant::now());
    ///
    /// let changes = rtc.sdp_api();
    /// assert!(changes.apply().is_none());
    /// # }
    /// ```
    pub fn apply(self) -> Option<(SdpOffer, SdpPendingOffer)> {
        if self.changes.is_empty() {
            return None;
        }

        let change_id = self.rtc.next_change_id();

        let requires_negotiation = self.changes.0.iter().any(requires_negotiation);

        if requires_negotiation {
            let offer = create_offer(self.rtc, &self.changes);
            let pending = SdpPendingOffer {
                change_id,
                changes: self.changes,
            };
            debug!("Create offer");
            Some((offer, pending))
        } else {
            debug!("Apply direct changes");
            apply_direct_changes(self.rtc, self.changes);
            None
        }
    }

    /// Combines the modifications made in [`SdpApi`] with those in [`SdpPendingOffer`].
    ///
    /// This function merges the changes present in [`SdpApi`] with the changes
    /// in [`SdpPendingOffer`]. In result this [`SdpApi`] will incorporate modifications
    /// from both the previous [`SdpPendingOffer`] and any newly added changes.
    ///
    /// ## Example
    ///
    /// ```no_run
    /// # use std::time::Instant;
    /// # use str0m::media::{Direction, MediaKind};
    /// # use str0m::Rtc;
    /// let mut rtc = Rtc::new(Instant::now());
    /// let mut changes = rtc.sdp_api();
    /// changes.add_media(MediaKind::Audio, Direction::SendOnly, None, None, None);
    /// let (_offer, pending) = changes.apply().unwrap();
    ///
    /// let mut changes = rtc.sdp_api();
    /// changes.add_media(MediaKind::Video, Direction::SendOnly, None, None, None);
    /// changes.merge(pending);
    ///
    /// // This `SdpOffer` will have changes from the first `SdpPendingChanges`
    /// // and new changes from `SdpApi`
    /// let (_offer, pending) = changes.apply().unwrap();
    /// ```
    pub fn merge(&mut self, mut pending_offer: SdpPendingOffer) {
        pending_offer.retain_relevant(self.rtc);

        // Prepend the original pending changes before the current SdpApi's own changes.
        //
        // AddMedia / AddApp entries from the pending offer carry already-allocated MIDs
        // that the remote peer may have committed to specific m-line positions. They must
        // appear before any new changes so that as_new_medias() assigns them the same
        // indices as in the original offer.
        pending_offer.changes.0.append(&mut self.changes.0);
        self.changes.0 = pending_offer.changes.0;
    }
}

/// Pending offer from a previous [`Rtc::sdp_api()`] call.
///
/// This allows us to accept a remote answer. No changes have been made to the session
/// before we call [`SdpApi::accept_answer()`], which means that rolling back a
/// change is as simple as dropping this instance.
///
/// ```no_run
/// # use std::time::Instant;
/// # use str0m::Rtc;
/// # use str0m::media::{MediaKind, Direction};
/// # use str0m::change::SdpAnswer;
/// let mut rtc = Rtc::new(Instant::now());
///
/// let mut changes = rtc.sdp_api();
/// let mid = changes.add_media(MediaKind::Audio, Direction::SendOnly, None, None, None);
/// let (offer, pending) = changes.apply().unwrap();
///
/// // send offer to remote peer, receive answer back
/// let answer: SdpAnswer = todo!();
///
/// rtc.sdp_api().accept_answer(pending, answer).unwrap();
/// ```
pub struct SdpPendingOffer {
    change_id: usize,
    changes: Changes,
}

impl SdpPendingOffer {
    /// Retains only the relevant changes in the `changes` vector based on the provided `Rtc` instance.
    ///
    /// This function filters the vector of `Change` instances stored in the current object and retains
    /// only those changes that are considered relevant with respect to the provided `Rtc` instance.
    fn retain_relevant(&mut self, rtc: &Rtc) {
        fn is_relevant(rtc: &Rtc, c: &Change) -> bool {
            match c {
                Change::AddMedia(v) => rtc.media(v.mid).is_none(),
                Change::AddApp(_) => rtc.session.app().is_none(),
                Change::AddChannel(v) => rtc.chan.stream_id_by_channel_id(v.0).is_none(),
                Change::Direction(m, d) => {
                    // If mid is missing, this is not relevant.
                    rtc.media(*m).map(|m| m.direction() != *d).unwrap_or(false)
                }
                Change::IceRestart(v, _) => rtc.ice.local_credentials() != v,
            }
        }

        self.changes.retain(|c| is_relevant(rtc, c));
    }
}

#[derive(Default)]
pub(crate) struct Changes(pub Vec<Change>);

impl Changes {
    /// Details of the active ICE restart, if any.
    ///
    /// Returns the new local ICE credentials and the whether to keep local ICE candidates if an
    /// ICE restart has been initiated in the offer, otherwise [`None`].
    fn ice_restart(&self) -> Option<(IceCreds, bool)> {
        self.iter().find_map(|c| match c {
            Change::IceRestart(creds, keep_local_candidates) => {
                Some((creds.clone(), *keep_local_candidates))
            }
            _ => None,
        })
    }
}

#[derive(Debug)]
#[allow(clippy::large_enum_variant)]
pub(crate) enum Change {
    AddMedia(AddMedia),
    AddApp(Mid),
    AddChannel((ChannelId, ChannelConfig)),
    Direction(Mid, Direction),
    IceRestart(IceCreds, bool),
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct AddMedia {
    pub mid: Mid,
    pub cname: String,
    pub msid: Msid,
    pub kind: MediaKind,
    pub dir: Direction,
    pub ssrcs: Vec<(Ssrc, Option<Ssrc>)>,
    pub simulcast: Option<Simulcast>,

    // pts and index are filled in when creating the SDP OFFER.
    // The default PT order is set by the Session (BUNDLE).
    // TODO: We can make this configurable here too.
    pub pts: Vec<Pt>,
    pub exts: ExtensionMap,
    pub index: usize,
}

impl Deref for Changes {
    type Target = Vec<Change>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for Changes {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

fn requires_negotiation(c: &Change) -> bool {
    match c {
        Change::IceRestart(_, _) => true,
        Change::AddMedia(_) => true,
        Change::AddApp(_) => true,
        Change::AddChannel(_) => false,
        Change::Direction(_, _) => true,
    }
}

fn apply_direct_changes(rtc: &mut Rtc, mut changes: Changes) {
    // Split out new channels, since that is not handled by the Session.
    let new_channels = changes.take_new_channels();

    for (id, config) in new_channels {
        rtc.chan.confirm(id, config);
    }
}

fn create_offer(rtc: &mut Rtc, changes: &Changes) -> SdpOffer {
    if !rtc.dtls.is_inited() {
        // The side that makes the first offer is the controlling side, unless they
        // are ICE Lite, in which case the roles are reversed (see RFC 5245).
        rtc.ice.set_controlling(!rtc.ice.ice_lite());
    }

    // Generate local sctp-init for SNAP if enabled and we have/will have an app m-line.
    if rtc.sctp.snap_enabled()
        && (rtc.session.app().is_some() || changes.contains_add_app())
        && !rtc.sctp.is_inited()
        && !rtc.sctp.ensure_local_snap_init()
    {
        warn!("Failed to generate SNAP INIT chunk, degrading to non-SNAP");
    }

    let params = AsSdpParams::new(rtc, Some(changes));
    let sdp = as_sdp(&rtc.session, params);

    sdp.into()
}

fn add_ice_details(
    rtc: &mut Rtc,
    sdp: &Sdp,
    pending: Option<&SdpPendingOffer>,
) -> Result<(), RtcError> {
    let Some(creds) = sdp.ice_creds() else {
        return Err(RtcError::RemoteSdp("missing a=ice-ufrag/pwd".into()));
    };

    // If we are handling an **offer** from the remote, differing ICE credentials indicate an ICE
    // restart initiated by the remote.
    //
    // If we are handling an **answer** from the remote, differing ICE credentials indicate an
    // acceptance of an ICE restart we requested.
    let ice_restart = match rtc.ice.remote_credentials() {
        Some(v) => *v != creds,
        None => false,
    };
    if ice_restart {
        let (new_local_creds, keep_local_candidates) = if let Some(pending) = pending {
            // Since we have a pending, this is an answer to our offer.
            pending.changes.ice_restart().ok_or_else(||
                // Answer contained changed remote creds, indicating an ice restart
                // but since we have no pending ice-creds, we didn't initiate it
                // Ice restart in an ANSWER breaks spec.
                RtcError::RemoteSdp(
                    "Ice restart in answer without one in the preceeding offer".into(),
                ))?
        } else {
            // The remote OFFER had an ice restart, and we need to respond with
            // new credentials in the ANSWER.
            (IceCreds::new(), true)
        };

        rtc.ice
            .ice_restart(new_local_creds.clone(), keep_local_candidates);
    }

    rtc.ice.set_remote_credentials(creds);

    for r in sdp.ice_candidates() {
        rtc.ice.add_remote_candidate(r.clone());
    }

    Ok(())
}

fn init_dtls(rtc: &mut Rtc, remote_sdp: &Sdp) -> Result<(), RtcError> {
    let setup = match remote_sdp.setup() {
        Some(v) => match v {
            // Remote being ActPass, we take Passive role.
            Setup::ActPass => Setup::Passive,
            _ => v.invert(),
        },

        None => {
            warn!("Missing a=setup line");
            Setup::Passive
        }
    };

    let active = setup == Setup::Active;
    rtc.init_dtls(active)?;

    Ok(())
}

/// Shared logic for processing a remote `a=sctp-init` attribute from an offer or answer.
///
/// Returns `true` if this is a new SNAP negotiation (remote init was accepted),
/// `false` otherwise.
///
/// The remote init bytes are stored in `RtcSctp.snap_init` for §5.6
/// re-offer validation.
///
/// When the remote includes `a=sctp-init`, we always accept and reciprocate —
/// Section 5.4 of draft-hancke-tsvwg-snap says the answerer MAY include the
/// attribute, and doing so is beneficial.
///
/// When an initial answer omits or rejects `a=sctp-init`, callers are expected
/// to fall back to a regular SCTP handshake.
fn process_remote_sctp_init(
    sctp: &mut RtcSctp,
    remote_init: Option<&str>,
) -> Result<bool, RtcError> {
    if let Some(remote_init_str) = remote_init {
        if sctp.is_inited() {
            // §5.6: SCTP already established — remote MUST re-send the
            // same sctp-init value on subsequent offers/answers.
            match sctp.snap_remote_init_string() {
                Some(cached) if cached == remote_init_str => {
                    debug!("Remote re-sent expected a=sctp-init for established association");
                }
                Some(_) => {
                    return Err(RtcError::RemoteSdp(
                        "Changed a=sctp-init for existing SCTP association".into(),
                    ));
                }
                None => {
                    // SCTP was established without SNAP but the remote is now
                    // sending a=sctp-init. We can't transition to SNAP
                    // mid-session, so just ignore it.
                    debug!("Ignoring a=sctp-init for non-SNAP established SCTP association");
                }
            }
            Ok(false)
        } else if sctp.set_remote_snap_init_string(remote_init_str) {
            Ok(true)
        } else {
            debug!("Ignoring malformed a=sctp-init");
            Ok(false)
        }
    } else if sctp.is_snap_established() {
        Err(RtcError::RemoteSdp(
            "Missing a=sctp-init for established SNAP SCTP association".into(),
        ))
    } else {
        Ok(false)
    }
}

fn as_sdp(session: &Session, params: AsSdpParams) -> Sdp {
    let (media_lines, mids, stream_ids) = {
        let mut v = as_media_lines(session);

        let mut new_lines = vec![];

        // When creating new m-lines from the pending changes, the m-line index starts from this.
        let new_index_start = v.len();

        // If there are additions in the pending changes, prepend them now.
        if let Some(pending) = params.pending {
            new_lines = pending
                .as_new_medias(new_index_start, &session.codec_config, &session.exts)
                .collect();
        }

        // Add potentially new m-lines to the existing ones.
        v.extend(new_lines.iter().map(|n| n as &dyn AsSdpMediaLine));

        // Turn into sdp::MediaLine (m-line).
        let mut lines = v
            .iter()
            .map(|m| {
                // Candidates should only be in the first BUNDLE mid
                let include_candidates = m.index() == 0;

                let attrs = params.media_attributes(include_candidates);

                // Already made send stream SSRCs
                let mut ssrcs = session.streams.ssrcs_tx(m.mid());

                // Merged with pending stream SSRCs
                if let Some(pending) = params.pending {
                    ssrcs.extend(pending.ssrcs_for_mid(m.mid()))
                }

                let params: Vec<_> = session
                    .codec_config
                    .all_for_kind(m.kind())
                    .cloned()
                    .collect();

                m.as_media_line(attrs, &ssrcs, &session.exts, &params)
            })
            .collect::<Vec<_>>();

        // Add a=sctp-init to the application m-line if SNAP is configured.
        if let Some(sctp_init) = &params.local_sctp_init {
            for line in &mut lines {
                if line.typ.is_channel() {
                    line.attrs
                        .push(sdp::MediaAttribute::SctpInit(sctp_init.clone()));
                }
            }
        }

        if let Some(pending) = params.pending {
            pending.apply_to(&mut lines);
        }

        // Mids go into the session part of the SDP.
        // Rejected (disabled) m-lines must not be part of the BUNDLE group.
        let mids = lines
            .iter()
            .filter(|l| !l.disabled)
            .map(|l| l.mid())
            .collect();

        let mut stream_ids = vec![];
        for msid in v.iter().filter_map(|v| v.msid()) {
            if !stream_ids.contains(&msid.stream_id) {
                stream_ids.push(msid.stream_id.clone());
            }
        }

        (lines, mids, stream_ids)
    };

    // AllowMixedExts adds "a=extmap-allow-mixed" at session level to signal
    // support for mixing one-byte and two-byte RTP header extensions.
    // TODO: It would make sense to perform an actual negotiation, however
    //       just adding this line should work fine:
    // https://github.com/meetecho/janus-gateway/blob/d2e74fdf9bb8aa7a39ed68ed28394afe1e0cd22d/src/sdp.c#L1519
    let mut attrs = vec![
        SessionAttribute::Group {
            typ: "BUNDLE".into(),
            mids,
        },
        SessionAttribute::AllowMixedExts,
        SessionAttribute::MsidSemantic {
            semantic: "WMS".to_string(),
            stream_ids,
        },
    ];

    if session.ice_lite {
        attrs.push(SessionAttribute::IceLite);
    }

    Sdp {
        session: sdp::Session {
            id: session.id(),
            bw: None,
            attrs,
        },
        media_lines,
    }
}

fn apply_offer(session: &mut Session, offer: SdpOffer) -> Result<(), RtcError> {
    offer.assert_consistency()?;

    update_session(session, &offer);

    let bundle_mids = offer.bundle_mids();
    let new_lines = sync_medias(session, &offer).map_err(RtcError::RemoteSdp)?;

    add_new_lines(session, &new_lines, true, bundle_mids).map_err(RtcError::RemoteSdp)?;

    ensure_stream_tx(session);

    Ok(())
}

fn apply_answer(
    session: &mut Session,
    pending: Changes,
    answer: SdpAnswer,
) -> Result<(), RtcError> {
    answer.assert_consistency()?;

    update_session(session, &answer);

    let bundle_mids = answer.bundle_mids();
    let new_lines = sync_medias(session, &answer).map_err(RtcError::RemoteSdp)?;

    // The new_lines from the answer must correspond to what we sent in the offer.
    if let Some(err) = pending.ensure_correct_answer(&new_lines) {
        return Err(RtcError::RemoteSdp(err));
    }

    add_new_lines(session, &new_lines, false, bundle_mids).map_err(RtcError::RemoteSdp)?;

    // Add all pending changes (since we pre-allocated SSRC communicated in the Offer).
    add_pending_changes(session, pending);

    ensure_stream_tx(session);

    Ok(())
}

fn ensure_stream_tx(session: &mut Session) {
    for media in &session.medias {
        // Only make send streams when we have to.
        if !media.direction().is_sending() {
            continue;
        }

        let mut rids: Vec<Option<Rid>> = vec![];

        if let Some(sim) = media.simulcast() {
            for layer in &*sim.send {
                let rid: Rid = layer.restriction_id.0.as_str().into();
                rids.push(Some(rid));
            }
        } else {
            rids.push(None);
        }

        // If any payload param has RTX, we need to prepare for RTX. This is because we always
        // communicate a=ssrc lines, which need to be complete with main and RTX SSRC.
        let has_rtx = session
            .codec_config
            .iter()
            .filter(|p| media.remote_pts().contains(&p.pt))
            .any(|p| p.resend().is_some());

        for rid in rids {
            let midrid = MidRid(media.mid(), rid);

            // If we already have the stream, we don't make any new one.
            let has_stream = session.streams.stream_tx_by_midrid(midrid).is_some();

            if has_stream {
                continue;
            }

            let (ssrc, rtx) = if has_rtx {
                let (ssrc, rtx) = session.streams.new_ssrc_pair();
                (ssrc, Some(rtx))
            } else {
                let ssrc = session.streams.new_ssrc();
                (ssrc, None)
            };

            let stream = session.streams.declare_stream_tx(ssrc, rtx, midrid);

            // Configure cache size
            let size = if media.kind().is_audio() {
                session.send_buffer_audio
            } else {
                session.send_buffer_video
            };

            stream.set_rtx_cache(size, DEFAULT_RTX_CACHE_DURATION, DEFAULT_RTX_RATIO_CAP);
        }
    }
}

fn add_pending_changes(session: &mut Session, pending: Changes) {
    // For pending AddMedia, we have outgoing SSRC communicated that needs to be added.
    for change in pending.0 {
        let add_media = match change {
            Change::AddMedia(v) => v,
            _ => continue,
        };

        let media = session
            .medias
            .iter_mut()
            .find(|m| m.mid() == add_media.mid)
            .expect("Media to be added for pending mid");

        // the cname/msid has already been communicated in the offer, we need to kep
        // it the same once the m-line is created.
        media.set_cname(add_media.cname);
        media.set_msid(add_media.msid);

        // If there are RIDs, the SSRC order matches that of the rid order.
        let layers = add_media.simulcast.map(|x| x.send).unwrap_or(vec![]);

        for (i, (ssrc, rtx)) in add_media.ssrcs.into_iter().enumerate() {
            let maybe_layer = layers.get(i).cloned();
            let midrid = MidRid(add_media.mid, maybe_layer.map(|layer| layer.rid));

            let stream = session.streams.declare_stream_tx(ssrc, rtx, midrid);

            let size = if media.kind().is_audio() {
                session.send_buffer_audio
            } else {
                session.send_buffer_video
            };

            stream.set_rtx_cache(size, DEFAULT_RTX_CACHE_DURATION, DEFAULT_RTX_RATIO_CAP);
        }
    }
}

/// Compares m-lines in Sdp with that already in the session.
///
/// * Existing m-lines can apply changes (such as direction change).
/// * New m-lines are returned to the caller.
fn sync_medias<'a>(session: &mut Session, sdp: &'a Sdp) -> Result<Vec<&'a MediaLine>, String> {
    let mut new_lines = Vec::with_capacity(sdp.media_lines.len());
    let bundle_mids = sdp.bundle_mids();

    for (idx, m) in sdp.media_lines.iter().enumerate() {
        // First, match existing m-lines.
        match m.typ {
            MediaType::Application => {
                if let Some((_, index)) = session.app() {
                    if idx != *index {
                        return index_err(m.mid());
                    }
                    continue;
                }
            }
            MediaType::Audio | MediaType::Video => {
                if let Some(media) = session.medias.iter_mut().find(|l| l.mid() == m.mid()) {
                    if idx != media.index() {
                        return index_err(m.mid());
                    }

                    update_media(
                        media,
                        m,
                        &session.codec_config,
                        &session.exts,
                        &mut session.streams,
                        bundle_mids,
                    );

                    continue;
                }
            }
            _ => {
                continue;
            }
        }

        // Second, discover new m-lines.
        new_lines.push(m);
    }

    fn index_err<T>(mid: Mid) -> Result<T, String> {
        Err(format!("Changed order for m-line with mid: {mid}"))
    }

    Ok(new_lines)
}

/// Adds new m-lines as found in an offer or answer.
fn add_new_lines(
    session: &mut Session,
    new_lines: &[&MediaLine],
    is_offer: bool,
    bundle_mids: Option<&[Mid]>,
) -> Result<(), String> {
    for m in new_lines {
        let idx = session.line_count();

        if m.typ.is_media() {
            let mut media = Media::from_remote_media_line(m, idx, is_offer);

            // For disabled (rejected) m-lines, don't fire open event
            // and the direction will be set to Inactive by update_media.
            // In max-bundle, port=0 with the MID in BUNDLE group is NOT rejected.
            let is_in_bundle = bundle_mids
                .map(|mids| mids.contains(&m.mid()))
                .unwrap_or(false);
            let is_rejected = m.disabled && !is_in_bundle;
            media.need_open_event = is_offer && !is_rejected;

            // Match/remap remote params.
            session
                .codec_config
                .update_params(&m.rtp_params(), m.direction());

            // Remap the extension to that of the answer.
            session.exts.remap(&m.extmaps());

            update_media(
                &mut media,
                m,
                &session.codec_config,
                &session.exts,
                &mut session.streams,
                bundle_mids,
            );

            session.add_media(media);
        } else if m.typ.is_channel() {
            session.set_app(m.mid(), idx)?;
        } else {
            return Err(format!(
                "New m-line is neither media nor channel: {}",
                m.mid()
            ));
        }
    }

    Ok(())
}

/// Update session level properties like
/// Extensions from offer or answer.
fn update_session(session: &mut Session, sdp: &Sdp) {
    // Does any m-line contain a a=rtcp-fb:xx transport-cc?
    let has_transport_cc = sdp
        .media_lines
        .iter()
        .any(|m| m.rtp_params().iter().any(|p| p.fb_transport_cc));

    // Is the session level sequence number enabled?
    let has_twcc_header = session
        .exts
        .id_of(Extension::TransportSequenceNumber)
        .is_some();

    // Since twcc feedback is session wide we enable it if there are _any_
    // m-line with a a=rtcp-fb transport-cc parameter and the sequence number
    // header is enabled. It can later be disabled for specific m-lines based
    // on the extensions map.
    if has_transport_cc && has_twcc_header {
        session.enable_twcc_feedback();
    }
}

/// Returns all media/channels as `AsMediaLine` trait.
fn as_media_lines(session: &Session) -> Vec<&dyn AsSdpMediaLine> {
    let mut v = vec![];

    if let Some(app) = session.app() {
        v.push(app as &dyn AsSdpMediaLine);
    }
    v.extend(session.medias().iter().map(|m| m as &dyn AsSdpMediaLine));
    v.sort_by_key(|f| f.index());
    v
}

fn update_media(
    media: &mut Media,
    m: &MediaLine,
    config: &CodecConfig,
    exts: &ExtensionMap,
    streams: &mut Streams,
    bundle_mids: Option<&[Mid]>,
) {
    // If the m-line has port=0, it could mean:
    // 1. The m-line is rejected (not in BUNDLE group)
    // 2. The m-line is bundled with another m-line (max-bundle format, RFC 8843)
    //
    // In max-bundle, secondary m-lines use port=0 to indicate they share transport
    // with the first m-line. This is NOT a rejection.
    let is_in_bundle = bundle_mids
        .map(|mids| mids.contains(&m.mid()))
        .unwrap_or(false);
    let is_rejected = m.disabled && !is_in_bundle;

    if is_rejected {
        if !media.disabled() {
            debug!(
                "Mid ({}) is rejected (port=0, not in BUNDLE), setting to Inactive",
                media.mid()
            );
        }
        media.mark_disabled();
        media.set_direction(Direction::Inactive);
        return;
    }

    // Direction changes
    //
    // All changes come from the other side, either via an incoming OFFER
    // or a ANSWER from our OFFER. Either way, the direction is inverted to
    // how we have it locally.
    let new_dir = m.direction().invert();
    //
    let change_direction_disallowed = !media.remote_created()
        && media.direction() == Direction::Inactive
        && new_dir == Direction::SendOnly;

    if change_direction_disallowed {
        debug!(
            "Ignore attempt to change inactive to recvonly by remote peer for locally created mid: {}",
            media.mid()
        );
    } else {
        media.set_direction(new_dir);
    }

    if new_dir.is_sending() {
        // The other side has declared how it EXPECTING to receive. We must only send
        // the RIDs declared in the answer.
        let rids = m.rids();
        let rid_tx = if rids.is_empty() {
            Rids::None
        } else {
            Rids::Specific(rids)
        };
        media.set_rid_tx(rid_tx);
    }
    if new_dir.is_receiving() {
        // The other side has declared what it proposes to send. We are accepting it.
        let rids = m.rids();
        let rid_rx = if rids.is_empty() {
            Rids::Any
        } else {
            Rids::Specific(rids)
        };
        media.set_rid_rx(rid_rx);
    }

    // Narrowing/ordering of of PT
    let pts: Vec<Pt> = m
        .rtp_params()
        .into_iter()
        .filter_map(|p| config.sdp_match_remote(p, m.direction()))
        .collect();
    media.set_remote_pts(pts);

    let mut remote_extmap = ExtensionMap::empty();
    for (id, ext) in m.extmaps().into_iter() {
        // The remapping of extensions should already have happened, which
        // means the ID are matching in the session to the remote.

        // Does the ID exist in session?
        let in_session = match exts.lookup(id) {
            Some(v) => v,
            None => continue,
        };

        if in_session != ext {
            // Don't set any extensions that aren't enabled in Session.
            continue;
        }

        // Use the Extension from session, since there might be a special
        // serializer for cases like VLA.
        remote_extmap.set(id, in_session.clone());
    }
    media.set_remote_extmap(remote_extmap);

    // SSRC changes
    // This will always be for ReceiverSource since any incoming a=ssrc line will be
    // about the remote side's SSRC.
    if !new_dir.is_receiving() {
        return;
    }

    // Simulcast configuration
    if let Some(s) = m.simulcast() {
        if s.is_munged {
            warn!("Not supporting simulcast via munging SDP");
        } else if media.simulcast().is_none() {
            // Invert before setting, since it has a recv and send config.
            media.set_simulcast(s.invert());
        }
    }

    // Only use pre-communicated SSRC if we are running without simulcast.
    // We found a bug in FF where the order of the simulcast lines does not
    // correspond to the order of the simulcast declarations. In this case
    // it's better to fall back on mid/rid dynamic mapping.
    if m.simulcast().is_some() {
        return;
    }

    let infos = m.ssrc_info();
    let main = infos.iter().filter(|i| i.repairs.is_none());

    for i in main {
        // TODO: If the remote is communicating _BOTH_ rid and a=ssrc this will fail.
        debug!("Adding pre-communicated SSRC: {:?}", i);
        let repair_ssrc = infos
            .iter()
            .find(|r| r.repairs == Some(i.ssrc))
            .map(|r| r.ssrc);

        // If remote communicated a main a=ssrc, but no RTX, we will not send nacks.
        let midrid = MidRid(media.mid(), None);
        let suppress_nack = repair_ssrc.is_none();
        streams.expect_stream_rx(i.ssrc, repair_ssrc, midrid, suppress_nack);
    }
}

trait AsSdpMediaLine {
    fn mid(&self) -> Mid;
    fn msid(&self) -> Option<&Msid>;
    fn index(&self) -> usize;
    fn kind(&self) -> MediaKind;
    fn as_media_line(
        &self,
        attrs: Vec<MediaAttribute>,
        ssrcs_tx: &[(Ssrc, Option<Ssrc>)],
        exts: &ExtensionMap,
        params: &[PayloadParams],
    ) -> MediaLine;
}

impl AsSdpMediaLine for (Mid, usize) {
    fn mid(&self) -> Mid {
        self.0
    }
    fn msid(&self) -> Option<&Msid> {
        None
    }
    fn index(&self) -> usize {
        self.1
    }
    fn kind(&self) -> MediaKind {
        MediaKind::Audio // doesn't matter for App
    }
    fn as_media_line(
        &self,
        mut attrs: Vec<MediaAttribute>,
        _ssrcs_tx: &[(Ssrc, Option<Ssrc>)],
        _exts: &ExtensionMap,
        _params: &[PayloadParams],
    ) -> MediaLine {
        attrs.push(MediaAttribute::Mid(self.0));
        attrs.push(MediaAttribute::SctpPort(5000));
        attrs.push(MediaAttribute::MaxMessageSize(262144));

        MediaLine {
            typ: sdp::MediaType::Application,
            disabled: false,
            proto: Proto::Sctp,
            pts: vec![],
            bw: None,
            attrs,
        }
    }
}

impl AsSdpMediaLine for Media {
    fn mid(&self) -> Mid {
        Media::mid(self)
    }
    fn msid(&self) -> Option<&Msid> {
        Some(Media::msid(self))
    }
    fn index(&self) -> usize {
        Media::index(self)
    }
    fn kind(&self) -> MediaKind {
        Media::kind(self)
    }
    fn as_media_line(
        &self,
        mut attrs: Vec<MediaAttribute>,
        ssrcs_tx: &[(Ssrc, Option<Ssrc>)],
        exts: &ExtensionMap,
        params: &[PayloadParams],
    ) -> MediaLine {
        if self.app_tmp {
            let app = (self.mid(), self.index());
            return app.as_media_line(attrs, ssrcs_tx, exts, params);
        }

        attrs.push(MediaAttribute::Mid(self.mid()));

        let audio = self.kind() == MediaKind::Audio;
        for (id, ext) in self.remote_extmap().iter_by_media_type(audio) {
            attrs.push(MediaAttribute::ExtMap {
                id,
                ext: ext.clone(),
            });
        }

        attrs.push(self.direction().into());
        attrs.push(MediaAttribute::Msid(self.msid().clone()));
        attrs.push(MediaAttribute::RtcpMux);

        // The effective params start from the Session::codec_config to retain the
        // user's configured preferred order, however they are narrowed only include
        // those the remote peer wants.
        let effective_params = params.iter().filter(|p| self.remote_pts().contains(&p.pt));

        let mut pts = vec![];

        for p in effective_params {
            p.as_media_attrs(&mut attrs);

            // The pts that will be advertised in the SDP
            pts.push(p.pt());
            if let Some(rtx) = p.resend() {
                pts.push(rtx);
            }
        }

        if let Some(s) = self.simulcast() {
            fn to_rids<'a>(
                gs: &'a SimulcastGroups,
                direction: &'static str,
            ) -> impl Iterator<Item = MediaAttribute> + 'a {
                gs.iter().map(move |layer| MediaAttribute::Rid {
                    id: layer.restriction_id.clone(),
                    direction,
                    pt: vec![],
                    restriction: layer.attributes.clone().unwrap_or_default(),
                })
            }
            attrs.extend(to_rids(&s.recv, "recv"));
            attrs.extend(to_rids(&s.send, "send"));
            attrs.push(MediaAttribute::Simulcast(s.clone()));
        }

        // Outgoing SSRCs
        let msid = format!("{} {}", self.msid().stream_id, self.msid().track_id);
        for (ssrc, ssrc_rtx) in ssrcs_tx {
            attrs.push(MediaAttribute::Ssrc {
                ssrc: *ssrc,
                attr: "cname".to_string(),
                value: self.cname().to_string(),
            });
            attrs.push(MediaAttribute::Ssrc {
                ssrc: *ssrc,
                attr: "msid".to_string(),
                value: msid.clone(),
            });
            if let Some(ssrc_rtx) = ssrc_rtx {
                attrs.push(MediaAttribute::Ssrc {
                    ssrc: *ssrc_rtx,
                    attr: "cname".to_string(),
                    value: self.cname().to_string(),
                });
                attrs.push(MediaAttribute::Ssrc {
                    ssrc: *ssrc_rtx,
                    attr: "msid".to_string(),
                    value: msid.clone(),
                });
            }
        }

        for (ssrc, ssrc_rtx) in ssrcs_tx {
            if let Some(ssrc_rtx) = ssrc_rtx {
                attrs.push(MediaAttribute::SsrcGroup {
                    semantics: "FID".to_string(),
                    ssrcs: vec![*ssrc, *ssrc_rtx],
                });
            }
        }

        MediaLine {
            typ: self.kind().into(),
            disabled: self.disabled(),
            proto: Proto::Srtp,
            pts,
            bw: None,
            attrs,
        }
    }
}

impl From<MediaKind> for MediaType {
    fn from(value: MediaKind) -> Self {
        match value {
            MediaKind::Audio => MediaType::Audio,
            MediaKind::Video => MediaType::Video,
        }
    }
}

struct AsSdpParams<'a, 'b> {
    pub candidates: Vec<Candidate>,
    pub creds: IceCreds,
    pub fingerprint: &'a Fingerprint,
    pub setup: Setup,
    pub pending: Option<&'b Changes>,
    pub local_sctp_init: Option<String>,
}

impl<'a, 'b> AsSdpParams<'a, 'b> {
    pub fn new(rtc: &'a Rtc, pending: Option<&'b Changes>) -> Self {
        let (creds, candidates) = if let Some((new_creds, keep_local_candidates)) =
            pending.and_then(|p| p.ice_restart())
        {
            if keep_local_candidates {
                // If we are performing an ICE restart and we are keeping the same
                // candidates we need to use ufrag from the new ICE credentials
                // in our offer.
                let mut new_candidates = rtc.ice.local_candidates().collect::<Vec<_>>();
                for c in &mut new_candidates {
                    c.set_ufrag(&new_creds.ufrag);
                }

                (new_creds, new_candidates)
            } else {
                (new_creds, vec![])
            }
        } else {
            (
                rtc.ice.local_credentials().clone(),
                rtc.ice.local_candidates().collect::<Vec<_>>(),
            )
        };

        AsSdpParams {
            candidates,
            creds,
            fingerprint: rtc.dtls.local_fingerprint(),
            setup: match rtc.dtls.is_active() {
                Some(true) => Setup::Active,
                Some(false) => Setup::Passive,
                None => Setup::ActPass,
            },
            pending,
            local_sctp_init: rtc.sctp.local_sctp_init_for_sdp(),
        }
    }

    fn media_attributes(&self, include_candidates: bool) -> Vec<MediaAttribute> {
        use MediaAttribute::*;

        let mut v = if include_candidates {
            self.candidates
                .iter()
                .map(|c| Candidate(c.clone()))
                .collect()
        } else {
            vec![]
        };

        v.push(IceUfrag(self.creds.ufrag.clone()));
        v.push(IcePwd(self.creds.pass.clone()));
        v.push(IceOptions("trickle".into()));
        v.push(Fingerprint(self.fingerprint.clone()));
        v.push(Setup(self.setup));

        v
    }
}

impl fmt::Debug for SdpPendingOffer {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SdpPendingOffer").finish()
    }
}

impl Changes {
    pub fn contains_add_app(&self) -> bool {
        for i in 0..self.0.len() {
            if matches!(&self.0[i], Change::AddApp(_)) {
                return true;
            }
        }
        false
    }

    pub fn take_new_channels(&mut self) -> Vec<(ChannelId, ChannelConfig)> {
        let mut v = vec![];

        if self.0.is_empty() {
            return v;
        }

        for i in (0..self.0.len()).rev() {
            if matches!(&self.0[i], Change::AddChannel(_)) {
                if let Change::AddChannel(id) = self.0.remove(i) {
                    v.push(id);
                }
            }
        }

        v
    }

    /// Tests the given lines (from answer) corresponds to changes.
    fn ensure_correct_answer(&self, lines: &[&MediaLine]) -> Option<String> {
        if self.count_new_medias() != lines.len() {
            return Some(format!(
                "Differing m-line count in offer vs answer: {} != {}",
                self.count_new_medias(),
                lines.len()
            ));
        }

        'next: for l in lines {
            let mid = l.mid();

            for m in &self.0 {
                use Change::*;
                match m {
                    AddMedia(v) if v.mid == mid => {
                        if !l.typ.is_media() {
                            return Some(format!(
                                "Answer m-line for mid ({}) is not of media type: {:?}",
                                mid, l.typ
                            ));
                        }
                        continue 'next;
                    }
                    AddApp(v) if *v == mid => {
                        if !l.typ.is_channel() {
                            return Some(format!(
                                "Answer m-line for mid ({}) is not a data channel: {:?}",
                                mid, l.typ
                            ));
                        }
                        continue 'next;
                    }
                    _ => {}
                }
            }

            return Some(format!("Mid in answer is not in offer: {mid}"));
        }

        None
    }

    fn count_new_medias(&self) -> usize {
        self.0
            .iter()
            .filter(|c| matches!(c, Change::AddMedia(_) | Change::AddApp(_)))
            .count()
    }

    pub fn as_new_medias<'a, 'b: 'a>(
        &'a self,
        index_start: usize,
        config: &'b CodecConfig,
        exts: &'b ExtensionMap,
    ) -> impl Iterator<Item = Media> + 'a {
        // Use a separate counter that only advances for entries that actually produce
        // an m-line (AddMedia / AddApp).  Non-media entries (Direction, IceRestart,
        // AddChannel) must not consume an index slot, otherwise the resulting m-line
        // indices would be non-contiguous and out of sync with their array positions.
        let mut media_idx = 0usize;
        self.0.iter().filter_map(move |c| {
            let result = c.as_new_media(index_start + media_idx, config, exts);
            if result.is_some() {
                media_idx += 1;
            }
            result
        })
    }

    pub(crate) fn apply_to(&self, lines: &mut [MediaLine]) {
        for change in &self.0 {
            if let Change::Direction(mid, dir) = change {
                if let Some(line) = lines.iter_mut().find(|l| l.mid() == *mid) {
                    if let Some(dir_pos) = line.attrs.iter().position(|a| a.is_direction()) {
                        line.attrs[dir_pos] = (*dir).into();
                    }
                }
            }
        }
    }

    fn ssrcs_for_mid(&self, mid: Mid) -> &[(Ssrc, Option<Ssrc>)] {
        let maybe_add_media = self
            .0
            .iter()
            .filter_map(|c| {
                if let Change::AddMedia(m) = c {
                    Some(m)
                } else {
                    None
                }
            })
            .find(|m| m.mid == mid);

        let Some(m) = maybe_add_media else {
            return &[];
        };

        &m.ssrcs
    }
}

impl Change {
    fn as_new_media(
        &self,
        index: usize,
        config: &CodecConfig,
        exts: &ExtensionMap,
    ) -> Option<Media> {
        use Change::*;
        match self {
            AddMedia(v) => {
                // TODO can we avoid all this cloning?
                let mut add = v.clone();
                add.pts = config.all_for_kind(v.kind).map(|p| p.pt()).collect();
                add.exts = exts.cloned_with_type(v.kind.is_audio());
                add.index = index;

                Some(Media::from_add_media(add))
            }
            AddApp(mid) => Some(Media::from_app_tmp(*mid, index)),
            _ => None,
        }
    }
}

#[cfg(test)]
mod test {
    use std::time::Instant;

    use sdp::RestrictionId;
    use sdp::SimulcastLayer as SdpSimulcastLayer;

    use crate::format::Codec;
    use crate::media::{Simulcast, SimulcastLayer};
    use crate::sdp::RtpMap;

    use super::*;

    fn resolve_pt(m_line: &MediaLine, needle: Pt) -> RtpMap {
        m_line
            .attrs
            .iter()
            .find_map(|attr| match attr {
                MediaAttribute::RtpMap { pt, value } if *pt == needle => Some(*value),
                _ => None,
            })
            .unwrap_or_else(|| panic!("Expected to find RtpMap for {needle}"))
    }

    fn count_lines(lines: &str, what: &str) -> usize {
        lines.lines().filter(|l| l == &what).count()
    }

    #[test]
    fn test_out_of_order_error() {
        crate::init_crypto_default();

        let now = Instant::now();
        let mut rtc1 = Rtc::new(now);
        let mut rtc2 = Rtc::new(now);

        let mut change1 = rtc1.sdp_api();
        change1.add_channel("ch1".into());
        let (offer1, pending1) = change1.apply().unwrap();

        let mut change2 = rtc2.sdp_api();
        change2.add_channel("ch2".into());
        let (offer2, _) = change2.apply().unwrap();

        // invalidates pending1
        let _ = rtc1.sdp_api().accept_offer(offer2).unwrap();
        let answer2 = rtc2.sdp_api().accept_offer(offer1).unwrap();

        let r = rtc1.sdp_api().accept_answer(pending1, answer2);

        assert!(matches!(r, Err(RtcError::ChangesOutOfOrder)));
    }

    #[test]
    fn sdp_api_merge_works() {
        crate::init_crypto_default();

        let mut rtc = Rtc::new(Instant::now());
        let mut changes = rtc.sdp_api();
        changes.add_media(MediaKind::Audio, Direction::SendOnly, None, None, None);
        let (offer, pending) = changes.apply().unwrap();

        let mut changes = rtc.sdp_api();
        changes.add_media(MediaKind::Video, Direction::SendOnly, None, None, None);
        changes.merge(pending);
        let (new_offer, _) = changes.apply().unwrap();

        // After merge(), the original AddMedia (audio) is prepended before the new AddMedia
        // (video) to preserve its original m-line position.  So audio is at index 0 and video at 1.
        assert_eq!(offer.media_lines[0], new_offer.media_lines[0]);
        assert_eq!(new_offer.media_lines[0].typ, MediaType::Audio);
        assert_eq!(new_offer.media_lines[1].typ, MediaType::Video);
        assert_eq!(new_offer.media_lines.len(), 2);
    }

    // The indices assigned to Media objects by as_new_medias() must be contiguous starting
    // from index_start.  Only entries that produce m-lines (AddMedia / AddApp) should
    // consume an index slot – non-media entries (AddChannel, Direction, IceRestart) must
    // not advance the counter.
    //
    // We test this by building a Changes vector directly and inspecting the indices
    // returned by as_new_medias().
    #[test]
    fn as_new_medias_contiguous_indices_with_non_media_changes() {
        crate::init_crypto_default();

        let now = Instant::now();
        let mut rtc = Rtc::new(now);

        // Build a Changes vector that interleaves non-media entries with media entries.
        // The non-media AddChannel entry must not consume an index slot.
        //
        // Changes = [AddApp(mid0), AddChannel(id, cfg), AddMedia(audio)]
        //
        // index_start = 0 (fresh session)
        // Expected indices: AddApp → 0, AddMedia(audio) → 1
        // Buggy indices:    AddApp → 0, AddMedia(audio) → 2
        let mut changes = Changes::default();
        let mid_app = rtc.new_mid();
        changes.0.push(Change::AddApp(mid_app));
        let mid_audio = rtc.new_mid();
        let chan_id = rtc.chan.new_channel(&ChannelConfig {
            label: "ch".into(),
            ..Default::default()
        });
        changes.0.push(Change::AddChannel((
            chan_id,
            ChannelConfig {
                label: "ch".into(),
                ..Default::default()
            },
        )));
        changes.0.push(Change::AddMedia(AddMedia {
            mid: mid_audio,
            cname: "test".into(),
            msid: Msid {
                stream_id: "stream".into(),
                track_id: "track".into(),
            },
            kind: MediaKind::Audio,
            dir: Direction::SendOnly,
            ssrcs: vec![],
            simulcast: None,
            pts: vec![],
            exts: ExtensionMap::empty(),
            index: 0, // will be overwritten by as_new_media()
        }));

        let config = CodecConfig::new_with_defaults();
        let exts = ExtensionMap::standard();

        let medias: Vec<Media> = changes.as_new_medias(0, &config, &exts).collect();

        // Should produce two Media objects: one for AddApp, one for AddMedia(audio).
        assert_eq!(medias.len(), 2, "Expected 2 media-producing entries");

        // The first m-line is AddApp at index 0.
        assert_eq!(medias[0].index(), 0, "AddApp should have index 0");

        // The second m-line is Audio.  It must get the contiguous index 1, not 2 (which
        // would result from counting the non-media AddChannel entry as a slot).
        assert_eq!(
            medias[1].index(),
            1,
            "AddMedia(audio) should have contiguous index 1, not 2"
        );
    }

    // AddMedia/AddApp entries from a pending offer carry already-allocated MIDs whose
    // m-line positions the remote peer may have committed to.  When merging a pending offer
    // into a new SdpApi, those original entries must be prepended so they keep their
    // original lower-index positions rather than being displaced by new changes.
    #[test]
    fn sdp_api_merge_stale_media_keeps_original_position() {
        crate::init_crypto_default();

        let mut rtc = Rtc::new(Instant::now());

        // First offer: add audio.  Audio will be at index 0.
        let mut changes = rtc.sdp_api();
        let _mid_audio = changes.add_media(MediaKind::Audio, Direction::SendOnly, None, None, None);
        let (offer1, pending) = changes.apply().unwrap();

        // The original offer has audio at position 0.
        assert_eq!(offer1.media_lines[0].typ, MediaType::Audio);

        // Simulate glare: a new SdpApi adds video, then merges the pending offer
        // containing the original audio AddMedia.
        let mut changes = rtc.sdp_api();
        changes.add_media(MediaKind::Video, Direction::SendOnly, None, None, None);
        changes.merge(pending);
        let (offer2, _) = changes.apply().unwrap();

        // The original audio must be prepended before the new video, keeping it at
        // position 0 — the same position as in the original offer.
        assert_eq!(
            offer2.media_lines[0].typ,
            MediaType::Audio,
            "Original audio from pending should be at position 0 (same as original offer)"
        );
        assert_eq!(
            offer2.media_lines[1].typ,
            MediaType::Video,
            "New video added to current SdpApi should be at position 1"
        );
        assert_eq!(
            offer1.media_lines[0], offer2.media_lines[0],
            "Audio m-line must be identical between original and merged offers"
        );
    }

    // When a new SdpApi has its own AddMedia changes and also merges a pending offer that
    // has AddMedia changes, the original pending entries must come before the new ones so
    // their m-line positions are stable:
    //   1. First offer: [AddMedia(audio), AddMedia(video)] → audio at 0, video at 1
    //   2. Glare – pending is saved
    //   3. New SdpApi: [AddMedia(screen)]
    //   4. After merge: [AddMedia(audio), AddMedia(video), AddMedia(screen)]
    //      → audio at 0, video at 1, screen at 2  (CORRECT)
    #[test]
    fn sdp_api_merge_with_direction_and_new_media_preserves_positions() {
        crate::init_crypto_default();

        let now = Instant::now();
        let mut rtc1 = Rtc::new(now);
        let mut rtc2 = Rtc::new(now);

        // Establish one audio m-line so we can change its direction later.
        let mut changes = rtc1.sdp_api();
        let mid_audio = changes.add_media(MediaKind::Audio, Direction::SendOnly, None, None, None);
        let (offer0, pending0) = changes.apply().unwrap();
        let answer0 = rtc2.sdp_api().accept_offer(offer0).unwrap();
        rtc1.sdp_api().accept_answer(pending0, answer0).unwrap();
        // Session now: audio at index 0.

        // Create an offer with two new medias: video1 and video2.
        // video1 → session position 1, video2 → session position 2.
        let mut changes = rtc1.sdp_api();
        let mid_v1 = changes.add_media(MediaKind::Video, Direction::SendOnly, None, None, None);
        let mid_v2 = changes.add_media(MediaKind::Video, Direction::SendOnly, None, None, None);
        let (offer1, pending1) = changes.apply().unwrap();

        assert_eq!(offer1.media_lines[1].mid(), mid_v1, "video1 at idx 1");
        assert_eq!(offer1.media_lines[2].mid(), mid_v2, "video2 at idx 2");

        // Glare: create a new SdpApi that:
        //   (a) changes direction of existing audio m-line (non-media Change)
        //   (b) adds a new screen-share video m-line
        // Then merge the original pending1 into it.
        let mut changes = rtc1.sdp_api();
        changes.set_direction(mid_audio, Direction::Inactive);
        let mid_screen = changes.add_media(MediaKind::Video, Direction::SendOnly, None, None, None);
        changes.merge(pending1);
        let (offer2, _) = changes.apply().unwrap();

        // Session already has audio at index 0.
        // The merged offer must have:
        //   position 0: audio (existing, unchanged)
        //   position 1: video1 (from pending — same position as offer1)
        //   position 2: video2 (from pending — same position as offer1)
        //   position 3: screen (newly added in the new SdpApi)
        assert_eq!(
            offer2.media_lines.len(),
            4,
            "Merged offer should have 4 m-lines: audio + video1 + video2 + screen"
        );

        // Original video m-lines from the pending offer must keep their positions (1 and 2).
        assert_eq!(
            offer2.media_lines[1].mid(),
            mid_v1,
            "video1 from pending should remain at position 1"
        );
        assert_eq!(
            offer1.media_lines[1], offer2.media_lines[1],
            "video1 m-line should be identical in both offers"
        );
        assert_eq!(
            offer2.media_lines[2].mid(),
            mid_v2,
            "video2 from pending should remain at position 2"
        );
        assert_eq!(
            offer1.media_lines[2], offer2.media_lines[2],
            "video2 m-line should be identical in both offers"
        );

        // New screen share is at position 3, after the original pending m-lines.
        assert_eq!(
            offer2.media_lines[3].mid(),
            mid_screen,
            "New screen-share should be at position 3"
        );
    }

    #[test]
    fn test_rtp_payload_priority() {
        crate::init_crypto_default();

        let now = Instant::now();
        let mut rtc1 = Rtc::builder()
            .clear_codecs()
            .enable_h264(true)
            .enable_vp8(true)
            .enable_vp9(true)
            .build(now);
        let mut rtc2 = Rtc::builder()
            .clear_codecs()
            .enable_vp8(true)
            .enable_h264(true)
            .build(now);

        let mut change1 = rtc1.sdp_api();
        change1.add_media(MediaKind::Video, Direction::SendOnly, None, None, None);
        let (offer1, _) = change1.apply().unwrap();

        let answer = rtc2.sdp_api().accept_offer(offer1).unwrap();
        assert_eq!(
            answer.media_lines.len(),
            1,
            "There should be one mline only"
        );

        let first_mline = &answer.media_lines[0];
        let first_pt = resolve_pt(first_mline, first_mline.pts[0]);

        assert_eq!(
            first_pt.codec,
            Codec::Vp8,
            "The first PT returned should be the highest priority PT from the answer that is supported."
        );

        let vp9_unsupported = first_mline
            .pts
            .iter()
            .any(|pt| resolve_pt(first_mline, *pt).codec == Codec::Vp9);

        assert!(
            !vp9_unsupported,
            "VP9 was not offered, so it should not be present in the answer"
        );
    }

    #[test]
    fn non_simulcast_rids() {
        crate::init_crypto_default();

        let now = Instant::now();
        let mut rtc1 = Rtc::new(now);
        let mut rtc2 = Rtc::new(now);

        // Test initial media creation
        let mid = {
            let mut changes = rtc1.sdp_api();
            let mid = changes.add_media(MediaKind::Audio, Direction::SendOnly, None, None, None);
            let (offer, pending) = changes.apply().unwrap();
            let answer = rtc2.sdp_api().accept_offer(offer).unwrap();
            rtc1.sdp_api().accept_answer(pending, answer).unwrap();

            assert!(matches!(rtc1.media(mid).unwrap().rids_rx(), Rids::Any));
            assert!(matches!(rtc1.media(mid).unwrap().rids_tx(), Rids::None));
            assert!(matches!(rtc2.media(mid).unwrap().rids_rx(), Rids::Any));
            assert!(matches!(rtc2.media(mid).unwrap().rids_tx(), Rids::None));

            mid
        };

        // Test later updates to that media
        {
            let mut changes = rtc1.sdp_api();
            changes.set_direction(mid, Direction::Inactive);
            let (offer, pending) = changes.apply().unwrap();
            let answer = rtc2.sdp_api().accept_offer(offer).unwrap();
            rtc1.sdp_api().accept_answer(pending, answer).unwrap();

            assert!(matches!(rtc1.media(mid).unwrap().rids_rx(), Rids::Any));
            assert!(matches!(rtc1.media(mid).unwrap().rids_tx(), Rids::None));
            assert!(matches!(rtc2.media(mid).unwrap().rids_rx(), Rids::Any));
            assert!(matches!(rtc2.media(mid).unwrap().rids_tx(), Rids::None));
        }
    }

    #[test]
    fn simulcast_ssrc_allocation() {
        crate::init_crypto_default();

        let mut rtc1 = Rtc::new(Instant::now());

        let mut simulcast = Simulcast::new();

        simulcast.add_send_layer(SimulcastLayer::new("h"));
        simulcast.add_send_layer(SimulcastLayer::new("m"));
        simulcast.add_send_layer(SimulcastLayer::new("l"));

        let mut change = rtc1.sdp_api();
        change.add_media(
            MediaKind::Video,
            Direction::SendOnly,
            None,
            None,
            Some(simulcast),
        );

        let Change::AddMedia(am) = &change.changes[0] else {
            panic!("Not AddMedia?!");
        };

        // these should be organized in order: m, h, l
        let pending_ssrcs = am.ssrcs.clone();
        assert_eq!(pending_ssrcs.len(), 3);

        for p in &pending_ssrcs {
            assert!(p.1.is_some()); // all should have rtx
        }

        let (offer, _) = change.apply().unwrap();
        let sdp = offer.into_inner();
        let line = &sdp.media_lines[0];

        assert_eq!(
            line.simulcast().unwrap().send,
            SimulcastGroups(vec![
                SdpSimulcastLayer {
                    restriction_id: RestrictionId("h".into(), true),
                    attributes: None,
                },
                SdpSimulcastLayer {
                    restriction_id: RestrictionId("m".into(), true),
                    attributes: None,
                },
                SdpSimulcastLayer {
                    restriction_id: RestrictionId("l".into(), true),
                    attributes: None,
                },
            ])
        );

        // Each SSRC, both regular and RTX get their own a=ssrc line.
        assert_eq!(line.ssrc_info().len(), pending_ssrcs.len() * 2);

        let fids: Vec<_> = line
            .attrs
            .iter()
            .filter_map(|a| {
                if let MediaAttribute::SsrcGroup { semantics, ssrcs } = a {
                    // We don't have any other semantics right now.
                    assert_eq!(semantics, "FID");
                    assert_eq!(ssrcs.len(), 2);
                    Some((ssrcs[0], ssrcs[1]))
                } else {
                    None
                }
            })
            .collect();

        assert_eq!(fids.len(), pending_ssrcs.len());

        for (a, b) in fids.iter().zip(pending_ssrcs.iter()) {
            assert_eq!(a.0, b.0);
            assert_eq!(Some(a.1), b.1);
        }

        let line_string = line.to_string();

        // The SDP offer should contain layers without any attributes
        assert_eq!(count_lines(&line_string, "a=rid:h send"), 1);
        assert_eq!(count_lines(&line_string, "a=rid:m send"), 1);
        assert_eq!(count_lines(&line_string, "a=rid:l send"), 1);
    }

    #[test]
    fn simulcast_attributes() {
        crate::init_crypto_default();

        let mut rtc1 = Rtc::new(Instant::now());

        let mut simulcast = Simulcast::new();

        // High layer
        simulcast.add_send_layer(
            SimulcastLayer::new_with_attributes("high")
                .max_width(1280)
                .max_height(720)
                .max_br(1100000)
                .max_br(1300000)
                .max_br(1500000) // the last one wins
                .max_fps(30)
                .build(),
        );

        // Medium layer
        simulcast.add_send_layer(
            SimulcastLayer::new_with_attributes("medium")
                .max_width(640)
                .max_height(360)
                .max_br(600000)
                // No max_fps
                .build(),
        );

        // Low layer
        simulcast.add_send_layer(
            SimulcastLayer::new_with_attributes("low")
                // No max_width
                .max_height(180)
                .max_br(200000)
                .max_fps(15)
                .build(),
        );

        // Custom attribute
        simulcast.add_send_layer(
            SimulcastLayer::new_with_attributes("custom")
                .custom("foo", "bar")
                .build(),
        );

        // No attributes
        simulcast.add_send_layer(SimulcastLayer::new_with_attributes("no_attrs").build());

        let mut change = rtc1.sdp_api();
        change.add_media(
            MediaKind::Video,
            Direction::SendOnly,
            None,
            None,
            Some(simulcast),
        );

        let (offer, _) = change.apply().unwrap();
        let sdp = offer.into_inner();
        let line = &sdp.media_lines[0];

        fn pairs_to_some_vec(pairs: &[(&str, &str)]) -> Option<Vec<(String, String)>> {
            Some(
                pairs
                    .iter()
                    .map(|(k, v)| (k.to_string(), v.to_string()))
                    .collect(),
            )
        }

        assert_eq!(
            line.simulcast().unwrap().send,
            SimulcastGroups(vec![
                SdpSimulcastLayer {
                    restriction_id: RestrictionId("high".into(), true),
                    attributes: pairs_to_some_vec(&[
                        ("max-width", "1280"),
                        ("max-height", "720"),
                        ("max-br", "1500000"),
                        ("max-fps", "30"),
                    ]),
                },
                SdpSimulcastLayer {
                    restriction_id: RestrictionId("medium".into(), true),
                    attributes: pairs_to_some_vec(&[
                        ("max-width", "640"),
                        ("max-height", "360"),
                        ("max-br", "600000"),
                    ]),
                },
                SdpSimulcastLayer {
                    restriction_id: RestrictionId("low".into(), true),
                    attributes: pairs_to_some_vec(&[
                        ("max-height", "180"),
                        ("max-br", "200000"),
                        ("max-fps", "15"),
                    ]),
                },
                SdpSimulcastLayer {
                    restriction_id: RestrictionId("custom".into(), true),
                    attributes: pairs_to_some_vec(&[("foo", "bar"),]),
                },
                SdpSimulcastLayer {
                    restriction_id: RestrictionId("no_attrs".into(), true),
                    attributes: None,
                },
            ])
        );

        // The SDP offer should contain layers with our attributes
        let line_string = line.to_string();
        assert_eq!(
            count_lines(
                &line_string,
                "a=rid:high send max-width=1280;max-height=720;max-br=1500000;max-fps=30"
            ),
            1
        );
        assert_eq!(
            count_lines(
                &line_string,
                "a=rid:medium send max-width=640;max-height=360;max-br=600000"
            ),
            1
        );
        assert_eq!(
            count_lines(
                &line_string,
                "a=rid:low send max-height=180;max-br=200000;max-fps=15"
            ),
            1
        );
        assert_eq!(count_lines(&line_string, "a=rid:custom send foo=bar"), 1);
        // No space at the end
        assert_eq!(count_lines(&line_string, "a=rid:no_attrs send"), 1);
    }
}