rtci 0.3.0

A sans-I/O WebRTC implementation: peer connections with ICE, DTLS-SRTP, SCTP data channels, RTP/RTCP and JSEP negotiation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
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
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
//! Session Description Protocol (SDP) types and utilities.
//!
//! This module provides types for working with SDP (Session Description Protocol),
//! which is used in WebRTC to negotiate media capabilities, codecs, network addresses,
//! and other session parameters between peers during the offer/answer exchange.
//!
//! # Overview
//!
//! SDP is a text-based protocol defined in [RFC 8866] that describes multimedia
//! sessions. In WebRTC, SDP is used to:
//!
//! - Describe available media codecs (audio/video formats)
//! - Exchange ICE candidates for NAT traversal
//! - Negotiate DTLS fingerprints for secure communication
//! - Establish media transport parameters
//! - Define simulcast and layered encoding configurations
//!
//! # Offer/Answer Model
//!
//! WebRTC uses the offer/answer model from [RFC 3264]:
//!
//! 1. **Offer**: The initiating peer creates an SDP offer describing their capabilities
//! 2. **Answer**: The remote peer responds with an SDP answer describing their chosen configuration
//! 3. **Pranswer**: Optional provisional answer before the final answer
//! 4. **Rollback**: Cancels negotiation and returns to the previous stable state
//!
//! # Public API
//!
//! This module exports two main types:
//!
//! - [`RTCSdpType`] - Enum representing the type of session description (Offer, Answer, etc.)
//! - [`RTCSessionDescription`] - Struct containing SDP text and its type
//!
//! # Examples
//!
//! ## Creating an Offer
//!
//! ```no_run
//! use rtci::peer_connection::sdp::{RTCSessionDescription, RTCSdpType};
//!
//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
//! // SDP string generated by create_offer()
//! let sdp_string = "v=0\r\no=- 123 456 IN IP4 0.0.0.0\r\n...".to_string();
//!
//! // Wrap the SDP in an RTCSessionDescription
//! let offer = RTCSessionDescription::offer(sdp_string)?;
//!
//! assert_eq!(offer.sdp_type, RTCSdpType::Offer);
//! println!("Created offer: {}", offer);
//! # Ok(())
//! # }
//! ```
//!
//! ## Creating an Answer
//!
//! ```no_run
//! use rtci::peer_connection::sdp::{RTCSessionDescription, RTCSdpType};
//!
//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
//! // SDP string generated by create_answer()
//! let sdp_string = "v=0\r\no=- 789 012 IN IP4 0.0.0.0\r\n...".to_string();
//!
//! // Wrap the SDP in an RTCSessionDescription
//! let answer = RTCSessionDescription::answer(sdp_string)?;
//!
//! assert_eq!(answer.sdp_type, RTCSdpType::Answer);
//! # Ok(())
//! # }
//! ```
//!
//! ## Using Provisional Answers
//!
//! ```no_run
//! use rtci::peer_connection::sdp::RTCSessionDescription;
//!
//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
//! // Create a provisional answer that may be updated later
//! let sdp_string = "v=0\r\no=- 345 678 IN IP4 0.0.0.0\r\n...".to_string();
//! let pranswer = RTCSessionDescription::pranswer(sdp_string)?;
//!
//! // Later, you can send a final answer to complete negotiation
//! # Ok(())
//! # }
//! ```
//!
//! ## Parsing SDP Content
//!
//! ```no_run
//! use rtci::peer_connection::sdp::RTCSessionDescription;
//!
//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let offer = RTCSessionDescription::offer(
//!     "v=0\r\no=- 123 456 IN IP4 0.0.0.0\r\n...".to_string()
//! )?;
//!
//! // Unmarshal parses the SDP text into a structured format
//! let parsed = offer.unmarshal()?;
//! println!("Session name: {}", parsed.session_name);
//! # Ok(())
//! # }
//! ```
//!
//! ## Serializing to JSON
//!
//! ```no_run
//! use rtci::peer_connection::sdp::{RTCSessionDescription, RTCSdpType};
//!
//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
//! // Create an offer description (parsed field set automatically)
//! let desc = RTCSessionDescription::offer(
//!     "v=0\r\no=- 123 456 IN IP4 0.0.0.0\r\ns=-\r\nt=0 0\r\n".to_string()
//! )?;
//!
//! // Serialize for transmission to remote peer
//! let json = serde_json::to_string(&desc)?;
//! println!("JSON: {}", json);
//!
//! // Deserialize received SDP
//! let received: RTCSessionDescription = serde_json::from_str(&json)?;
//! assert_eq!(received.sdp_type, RTCSdpType::Offer);
//! # Ok(())
//! # }
//! ```
//!
//! # SDP Structure
//!
//! A typical WebRTC SDP contains:
//!
//! - **Session-level attributes**: Version, origin, timing
//! - **Media sections**: One per audio/video track or data channel
//! - **ICE candidates**: Network addresses for connectivity
//! - **Codec information**: Supported formats and parameters
//! - **DTLS fingerprints**: For secure communication
//!
//! # Specification
//!
//! - [RFC 8866] - SDP: Session Description Protocol
//! - [RFC 3264] - An Offer/Answer Model with SDP
//! - [RFC 9429] - JavaScript Session Establishment Protocol (JSEP)
//! - [W3C WebRTC Specification]
//!
//! [RFC 8866]: https://datatracker.ietf.org/doc/html/rfc8866
//! [RFC 3264]: https://datatracker.ietf.org/doc/html/rfc3264
//! [RFC 9429]: https://datatracker.ietf.org/doc/html/rfc9429
//! [W3C WebRTC Specification]: https://www.w3.org/TR/webrtc/#session-description-model

#[cfg(test)]
mod sdp_test;

#[cfg(test)]
mod browser_sdp_test;

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

    fn default_params() -> PopulateSdpParams {
        PopulateSdpParams {
            media_description_fingerprint: false,
            is_ice_lite: false,
            is_extmap_allow_mixed: false,
            connection_role: ConnectionRole::Active,
            ice_gathering_state: RTCIceGatheringState::Complete,
            bundle: BundleMode::initial_offer(),
            offered_tag_rtcp_mux_only: false,
            rtcp_mux_only: true,
            rtcp_mux_only_renegotiated: false,
            bundle_policy: RTCBundlePolicy::MaxCompat,
            initial_offer: false,
            bundle_attributes_in_tagged_section_only: false,
            bundle_only_browser_form: false,
            answer_offered_formats_only: false,
            sctp_max_message_size: 0,
            sctp_port: 5000,
            sctp_over_tcp: false,
            ignore_rid_pause_for_recv: false,
            write_ssrc_attributes_for_simulcast: false,
            ice_pacing: None,
            ice_options_in_media_sections: false,
            ice_options: vec!["trickle", "ice2"],
            ls_groups: vec![],
            selected_destination: None,
            remote_candidates: vec![],
            ecn: None,
            rid_pause_marks: false,
            video_receive_limits: None,
            codec_video_receive_limits: vec![],
            w3c_simulcast_answer: false,
            msid_appdata: false,
        }
    }

    #[test]
    fn test_rejected_audio_mline_has_port_zero() {
        let media_sections = vec![MediaSection {
            mid: "0".to_owned(),
            rejected: true,
            rejected_kind: "audio".to_owned(),
            transceiver_index: usize::MAX,
            ..Default::default()
        }];

        let me = MediaEngine::default();
        let mut transceivers: Vec<RTCRtpTransceiverInternal> = vec![];
        let sdp = RTCPeerConnection::populate_sdp(
            SessionDescription::default(),
            &[],
            &me,
            &mut transceivers,
            &[],
            &RTCIceParameters::default(),
            &media_sections,
            default_params(),
        )
        .unwrap();

        assert_eq!(sdp.media_descriptions.len(), 1);
        let desc = &sdp.media_descriptions[0];
        assert_eq!(desc.media_name.media, "audio");
        assert_eq!(desc.media_name.port.value, 0);
        assert_eq!(desc.media_name.protos, vec!["UDP", "TLS", "RTP", "SAVPF"]);
        assert_eq!(desc.media_name.formats, vec!["0"]);
        assert!(!desc.connection_information.is_empty());
    }

    #[test]
    fn test_rejected_application_mline_uses_sctp_proto() {
        let media_sections = vec![MediaSection {
            mid: "0".to_owned(),
            rejected: true,
            rejected_kind: "application".to_owned(),
            transceiver_index: usize::MAX,
            ..Default::default()
        }];

        let me = MediaEngine::default();
        let mut transceivers: Vec<RTCRtpTransceiverInternal> = vec![];
        let sdp = RTCPeerConnection::populate_sdp(
            SessionDescription::default(),
            &[],
            &me,
            &mut transceivers,
            &[],
            &RTCIceParameters::default(),
            &media_sections,
            default_params(),
        )
        .unwrap();

        assert_eq!(sdp.media_descriptions.len(), 1);
        let desc = &sdp.media_descriptions[0];
        assert_eq!(desc.media_name.media, "application");
        assert_eq!(desc.media_name.port.value, 0);
        assert_eq!(desc.media_name.protos, vec!["UDP", "DTLS", "SCTP"]);
        assert_eq!(desc.media_name.formats, vec!["webrtc-datachannel"]);
    }

    #[test]
    fn test_rejected_mline_not_added_to_bundle() {
        let media_sections = vec![
            MediaSection {
                mid: "0".to_owned(),
                rejected: true,
                rejected_kind: "video".to_owned(),
                transceiver_index: usize::MAX,
                ..Default::default()
            },
            MediaSection {
                mid: "1".to_owned(),
                rejected: true,
                rejected_kind: "audio".to_owned(),
                transceiver_index: usize::MAX,
                ..Default::default()
            },
        ];

        let me = MediaEngine::default();
        let mut transceivers: Vec<RTCRtpTransceiverInternal> = vec![];
        let sdp = RTCPeerConnection::populate_sdp(
            SessionDescription::default(),
            &[],
            &me,
            &mut transceivers,
            &[],
            &RTCIceParameters::default(),
            &media_sections,
            default_params(),
        )
        .unwrap();

        // Rejected m-lines should NOT appear in the BUNDLE group
        let bundle = sdp
            .attributes
            .iter()
            .find(|a| a.key == "group" && a.value.as_deref().unwrap_or("").starts_with("BUNDLE"));
        assert!(
            bundle.is_none(),
            "BUNDLE group should not be present when all m-lines are rejected"
        );

        // Both m-lines should be present with port=0
        assert_eq!(sdp.media_descriptions.len(), 2);
        assert_eq!(sdp.media_descriptions[0].media_name.port.value, 0);
        assert_eq!(sdp.media_descriptions[1].media_name.port.value, 0);
    }
}

mod answer_check;
pub(crate) mod ecn;
pub(crate) mod fec_session;
pub(crate) mod imageattr;
pub(crate) mod sdp_type;
pub(crate) mod send_limits;
pub(crate) mod session_description;
pub(crate) mod simulcast;

pub(crate) use answer_check::{bundle_groups, check_answer_against_offer, effective_direction};
pub(crate) use simulcast::{SimulcastDirection, SimulcastRid, get_rids};

pub use imageattr::RTCVideoResolutionRange;
pub use sdp_type::RTCSdpType;
pub use session_description::RTCSessionDescription;

use crate::media_stream::MediaStreamId;
use crate::media_stream::track::{MediaStreamTrack, MediaStreamTrackId};
use crate::peer_connection::RTCPeerConnection;
use crate::peer_connection::configuration::RTCBundlePolicy;
use crate::peer_connection::configuration::media_engine::{
    MediaEngine, RTCPacketTime, is_rtcp_conflicting_payload_type, local_extension_ids,
};
use crate::peer_connection::configuration::setting_engine::AnswerIceOptions;
use crate::peer_connection::state::ice_gathering_state::RTCIceGatheringState;
use crate::peer_connection::transport::dtls::fingerprint::{
    RTCDtlsFingerprint, parse_fingerprint_attribute,
};
use crate::peer_connection::transport::dtls::role::validate_setup_attributes;
use crate::peer_connection::transport::ice::candidate::RTCIceCandidate;
use crate::peer_connection::transport::ice::parameters::RTCIceParameters;
use crate::rtp_transceiver::direction::RTCRtpTransceiverDirection;
use crate::rtp_transceiver::rtp_sender::rtp_codec::{
    CodecMatch, RTCRtpCodec, RtpCodecKind, codec_parameters_fuzzy_search, codec_parameters_search,
    is_fec_mime_type, repair_family, rtcp_feedback_intersection,
};
use crate::rtp_transceiver::rtp_sender::rtp_codec_parameters::RTCRtpCodecParameters;
use crate::rtp_transceiver::rtp_sender::rtp_coding_parameters::RTCRtpRidRestrictions;
use crate::rtp_transceiver::{
    PayloadType, SSRC,
    internal::RTCRtpTransceiverInternal,
    rtp_sender::rtcp_parameters::{
        RTCP_FB_ACK_CCFB, RTCPFeedback, TYPE_RTCP_FB_ACK, negotiates_ccfb,
    },
};
use ice::candidate::{Candidate, unmarshal_candidate};
use sdp::attribute::RidIdGrammar;
use sdp::description::common::{Address, ConnectionInformation};
use sdp::description::media::*;
use sdp::description::session::*;
use sdp::extmap::ExtMap;
use sdp::util::ConnectionRole;
use shared::error::{Error, Result};
use std::collections::{HashMap, HashSet};
use url::Url;

/// `a=bundle-only` (RFC 8843 §6).
pub(crate) const ATTR_KEY_BUNDLE_ONLY: &str = "bundle-only";
/// `a=sframe` (draft-ietf-avtcore-rtp-sframe-03 section 6).
pub(crate) const ATTR_KEY_SFRAME: &str = "sframe";
/// `a=ice-options` (RFC 8839 §5.6).
pub(crate) const ATTR_KEY_ICE_OPTIONS: &str = "ice-options";
/// `a=ice-pacing` (RFC 8839 §5.5).
pub(crate) const ATTR_KEY_ICE_PACING: &str = "ice-pacing";
/// RFC 8839 section 5.2.
pub(crate) const ATTR_KEY_REMOTE_CANDIDATES: &str = "remote-candidates";
/// `a=ice-mismatch` (RFC 8839 section 5.3).
pub(crate) const ATTR_KEY_ICE_MISMATCH: &str = "ice-mismatch";
/// RFC 6236 section 3.1.
pub(crate) const ATTR_KEY_IMAGEATTR: &str = "imageattr";

/// The remote candidates an offer's `a=remote-candidates` lines name, as (address, port), of
/// the sections that carry candidates (RFC 8839 section 5.2). RFC 9429 section 5.8.2: they
/// "MUST be parsed ... but their values are ignored": one that does not parse refuses the
/// description; a full agent then only takes its default destination from them.
pub(crate) fn remote_candidates(desc: &SessionDescription) -> Result<Vec<(String, u16)>> {
    use sdp::attribute::{RemoteCandidates, TypedAttribute};
    let mut named = vec![];
    for m in &desc.media_descriptions {
        for a in m
            .attributes
            .iter()
            .filter(|a| a.key == ATTR_KEY_REMOTE_CANDIDATES)
        {
            let value = a.value.as_deref().unwrap_or_default();
            let parsed = RemoteCandidates::parse(value).map_err(|_| {
                Error::SdpInvalidValue(format!(
                    "a=remote-candidates:{value} (RFC 8839 section 5.2)"
                ))
            })?;
            if is_rejected_media(m) {
                continue;
            }
            named.extend(
                parsed
                    .candidates
                    .into_iter()
                    .filter(|c| c.component == 1)
                    .map(|c| (c.address, c.port)),
            );
        }
    }
    Ok(named)
}

/// The `ufrag` extension attribute of a candidate line (`candidate-attribute` without the
/// `candidate:` prefix), the ICE generation it names (RFC 8839 section 5.1, RFC 8838 section
/// 9).
pub(crate) fn candidate_line_ufrag(value: &str) -> Option<&str> {
    let fields: Vec<&str> = value.split_ascii_whitespace().collect();
    // foundation component transport priority address port "typ" type, then raddr/rport and
    // the extension pairs.
    let mut i = 8;
    while i + 1 < fields.len() {
        if fields[i] == "ufrag" {
            return Some(fields[i + 1]);
        }
        i += 2;
    }
    None
}
/// The `b=` lines that state a receive limit of `tias` bits per second: `b=TIAS:<tias>`
/// (RFC 3890) and `b=AS` (RFC 8866 section 5.8, kilobits per second) for peers that read only
/// that one, the smallest value from which RFC 9429 section 5.10 derives at least `tias`
/// ("TIAS = AS * 1000 * 0.95 - (50 * 40 * 8)").
pub(crate) fn receive_bandwidth_lines(tias: u64) -> [sdp::description::common::Bandwidth; 2] {
    use sdp::description::common::Bandwidth;
    let kbps = tias.saturating_add(50 * 40 * 8).div_ceil(950);
    [
        Bandwidth {
            experimental: false,
            bandwidth_type: "TIAS".to_owned(),
            bandwidth: tias,
        },
        Bandwidth {
            experimental: false,
            bandwidth_type: "AS".to_owned(),
            bandwidth: kbps,
        },
    ]
}

/// `a=ptime` (RFC 8866 section 6.4).
pub(crate) const ATTR_KEY_PTIME: &str = "ptime";
/// `a=maxptime` (RFC 8866 section 6.5).
pub(crate) const ATTR_KEY_MAXPTIME: &str = "maxptime";

/// The packet times a media section states (`a=ptime`, `a=maxptime`; RFC 8866 sections 6.4,
/// 6.5); a value that is not a whole number of milliseconds is not stated. RFC 8866 allows a
/// decimal `a=ptime`: it is rounded up.
pub(crate) fn media_packet_time(media: &MediaDescription) -> RTCPacketTime {
    let value = |key: &str| -> Option<u32> {
        let value = media.attribute(key)??.trim();
        match value.split_once('.') {
            None => value.parse().ok(),
            Some((whole, fraction)) => {
                let whole: u32 = if whole.is_empty() {
                    0
                } else {
                    whole.parse().ok()?
                };
                if !fraction.bytes().all(|b| b.is_ascii_digit()) {
                    return None;
                }
                Some(whole + u32::from(fraction.bytes().any(|b| b != b'0')))
            }
        }
    };
    RTCPacketTime {
        ptime: value(ATTR_KEY_PTIME),
        maxptime: value(ATTR_KEY_MAXPTIME),
    }
}

/// RFC 8859 section 4.7: `a=ptime` and `a=maxptime` are IDENTICAL-PER-PT, they "MUST have
/// identical values across all the media descriptions for a given RTP payload type when
/// repeated": two sections of one BUNDLE group that both state one and share a payload type
/// must state the same value. This endpoint writes one packet time for all its audio
/// sections, so its own descriptions hold it; a remote description that breaks it is refused.
pub(crate) fn check_bundled_packet_times(desc: &SessionDescription) -> Result<()> {
    for group in bundle_groups(desc) {
        let sections: Vec<&MediaDescription> = desc
            .media_descriptions
            .iter()
            .filter(|m| {
                !is_rejected_media(m)
                    && get_mid_value(m).is_some_and(|mid| group.contains(&mid.as_str()))
            })
            .collect();
        for (key, pick) in [
            (
                ATTR_KEY_PTIME,
                (|t: RTCPacketTime| t.ptime) as fn(RTCPacketTime) -> Option<u32>,
            ),
            (ATTR_KEY_MAXPTIME, |t: RTCPacketTime| t.maxptime),
        ] {
            let mut by_pt: HashMap<&str, u32> = HashMap::new();
            for media in &sections {
                let Some(value) = pick(media_packet_time(media)) else {
                    continue;
                };
                for pt in &media.media_name.formats {
                    match by_pt.get(pt.as_str()) {
                        Some(&other) if other != value => {
                            return Err(Error::SdpInvalidValue(format!(
                                "a={key} differs ({other} and {value}) for payload type {pt} \
                                 across bundled sections (RFC 8859 section 4.7)"
                            )));
                        }
                        Some(_) => {}
                        None => {
                            by_pt.insert(pt.as_str(), value);
                        }
                    }
                }
            }
        }
    }
    Ok(())
}

/// RFC 8859 section 4.3: an attribute of the IDENTICAL category is "repeated across all the
/// media descriptions under multiplexing" with the same value. RFC 9143 section 7.1.3 lets
/// an answer or a subsequent offer carry it in the tagged section only, from where it applies
/// to every bundled section (the note of section 4.3: such attributes "might not always be
/// explicitly encoded across all media descriptions"), so an absence is not a disagreement.
/// Two bundled sections that both carry one with different values are. A section that
/// carries one its tagged section lacks is not refused: RFC 9429 section 5.2.2 itself writes
/// `a=rtcp-mux-only` in a section a later offer adds and not in the tagged one, and a tagged
/// data section carries none of the RTP session's attributes. The category is rtci-sdp's
/// table (`sdp::attribute::mux`). The browser descriptions recorded by the interop harness
/// never disagree (Firefox carries `a=rtcp-rsize` and `a=extmap-allow-mixed` in the tagged
/// section only: absences).
pub(crate) fn check_bundled_identical_attributes(desc: &SessionDescription) -> Result<()> {
    use ::sdp::attribute::mux::{MuxCategory, category};
    let values = |media: &MediaDescription, key: &str| -> Option<Vec<String>> {
        let mut found: Vec<String> = media
            .attributes
            .iter()
            .filter(|a| a.key == key)
            .map(|a| {
                a.value
                    .as_deref()
                    .unwrap_or_default()
                    .split_whitespace()
                    .collect::<Vec<_>>()
                    .join(" ")
            })
            .collect();
        found.sort();
        (!found.is_empty()).then_some(found)
    };
    for media in &desc.media_descriptions {
        if is_rejected_media(media) {
            continue;
        }
        let Some(tagged) = tagged_section(desc, media) else {
            continue;
        };
        if std::ptr::eq(tagged, media) {
            continue;
        }
        let mut keys: Vec<&str> = media.attributes.iter().map(|a| a.key.as_str()).collect();
        keys.dedup();
        for key in keys {
            if category(key) != Some(MuxCategory::Identical) {
                continue;
            }
            let Some(own) = values(media, key) else {
                continue;
            };
            let mid = get_mid_value(media).map(String::as_str).unwrap_or_default();
            let tag = get_mid_value(tagged)
                .map(String::as_str)
                .unwrap_or_default();
            if let Some(theirs) = values(tagged, key)
                && theirs != own
            {
                return Err(Error::SdpInvalidValue(format!(
                    "a={key} differs between the bundled sections {mid} and {tag} (RFC 8859 \
                     section 4.3: IDENTICAL category)"
                )));
            }
        }
    }
    Ok(())
}

/// The Ta a description proposes (`a=ice-pacing`, RFC 8839 section 5.5: session level, a
/// value in milliseconds of 1 to 10 digits); `None` when it proposes none or the value is not
/// one (section 5.5: an agent that does not understand it uses the default).
pub(crate) fn remote_ice_pacing(desc: &SessionDescription) -> Option<std::time::Duration> {
    desc.attribute(ATTR_KEY_ICE_PACING)
        .map(|v| v.trim())
        .filter(|v| (1..=10).contains(&v.len()) && v.bytes().all(|b| b.is_ascii_digit()))
        .and_then(|v| v.parse::<u64>().ok())
        .map(std::time::Duration::from_millis)
}

/// The ICE options a description states (`a=ice-options`, RFC 8839 section 5.6), at session
/// level and in its media sections, each once, in order.
/// The options of an answer's `a=ice-options` line under `setting`, given the offer's
/// options (`remote_ice_options`): `trickle` first, then `ice2` (RFC 9429 section 5.3.1 for
/// [`AnswerIceOptions::AsOffered`]).
pub(crate) fn answer_ice_options(
    setting: AnswerIceOptions,
    offered: &[String],
) -> Vec<&'static str> {
    let offered = |option: &str| offered.iter().any(|o| o == option);
    let (trickle, ice2) = match setting {
        AnswerIceOptions::AsOffered => (offered("trickle"), offered("ice2")),
        AnswerIceOptions::TrickleAlways => (true, offered("ice2")),
        AnswerIceOptions::Always => (true, true),
    };
    [(trickle, "trickle"), (ice2, "ice2")]
        .into_iter()
        .filter_map(|(on, option)| on.then_some(option))
        .collect()
}

pub(crate) fn remote_ice_options(desc: &SessionDescription) -> Vec<String> {
    let mut out: Vec<String> = vec![];
    let values = desc
        .attributes
        .iter()
        .chain(
            desc.media_descriptions
                .iter()
                .flat_map(|m| m.attributes.iter()),
        )
        .filter(|a| a.key == ATTR_KEY_ICE_OPTIONS)
        .filter_map(|a| a.value.as_deref());
    for option in values.flat_map(str::split_whitespace) {
        if !out.iter().any(|o| o == option) {
            out.push(option.to_owned());
        }
    }
    out
}

pub(crate) const SDP_ATTRIBUTE_RID: &str = "rid";
pub(crate) const SDP_ATTRIBUTE_SIMULCAST: &str = "simulcast";
pub(crate) const GENERATED_CERTIFICATE_ORIGIN: &str = "WebRTC";
pub(crate) const MEDIA_SECTION_APPLICATION: &str = "application";

/// TrackDetails represents any media source that can be represented in a SDP
/// This isn't keyed by SSRC because it also needs to support rid based sources
#[derive(Default, Debug, Clone)]
pub(crate) struct TrackDetails {
    pub(crate) mid: String,
    pub(crate) kind: RtpCodecKind,
    /// The first MediaStream the track is in (`-` when it is in none), the id its
    /// `MediaStreamTrack` carries.
    pub(crate) stream_id: MediaStreamId,
    /// Every MediaStream the track is in, one per `a=msid` line, without `-` (RFC 8830
    /// section 2: "Multiple media descriptions with the same value for msid-id ... If
    /// multiple media descriptions ... one track in several streams").
    pub(crate) stream_ids: Vec<MediaStreamId>,
    /// The msid-appdata, the sender's track id. Empty when the `a=msid` lines carry none
    /// (the form RFC 9429 section 5.2.1 has senders write): the recipient names the track
    /// itself (RFC 8830 section 3).
    pub(crate) track_id: MediaStreamTrackId,
    pub(crate) ssrc: Option<SSRC>,
    pub(crate) rtx_ssrc: Option<SSRC>,
    pub(crate) fec_ssrc: Option<SSRC>,
    pub(crate) rids: Vec<String>,
    /// What each rid's `a=rid` line restricts the stream to (RFC 8851 section 5).
    pub(crate) rid_restrictions: HashMap<String, RTCRtpRidRestrictions>,
    /// The further simulcast streams of the track an `a=ssrc-group:SIM` names, after the
    /// first one (`ssrc`).
    pub(crate) ssrc_layers: Vec<SsrcLayer>,
    /// With `rids`: the streams the section also declares by SSRC (`a=ssrc`, each `SIM`
    /// member one), with the repair flows `a=ssrc-group:FID` / `FEC-FR` pair them with, in
    /// the order of their `a=ssrc` lines. RFC 9143 section 9.2 associates a packet whose SSRC
    /// the section declares with the section; a packet of one that carries no RID is received
    /// as a stream without a rid.
    pub(crate) declared_ssrcs: Vec<SsrcLayer>,
}

/// The `ssrc-group` semantics of simulcast streams sent as SSRCs of one track, without
/// RFC 8853 rids (registered in RFC 5576's registry by libwebrtc's use; "SIM").
const SEMANTIC_TOKEN_SIMULCAST: &str = "SIM";

/// A stream an m= section declares by SSRC with its repair flows (RFC 5576 section 4.2, RFC
/// 4588 section 8.1): one simulcast stream of an `a=ssrc-group:SIM` track, or a declared
/// stream of a section with `a=rid`.
#[derive(Default, Debug, Clone, PartialEq, Eq)]
pub(crate) struct SsrcLayer {
    pub(crate) ssrc: SSRC,
    pub(crate) rtx_ssrc: Option<SSRC>,
    pub(crate) fec_ssrc: Option<SSRC>,
}

/// What the `a=ssrc-group` lines of a media section say (RFC 5576 section 4.2): a group
/// lists one or more ssrc-ids, and any number of them.
#[derive(Default, Debug)]
struct SsrcGroups {
    /// The RTX flow of each primary: the second id of its `FID` group (RFC 4588 section 8.6).
    rtx: HashMap<SSRC, SSRC>,
    /// The FEC repair flow of each source of a `FEC-FR` group (RFC 5956 section 4.3).
    fec: HashMap<SSRC, SSRC>,
    /// Every SSRC that is a repair flow of another, not a track of its own.
    repair_flows: HashSet<SSRC>,
    /// The members of each `SIM` group, in order.
    simulcast: Vec<Vec<SSRC>>,
}

impl SsrcGroups {
    fn of(media: &MediaDescription) -> Self {
        let mut lists: Vec<(&str, Vec<SSRC>)> = vec![];
        for value in media
            .attributes
            .iter()
            .filter(|a| a.key == ATTR_KEY_SSRC_GROUP)
            .filter_map(|a| a.value.as_deref())
        {
            let mut tokens = value.split(' ');
            let semantics = tokens.next().unwrap_or_default();
            let Ok(ids) = tokens
                .map(str::parse::<SSRC>)
                .collect::<std::result::Result<Vec<_>, _>>()
            else {
                log::warn!("a=ssrc-group:{value}: an ssrc-id is not a number");
                continue;
            };
            if !ids.is_empty() {
                lists.push((semantics, ids));
            }
        }

        let mut groups = SsrcGroups::default();
        // `FID` (RFC 5888 section 8.4, RFC 4588 section 8.6): the first id is the source,
        // every further one a flow of the same source, the first of them its RTX flow.
        let mut primaries: HashSet<SSRC> = HashSet::new();
        for (semantics, ids) in &lists {
            if *semantics == SEMANTIC_TOKEN_FLOW_IDENTIFICATION && ids.len() >= 2 {
                groups.rtx.entry(ids[0]).or_insert(ids[1]);
                groups.repair_flows.extend(&ids[1..]);
                primaries.insert(ids[0]);
            } else if *semantics == SEMANTIC_TOKEN_SIMULCAST {
                primaries.extend(ids);
            }
        }
        // `FEC-FR` (RFC 5956 sections 4.1, 4.3): one or more source flows and the additive
        // repair flows that protect them. The first id is a source (as WebRTC writes it,
        // `FEC-FR <source> <repair>`, RFC 8627 section 6); a further id is a source too when
        // it is a primary of its own (an `FID` source or a `SIM` stream, as `S1 S2 R2` in
        // section 4.2), a repair flow otherwise.
        for (semantics, ids) in &lists {
            if *semantics != SEMANTIC_TOKEN_FORWARD_ERROR_CORRECTION_FRAMEWORK || ids.len() < 2 {
                continue;
            }
            let (mut sources, mut repairs): (Vec<SSRC>, Vec<SSRC>) = (vec![], vec![]);
            for (i, ssrc) in ids.iter().enumerate() {
                if i == 0 || primaries.contains(ssrc) {
                    sources.push(*ssrc);
                } else {
                    repairs.push(*ssrc);
                }
            }
            let Some(&repair) = repairs.first() else {
                continue;
            };
            for source in sources {
                groups.fec.entry(source).or_insert(repair);
            }
            groups.repair_flows.extend(repairs);
        }
        groups.simulcast = lists
            .into_iter()
            .filter(|(semantics, ids)| *semantics == SEMANTIC_TOKEN_SIMULCAST && ids.len() >= 2)
            .map(|(_, ids)| ids)
            .collect();
        for members in &mut groups.simulcast {
            members.retain(|ssrc| !groups.repair_flows.contains(ssrc));
        }
        groups
    }
}

pub(crate) fn track_details_for_ssrc(
    track_details: &[TrackDetails],
    ssrc: SSRC,
) -> Option<&TrackDetails> {
    track_details.iter().find(|x| x.ssrc == Some(ssrc))
}

pub(crate) fn track_details_for_rid<'a>(
    track_details: &'a [TrackDetails],
    mid: &String,
    rid: &String,
) -> Option<&'a TrackDetails> {
    track_details
        .iter()
        .find(|x| &x.mid == mid && x.rids.contains(rid))
}

/// extract all TrackDetails from an SDP.
///
/// Rid-ids are read with `rid_ids` (`SettingEngine::rid_id_grammar`).
pub(crate) fn track_details_from_sdp(
    s: &SessionDescription,
    rid_ids: RidIdGrammar,
) -> Vec<TrackDetails> {
    let mut incoming_tracks = vec![];

    for media in &s.media_descriptions {
        // Tracks in the order their `a=ssrc` lines first appear. A track a later
        // `a=ssrc-group` names as a repair flow is removed by clearing its slot, and
        // `slot_by_ssrc` finds a track by SSRC (unique within the section) without a scan.
        let mut track_slots: Vec<Option<TrackDetails>> = vec![];
        let mut slot_by_ssrc: HashMap<SSRC, usize> = HashMap::new();

        // The section's `a=msid` lines (RFC 8830 section 2), read before anything else: they
        // name the track's streams whatever a legacy `a=ssrc:<n> msid:` attribute says.
        let msid = media_msid(media);
        let has_media_msid = msid.is_some();
        let (stream_ids, msid_track_id) = msid.unwrap_or_default();
        let mut stream_id = if has_media_msid {
            stream_ids.first().map_or("-", String::as_str)
        } else {
            ""
        };
        let mut track_id = msid_track_id.as_str();

        // If media section is recvonly or inactive skip
        if media.attribute(ATTR_KEY_RECV_ONLY).is_some()
            || media.attribute(ATTR_KEY_INACTIVE).is_some()
        {
            continue;
        }

        let mid_value = match get_mid_value(media) {
            Some(mid_value) if !mid_value.is_empty() => mid_value,
            _ => continue,
        };

        if media.is_webrtc_datachannel() {
            continue;
        }

        let codec_type = RtpCodecKind::from(media.media_name.media.as_str());
        if codec_type == RtpCodecKind::Unspecified || is_unknown_media_protocol(media) {
            continue;
        }

        // RFC 5576 section 4.2: a group "MUST list at least one <ssrc-id> for a group and MAY
        // list any number of additional ones". Read before the `a=ssrc` lines, wherever the
        // groups stand in the section.
        let groups = SsrcGroups::of(media);

        for attr in &media.attributes {
            match attr.key.as_str() {
                // Handle `a=msid:<stream_id> <track_label>` The first value is the same as MediaStream.id
                // in the browser and can be used to figure out which tracks belong to the same stream. The browser should
                // figure this out automatically when an ontrack event is emitted on RTCPeerConnection.
                // `a=msid` lines were read by `media_msid` above.
                ATTR_KEY_MSID => {}

                ATTR_KEY_SSRC => {
                    if let Some(value) = &attr.value {
                        let split: Vec<&str> = value.split(' ').collect();
                        let ssrc = match split[0].parse::<u32>() {
                            Ok(ssrc) => ssrc,
                            Err(err) => {
                                log::warn!("Failed to parse SSRC: {err}");
                                continue;
                            }
                        };

                        if groups.repair_flows.contains(&ssrc) {
                            continue; // A repair flow (RTX, FEC) of a primary, not a track.
                        }

                        // The source-level msid of a description without `a=msid` lines
                        // (the form that predates them).
                        if !has_media_msid && split.len() == 3 && split[1].starts_with("msid:") {
                            stream_id = &split[1]["msid:".len()..];
                            track_id = split[2];
                        }

                        if let Some(track) = slot_by_ssrc
                            .get(&ssrc)
                            .and_then(|&slot| track_slots[slot].as_mut())
                        {
                            track.mid = mid_value.to_string();
                            track.kind = codec_type;
                            stream_id.clone_into(&mut track.stream_id);
                            track_id.clone_into(&mut track.track_id);
                            track.ssrc = Some(ssrc);
                        } else {
                            let track_details = TrackDetails {
                                mid: mid_value.to_string(),
                                kind: codec_type,
                                stream_id: stream_id.to_owned(),
                                track_id: track_id.to_owned(),
                                ssrc: Some(ssrc),
                                ..Default::default()
                            };
                            slot_by_ssrc.insert(ssrc, track_slots.len());
                            track_slots.push(Some(track_details));
                        }
                    }
                }
                _ => {}
            };
        }

        for track in track_slots.iter_mut().flatten() {
            if let Some(ssrc) = track.ssrc {
                track.rtx_ssrc = groups.rtx.get(&ssrc).copied();
                track.fec_ssrc = groups.fec.get(&ssrc).copied();
            }
        }

        // RFC 5576 section 4.2 with the `SIM` semantics: the sources of a group are the
        // simulcast streams of one track, the first one's track; the others are its further
        // layers, each with its repair flows.
        for members in &groups.simulcast {
            let mut present = members
                .iter()
                .filter_map(|ssrc| slot_by_ssrc.get(ssrc).map(|&slot| (*ssrc, slot)));
            let Some((_, keeper)) = present.next() else {
                continue;
            };
            let layers: Vec<(SSRC, usize)> = present.collect();
            for (ssrc, slot) in layers {
                if slot == keeper || track_slots[slot].take().is_none() {
                    continue;
                }
                if let Some(track) = track_slots[keeper].as_mut() {
                    track.ssrc_layers.push(SsrcLayer {
                        ssrc,
                        rtx_ssrc: groups.rtx.get(&ssrc).copied(),
                        fec_ssrc: groups.fec.get(&ssrc).copied(),
                    });
                }
            }
        }

        let mut tracks_in_media_section: Vec<TrackDetails> =
            track_slots.into_iter().flatten().collect();
        // Every track of the section is in the streams its `a=msid` lines name; without such
        // lines, in the one its source-level msid names.
        let stream_ids_of = |stream_id: &str| -> Vec<MediaStreamId> {
            if has_media_msid {
                stream_ids.clone()
            } else if stream_id.is_empty() || stream_id == "-" {
                vec![]
            } else {
                vec![stream_id.to_owned()]
            }
        };
        for track in &mut tracks_in_media_section {
            if has_media_msid {
                // One track, whichever `a=ssrc` line it was read from.
                stream_id.clone_into(&mut track.stream_id);
                track_id.clone_into(&mut track.track_id);
            }
            track.stream_ids = stream_ids_of(&track.stream_id);
        }

        // If media line is using RTP Stream Identifier Source Description per RFC8851
        // the section is one track whose streams are its rids. Its `a=ssrc` lines (Firefox
        // and Pion write them beside 'rid' and 'simulcast') are kept on that track as the
        // SSRCs the section declares (RFC 9143 section 9.2): a packet that carries a RID is
        // bound by its rid, one that carries none by its declared SSRC.
        if has_media_msid || (!track_id.is_empty() && !stream_id.is_empty()) {
            // The streams the remote side sends: its `send` rids. A `recv` rid is one of this
            // endpoint's own streams, which the remote side takes.
            let rids: Vec<SimulcastRid> = get_rids(media, rid_ids)
                .into_iter()
                .filter(|rid| rid.direction == SimulcastDirection::Send)
                .collect();
            if !rids.is_empty() {
                let simulcast_track = TrackDetails {
                    mid: mid_value.to_string(),
                    kind: codec_type,
                    stream_id: stream_id.to_owned(),
                    stream_ids: stream_ids_of(stream_id),
                    track_id: track_id.to_owned(),
                    rids: rids.iter().map(|r| r.id.clone()).collect(),
                    rid_restrictions: rids
                        .iter()
                        .map(|r| (r.id.clone(), r.to_restrictions()))
                        .collect(),
                    // Each track's SSRC, then its further `SIM` streams: every one a
                    // declared primary with its own repair flows.
                    declared_ssrcs: tracks_in_media_section
                        .iter()
                        .flat_map(|track| {
                            track
                                .ssrc
                                .map(|ssrc| SsrcLayer {
                                    ssrc,
                                    rtx_ssrc: track.rtx_ssrc,
                                    fec_ssrc: track.fec_ssrc,
                                })
                                .into_iter()
                                .chain(track.ssrc_layers.iter().cloned())
                        })
                        .collect(),
                    ..Default::default()
                };

                tracks_in_media_section = vec![simulcast_track];
            } else if tracks_in_media_section.is_empty() {
                // no rids, no ssrc set
                let implicit_track = TrackDetails {
                    mid: mid_value.to_string(),
                    kind: codec_type,
                    stream_id: stream_id.to_owned(),
                    stream_ids: stream_ids_of(stream_id),
                    track_id: track_id.to_owned(),
                    ..Default::default()
                };

                tracks_in_media_section = vec![implicit_track];
            }
        }

        incoming_tracks.extend(tracks_in_media_section);
    }

    incoming_tracks
}

/// The `a=msid` lines of a media section (RFC 8830 section 2, `msid-id [SP msid-appdata]`):
/// the MediaStream ids they name, in order and once each, without the `-` that stands for
/// "no MediaStream" (RFC 8830 section 3), and the msid-appdata of the first line that has
/// one. `None` when the section has no well-formed `a=msid` line; a line that is not
/// `msid-id [SP msid-appdata]` is ignored (section 3: "SHOULD be ignored").
///
/// RFC 9429 section 5.8.2 reads the lines "ignoring appdata"; the appdata is still returned,
/// because a sender that writes it means its track id (RFC 8830 section 3).
pub(crate) fn media_msid(media: &MediaDescription) -> Option<(Vec<MediaStreamId>, String)> {
    let mut found = false;
    let mut stream_ids: Vec<MediaStreamId> = vec![];
    let mut track_id = String::new();
    for value in media
        .attributes
        .iter()
        .filter(|a| a.key == ATTR_KEY_MSID)
        .filter_map(|a| a.value.as_deref())
    {
        let mut tokens = value.split(' ');
        let (Some(id), appdata, None) = (tokens.next(), tokens.next(), tokens.next()) else {
            continue;
        };
        if !is_msid_token(id) || appdata.is_some_and(|appdata| !is_msid_token(appdata)) {
            continue;
        }
        found = true;
        if id != "-" && !stream_ids.iter().any(|known| known == id) {
            stream_ids.push(id.to_owned());
        }
        if let (true, Some(appdata)) = (track_id.is_empty(), appdata) {
            appdata.clone_into(&mut track_id);
        }
    }
    found.then_some((stream_ids, track_id))
}

#[test]
fn track_details_from_sdp_pairs_repair_flows_by_lookup() {
    const PRIMARIES: u32 = 3000;
    let mut media = MediaDescription::default()
        .with_value_attribute(ATTR_KEY_MID.to_owned(), "0".to_owned())
        .with_property_attribute(ATTR_KEY_SEND_RECV.to_owned());
    media.media_name.media = "video".to_owned();
    for i in 0..PRIMARIES {
        let (primary, rtx, fec) = (10_000 + i, 20_000 + i, 30_000 + i);
        // Half the groups follow their ssrc lines (the repair track is removed again), half
        // precede them (the repair ssrc is never added).
        let group_first = i % 2 == 0;
        if group_first {
            media = media
                .with_value_attribute(
                    ATTR_KEY_SSRC_GROUP.to_owned(),
                    format!("FID {primary} {rtx}"),
                )
                .with_value_attribute(
                    ATTR_KEY_SSRC_GROUP.to_owned(),
                    format!("FEC-FR {primary} {fec}"),
                );
        }
        for ssrc in [primary, rtx, fec] {
            media = media.with_value_attribute(
                ATTR_KEY_SSRC.to_owned(),
                format!("{ssrc} msid:stream track{i}"),
            );
        }
        if !group_first {
            media = media
                .with_value_attribute(
                    ATTR_KEY_SSRC_GROUP.to_owned(),
                    format!("FID {primary} {rtx}"),
                )
                .with_value_attribute(
                    ATTR_KEY_SSRC_GROUP.to_owned(),
                    format!("FEC-FR {primary} {fec}"),
                );
        }
    }
    let desc = SessionDescription::default().with_media(media);

    let tracks = track_details_from_sdp(&desc, RidIdGrammar::Corrected);

    assert_eq!(tracks.len(), PRIMARIES as usize);
    for (i, track) in tracks.iter().enumerate() {
        let i = i as u32;
        assert_eq!(track.ssrc, Some(10_000 + i));
        assert_eq!(track.rtx_ssrc, Some(20_000 + i));
        assert_eq!(track.fec_ssrc, Some(30_000 + i));
        assert_eq!(track.track_id, format!("track{i}"));
        assert_eq!(track.mid, "0");
    }
}

/// RFC 5576 section 4.2: a group "MAY list any number of additional" ids. A `FID` group of
/// three is a source and two further flows of it, the first of them its RTX flow; a `FEC-FR`
/// group of three is one source and two additive repair flows (RFC 5956 section 4.1). No flow
/// a group names as a repair flow is a track.
#[test]
fn groups_of_three_ids_name_one_source_and_its_flows() {
    let mut media = MediaDescription::default()
        .with_value_attribute(ATTR_KEY_MID.to_owned(), "0".to_owned())
        .with_property_attribute(ATTR_KEY_SEND_RECV.to_owned())
        .with_value_attribute(ATTR_KEY_SSRC_GROUP.to_owned(), "FID 4 14 24".to_owned())
        .with_value_attribute(ATTR_KEY_SSRC_GROUP.to_owned(), "FEC-FR 4 34 44".to_owned());
    media.media_name.media = "video".to_owned();
    for ssrc in [4, 14, 24, 34, 44] {
        media = media.with_value_attribute(
            ATTR_KEY_SSRC.to_owned(),
            format!("{ssrc} msid:stream track"),
        );
    }
    let tracks = track_details_from_sdp(
        &SessionDescription::default().with_media(media),
        RidIdGrammar::Corrected,
    );
    assert_eq!(tracks.len(), 1, "{tracks:?}");
    assert_eq!(tracks[0].ssrc, Some(4));
    assert_eq!(tracks[0].rtx_ssrc, Some(14));
    assert_eq!(tracks[0].fec_ssrc, Some(34));
    assert!(tracks[0].ssrc_layers.is_empty());
}

#[test]
fn get_rids_orders_and_pauses_by_lookup() {
    const RIDS: usize = 3000;
    let mut media = MediaDescription::default();
    media.media_name.media = "video".to_owned();
    for i in 0..RIDS {
        media = media.with_value_attribute(SDP_ATTRIBUTE_RID.to_owned(), format!("r{i} send"));
    }
    // Reverse order, every third one paused, and one unknown id.
    let mut list: Vec<String> = (0..RIDS)
        .rev()
        .map(|i| {
            if i % 3 == 0 {
                format!("~r{i}")
            } else {
                format!("r{i}")
            }
        })
        .collect();
    list.push("unknown".to_owned());
    let simulcast = media.clone().with_value_attribute(
        SDP_ATTRIBUTE_SIMULCAST.to_owned(),
        format!("send {}", list.join(";")),
    );

    let rids = get_rids(&simulcast, RidIdGrammar::Corrected);

    assert_eq!(rids.len(), RIDS);
    for (position, rid) in rids.iter().enumerate() {
        let i = RIDS - 1 - position;
        assert_eq!(rid.id, format!("r{i}"));
        assert_eq!(rid.paused, i % 3 == 0, "rid r{i}");
        assert!(rid.simulcast);
    }

    // RFC 8853 section 5.2: a rid-id "MUST NOT" occur twice on the line. One that does is
    // malformed and not used: the rids stay, in a=rid order, as no simulcast streams.
    list.push("r1".to_owned());
    let repeated = media.with_value_attribute(
        SDP_ATTRIBUTE_SIMULCAST.to_owned(),
        format!("send {}", list.join(";")),
    );
    let rids = get_rids(&repeated, RidIdGrammar::Corrected);
    assert_eq!(rids.len(), RIDS);
    assert!(
        rids.iter()
            .enumerate()
            .all(|(i, rid)| rid.id == format!("r{i}") && !rid.simulcast)
    );
}

/// `a=rtcp` (RFC 3605 section 2.1).
pub(crate) const ATTR_KEY_RTCP: &str = "rtcp";

/// The default candidate of a section (RFC 8839 section 4.2.1.2: the one "most likely to
/// work": a relayed candidate, else a server-reflexive one, else a host candidate; RTP,
/// component 1), as (address, port). UDP candidates are preferred, as the m= line says UDP.
/// A candidate whose address is not an IP address (an mDNS name) is never the default (the
/// mDNS ICE candidates draft, section 3.1.2.2: the `c=` line then says 0.0.0.0 and port 9).
fn default_candidate(candidates: &[RTCIceCandidate]) -> Option<(std::net::IpAddr, u16)> {
    use crate::peer_connection::transport::ice::candidate_type::RTCIceCandidateType as Type;
    use crate::peer_connection::transport::ice::protocol::RTCIceProtocol;
    let rank = |c: &RTCIceCandidate| -> u8 {
        match c.typ {
            Type::Relay => 0,
            Type::Srflx => 1,
            Type::Prflx => 2,
            _ => 3,
        }
    };
    candidates
        .iter()
        .filter_map(|c| Some((c, c.address.parse::<std::net::IpAddr>().ok()?)))
        .filter(|(c, _)| c.port != 0)
        .min_by_key(|(c, _)| {
            (
                c.protocol != RTCIceProtocol::Udp,
                rank(c),
                std::cmp::Reverse(c.priority),
            )
        })
        .map(|(c, ip)| (ip, c.port))
}

/// Puts a default destination in a section: the `m=` port and `c=` address, and the `a=rtcp`
/// line when the section has one (RTCP is multiplexed, so it is the RTP destination too; RFC
/// 5761 section 5.1.3).
pub(crate) fn set_default_destination(m: &mut MediaDescription, ip: std::net::IpAddr, port: u16) {
    m.media_name.port = RangedPort {
        value: port as isize,
        range: None,
    };
    let address_type = if ip.is_ipv4() { "IP4" } else { "IP6" };
    m.connection_information = vec![ConnectionInformation {
        network_type: "IN".to_owned(),
        address_type: address_type.to_owned(),
        address: Some(Address {
            address: ip.to_string(),
            ttl: None,
            range: None,
        }),
    }];
    for a in &mut m.attributes {
        if a.key == ATTR_KEY_RTCP {
            a.value = Some(format!("{port} IN {address_type} {ip}"));
        }
    }
}

/// RFC 9143 section 7.2 (and 7.5.1 for later offers): the bundled sections that are not
/// bundle-only share the BUNDLE transport's address and port, the default destination of the
/// section of their group that carries the candidates. Each BUNDLE group is a transport of its
/// own (section 5), with its own destination.
pub(crate) fn share_bundle_destination(d: &mut SessionDescription) {
    let groups: Vec<Vec<String>> = bundle_groups(d)
        .into_iter()
        .map(|group| group.into_iter().map(str::to_owned).collect())
        .collect();
    for group in groups {
        let in_group =
            |m: &MediaDescription| get_mid_value(m).is_some_and(|mid| group.contains(mid));
        let Some(carrier) = d.media_descriptions.iter().find(|m| {
            in_group(m) && m.attribute("candidate").is_some() && m.media_name.port.value != 0
        }) else {
            continue;
        };
        let Some(ip) = carrier
            .connection_information
            .first()
            .and_then(|c| c.address.as_ref())
            .and_then(|a| a.address.parse::<std::net::IpAddr>().ok())
        else {
            continue;
        };
        let Ok(port) = u16::try_from(carrier.media_name.port.value) else {
            continue;
        };
        if ip.is_unspecified() {
            continue;
        }
        for m in &mut d.media_descriptions {
            if m.media_name.port.value != 0 && !m.has_attribute(ATTR_KEY_BUNDLE_ONLY) && in_group(m)
            {
                set_default_destination(m, ip, port);
            }
        }
    }
}

pub(crate) fn add_candidates_to_media_descriptions(
    candidates: &[RTCIceCandidate],
    mut m: MediaDescription,
    ice_gathering_state: RTCIceGatheringState,
) -> Result<MediaDescription> {
    // Each line names its ICE generation with the `ufrag` extension attribute (RFC 8839
    // section 5.1 `extension-att-name`; RFC 8838 section 9: a candidate is tied to an ICE
    // session), the section's own `a=ice-ufrag`, as trickled candidates already do
    // (`usernameFragment`).
    let ufrag = m
        .attribute("ice-ufrag")
        .flatten()
        .filter(|ufrag| !ufrag.is_empty())
        .map(str::to_owned);
    let append_candidate_if_new = |c: &Candidate, m: MediaDescription| -> MediaDescription {
        let mut marshaled = c.marshal();
        if let Some(ufrag) = &ufrag {
            marshaled = format!("{marshaled} ufrag {ufrag}");
        }
        for a in &m.attributes {
            if let Some(value) = &a.value
                && &marshaled == value
            {
                return m;
            }
        }

        m.with_value_attribute("candidate".to_owned(), marshaled)
    };

    // RTP candidates only (component 1). RTP and RTCP are multiplexed on one port, so there
    // is no RTCP component to describe: RFC 8858 section 5.3 (updating RFC 8839), "the offerer
    // MUST NOT include RTCP candidates" when it cannot use a separate RTCP port, and RFC 5761
    // section 5.1.3 for the answer.
    for c in candidates {
        let mut candidate = c.to_ice()?;
        candidate.set_component(1);
        m = append_candidate_if_new(&candidate, m);
    }
    // RFC 8839 section 4.2.1.2 and RFC 9429 sections 5.2.2, 5.3.2: once there are candidates,
    // the m= and c= lines carry the default candidate's port and address (the dummy 9 and
    // 0.0.0.0 stand for "no candidates yet").
    if m.media_name.port.value != 0
        && let Some((ip, port)) = default_candidate(candidates)
    {
        set_default_destination(&mut m, ip, port);
    }

    if ice_gathering_state != RTCIceGatheringState::Complete {
        return Ok(m);
    }
    for a in &m.attributes {
        if &a.key == "end-of-candidates" {
            return Ok(m);
        }
    }

    Ok(m.with_property_attribute("end-of-candidates".to_owned()))
}

pub(crate) struct AddDataMediaSectionParams {
    should_add_candidates: bool,
    mid_value: String,
    ice_params: RTCIceParameters,
    dtls_role: ConnectionRole,
    ice_gathering_state: RTCIceGatheringState,
    sctp_max_message_size: usize,
    /// The `a=sctp-port` value (RFC 8841 section 5); 0 asks for no association.
    sctp_port: u16,
    /// Whether the m= line says `TCP/DTLS/SCTP`: in an answer, when the offer does (RFC 8841
    /// section 10.3: "an 'm=' line proto value identical to the value in the offer").
    sctp_over_tcp: bool,
}

pub(crate) fn add_data_media_section(
    d: SessionDescription,
    dtls_fingerprints: &[RTCDtlsFingerprint],
    candidates: &[RTCIceCandidate],
    params: AddDataMediaSectionParams,
) -> Result<SessionDescription> {
    let mut media = MediaDescription {
        media_name: MediaName {
            media: MEDIA_SECTION_APPLICATION.to_owned(),
            port: RangedPort {
                value: 9,
                range: None,
            },
            protos: vec![
                if params.sctp_over_tcp { "TCP" } else { "UDP" }.to_owned(),
                "DTLS".to_owned(),
                "SCTP".to_owned(),
            ],
            formats: vec!["webrtc-datachannel".to_owned()],
        },
        media_title: None,
        connection_information: vec![ConnectionInformation {
            network_type: "IN".to_owned(),
            address_type: "IP4".to_owned(),
            address: Some(Address {
                address: "0.0.0.0".to_owned(),
                ttl: None,
                range: None,
            }),
        }],
        bandwidth: vec![],
        encryption_key: None,
        attributes: vec![],
    }
    .with_value_attribute(
        ATTR_KEY_CONNECTION_SETUP.to_owned(),
        params.dtls_role.to_string(),
    )
    .with_value_attribute(ATTR_KEY_MID.to_owned(), params.mid_value)
    .with_property_attribute(RTCRtpTransceiverDirection::Sendrecv.to_string())
    .with_value_attribute("sctp-port".to_owned(), params.sctp_port.to_string())
    // RFC 8841 6.1: 0 would promise messages of any size, which this endpoint cannot take:
    // what it accepts is bounded by `SctpMaxMessageSize::MAX_MESSAGE_SIZE`, so that bound is
    // advertised instead, and it is the limit the SCTP transport receives by.
    .with_value_attribute(
        "max-message-size".to_owned(),
        format!(
            "{}",
            match params.sctp_max_message_size {
                0 => crate::peer_connection::configuration::setting_engine::SctpMaxMessageSize::MAX_MESSAGE_SIZE
                    as usize,
                limit => limit,
            }
        ),
    )
    .with_ice_credentials(
        params.ice_params.username_fragment,
        params.ice_params.password,
    );

    for f in dtls_fingerprints {
        media = media.with_fingerprint(f.algorithm.clone(), f.value.to_uppercase());
    }

    if params.should_add_candidates {
        media =
            add_candidates_to_media_descriptions(candidates, media, params.ice_gathering_state)?;
    }

    Ok(d.with_media(media))
}

pub(crate) struct AddTransceiverSdpParams {
    should_add_candidates: bool,
    mid_value: String,
    dtls_role: ConnectionRole,
    ice_gathering_state: RTCIceGatheringState,
    ignore_rid_pause_for_recv: bool,
    /// `SettingEngineBuilder::with_rid_pause_marks`: `~` is written without RFC 7728.
    rid_pause_marks: bool,
    /// The video receive limits (`a=imageattr`, RFC 9429 section 3.6.1): for every codec,
    /// and by MIME type.
    video_receive_limits: Option<RTCVideoResolutionRange>,
    codec_video_receive_limits: Vec<(String, RTCVideoResolutionRange)>,
    /// `SettingEngineBuilder::with_w3c_simulcast_answer`: an answer's `a=rid` lines have no
    /// restrictions.
    w3c_simulcast_answer: bool,
    /// `SettingEngineBuilder::with_msid_appdata`: `a=msid` lines carry the track id.
    msid_appdata: bool,
    write_ssrc_attributes_for_simulcast: bool,
    /// An offer (initial or subsequent) rather than an answer.
    is_offer: bool,
    /// The RTCP mux policy is "require".
    rtcp_mux_only: bool,
    /// `SettingEngineBuilder::with_rtcp_mux_only_in_subsequent_offers`: a section a subsequent
    /// offer carries over says `a=rtcp-mux-only` again (RFC 8858 section 4.5).
    rtcp_mux_only_renegotiated: bool,
    /// `SettingEngineBuilder::with_ecn` with the initiation it prefers, unless ECN is used
    /// without signalling (`with_ecn_without_signalling`): `a=ecn-capable-rtp` is written.
    ecn: Option<interceptor::EcnInitiation>,
    /// The payload type each format an answer may add (RFC 9429 section 5.3.1) takes, by
    /// (SFrame numbering, kind, the format's own payload type): see `answer_payload_types`.
    answer_payload_types: HashMap<(bool, RtpCodecKind, u8), u8>,
    /// `SettingEngineBuilder::with_answer_offered_formats_only`: an answer lists only formats
    /// the offer has.
    answer_offered_formats_only: bool,
}

impl RTCPeerConnection {
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn add_transceiver_sdp(
        mut d: SessionDescription,
        dtls_fingerprints: &[RTCDtlsFingerprint],
        media_engine: &MediaEngine,
        transceivers: &mut [RTCRtpTransceiverInternal],
        ice_params: &RTCIceParameters,
        candidates: &[RTCIceCandidate],
        media_section: &MediaSection,
        params: AddTransceiverSdpParams,
    ) -> Result<(SessionDescription, bool)> {
        let (
            should_add_candidates,
            mid_value,
            dtls_role,
            ice_gathering_state,
            ignore_rid_pause_for_recv,
            write_ssrc_attributes_for_simulcast,
            is_offer,
        ) = (
            params.should_add_candidates,
            params.mid_value,
            params.dtls_role,
            params.ice_gathering_state,
            params.ignore_rid_pause_for_recv,
            params.write_ssrc_attributes_for_simulcast,
            params.is_offer,
        );

        let transceiver = &mut transceivers[media_section.transceiver_index];
        let mut media =
            MediaDescription::new_jsep_media_description(transceiver.kind().to_string(), vec![])
                .with_value_attribute(ATTR_KEY_CONNECTION_SETUP.to_owned(), dtls_role.to_string())
                .with_value_attribute(ATTR_KEY_MID.to_owned(), mid_value.clone())
                .with_ice_credentials(
                    ice_params.username_fragment.clone(),
                    ice_params.password.clone(),
                )
                .with_property_attribute(ATTR_KEY_RTCPMUX.to_owned());
        // Under the mux policy "require" a new m= section of an offer says this endpoint only
        // multiplexes (RFC 9429 sections 4.1.1 and 5.2.1, RFC 8858 section 4.2); a section
        // negotiated before does not get the line (RFC 9429 section 5.2.2: "The
        // 'a=rtcp-mux-only' line MUST NOT be added"), unless the application asked for RFC
        // 8858 section 4.5's form ("the offerer SHOULD associate an SDP 'rtcp-mux-only' with
        // the corresponding SDP media description"). An answer does not carry it (RFC 8858
        // section 4.3), but for the answerer-tagged section of a BUNDLE group whose offer had
        // it (RFC 9143 section 9.3.1.2), which `populate_sdp` adds.
        if is_offer
            && params.rtcp_mux_only
            && (!media_section.renegotiated || params.rtcp_mux_only_renegotiated)
        {
            media = media.with_property_attribute(ATTR_KEY_RTCP_MUX_ONLY.to_owned());
        }
        // RFC 9429 section 5.2.1: an offer's new section has "An "a=rtcp" line ... containing
        // the default value "9 IN IP4 0.0.0.0"" (the default candidate's once there is one);
        // section 5.2.2: "The "a=rtcp" line MUST NOT be added if the most recent answer
        // included an "a=rtcp-mux" line", which this endpoint's answers always do. An answer
        // to an offer with `a=rtcp-mux` has none either (section 5.3.1).
        if is_offer && !media_section.renegotiated {
            media =
                media.with_value_attribute(ATTR_KEY_RTCP.to_owned(), "9 IN IP4 0.0.0.0".to_owned());
        }
        // Reduced-size RTCP (RFC 5506 section 5).
        if media_section.offered_rtcp_rsize.unwrap_or(true) {
            media = media.with_property_attribute(ATTR_KEY_RTCPRSIZE.to_owned());
        }
        // draft-ietf-avtcore-rtp-sframe-03 section 6 / webrtc-encoded-transform 2.1: the
        // transceiver's media is SFrame-encrypted.
        if transceiver.describe_sframe(is_offer) {
            media = media.with_property_attribute(ATTR_KEY_SFRAME.to_owned());
        }

        // RFC 9429 section 5.2.2: a later offer lists every available format, not only the
        // negotiated ones.
        let codecs = if is_offer {
            transceiver.get_offer_codecs(media_engine)
        } else {
            transceiver.get_codecs(media_engine)
        };
        // `SettingEngineBuilder::with_answer_offered_formats_only`: the answer lists the
        // offered formats only (RFC 9429 section 5.3.1 "MAY include formats that are locally
        // supported but not present in the offer"; libwebrtc's form), also when codec
        // preferences name a format the offer lacks.
        let codecs = match &media_section.offered_codecs {
            Some(offered) if !is_offer && params.answer_offered_formats_only => {
                offered_formats_only(codecs, offered)
            }
            _ => codecs,
        };
        // Which repair flows the section has a format for: a sender's RTX / FlexFEC SSRCs are
        // described only then (codec preferences may leave either out). The FEC flow is the
        // FlexFEC coder's: draft-03 (`video/flexfec-03`) or RFC 8627 (`video/flexfec`), each
        // matched exactly as the sender's `find_fec_format` does.
        let repair_flows = RepairFlows {
            rtx: codecs.iter().any(|c| repair_family(&c.rtp_codec) == "rtx"),
            fec: codecs
                .iter()
                .any(|c| is_fec_mime_type(&c.rtp_codec.mime_type)),
        };
        let mut ccfb = false;
        let mut nack_ecn = false;
        let mut rrtr = false;
        // The `xr-format`s other than `rcvr-rtt` the section's formats have (RFC 3611 section
        // 5.1), in the order met: `ecn-sum` with ECN (RFC 6679 section 6.3).
        let mut xr_formats: Vec<String> = vec![];
        for codec in &codecs {
            let name = codec
                .rtp_codec
                .mime_type
                .trim_start_matches("audio/")
                .trim_start_matches("video/")
                .trim_start_matches("application/")
                .to_owned();
            media = media.with_codec(
                codec.payload_type,
                name,
                codec.rtp_codec.clock_rate,
                codec.rtp_codec.channels,
                // This endpoint's own parameters, not the ones the peer stated for the format.
                media_engine.local_fmtp_line(transceiver.kind(), codec, !is_offer),
            );

            // An answer has only feedback the offer has for the format (RFC 4585 section 4.2).
            let feedbacks = match &media_section.offered_codecs {
                Some(offered) => match codec_parameters_search(
                    &codec.rtp_codec,
                    Some(codec.payload_type),
                    offered,
                ) {
                    (offered, CodecMatch::Exact | CodecMatch::Partial) => {
                        rtcp_feedback_intersection(
                            &codec.rtp_codec.rtcp_feedback,
                            &offered.rtp_codec.rtcp_feedback,
                        )
                    }
                    _ => vec![],
                },
                None => codec.rtp_codec.rtcp_feedback.clone(),
            };
            for feedback in &feedbacks {
                // RFC 8888 section 6: "The payload type used with 'ccfb' feedback MUST be the
                // wildcard type ('*')": written once, below.
                if negotiates_ccfb([(feedback.typ.as_str(), feedback.parameter.as_str())]) {
                    ccfb = true;
                    continue;
                }
                // RFC 6679 section 6.2: the ECN feedback packet (`nack ecn`) applies to the
                // RTP session, so it is written once, for every format, below.
                if feedback.typ == crate::rtp_transceiver::rtp_sender::TYPE_RTCP_FB_NACK
                    && feedback.parameter
                        == crate::rtp_transceiver::rtp_sender::rtcp_parameters::RTCP_FB_NACK_ECN
                {
                    nack_ecn = true;
                    continue;
                }
                // XR formats are `a=rtcp-xr` (below), never `a=rtcp-fb` lines.
                if feedback.typ == RTCP_FB_XR {
                    if !xr_formats.contains(&feedback.parameter) {
                        xr_formats.push(feedback.parameter.clone());
                    }
                    continue;
                }
                // Receiver reference times: `a=rtcp-xr`, below; an `a=rtcp-fb ... rrtr` line
                // only where the offer had one.
                if feedback.typ == interceptor::RTCP_FB_RRTR {
                    rrtr = true;
                    if is_rcvr_rtt(&feedback.parameter) {
                        continue;
                    }
                }
                media = media.with_value_attribute(
                    "rtcp-fb".to_owned(),
                    if feedback.parameter.is_empty() {
                        format!("{} {}", codec.payload_type, feedback.typ)
                    } else {
                        format!(
                            "{} {} {}",
                            codec.payload_type, feedback.typ, feedback.parameter
                        )
                    },
                );
            }
        }
        // RFC 9429 section 5.3.1: without codec preferences, "Any currently available media
        // formats that are not present in the current remote description MUST be added after
        // all existing formats" (RFC 3264 section 6.1 lets an answer list them: the offerer
        // may use them in a later offer). Media formats only: a repair format (RTX, FEC, RED)
        // goes with a primary of the answer, and none of them takes feedback (RFC 4585 section
        // 4.2: the answer adds none). Each keeps its registered payload type unless the
        // section already uses it, then takes a free dynamic one.
        // An SFrame section adds them in its own numbering (draft-ietf-avtcore-rtp-sframe-03
        // section 6). The numbers come from `answer_payload_types`, the same for every section
        // of the answer: a payload type the offer uses for another format is never taken,
        // which in a BUNDLE group would give it two configurations (RFC 9143 section 9.1.1).
        // `SettingEngineBuilder::with_answer_offered_formats_only` leaves them out.
        if !is_offer
            && !params.answer_offered_formats_only
            && !transceiver.has_application_codec_preferences()
            && let Some(offered) = &media_section.offered_codecs
            && !codecs.is_empty()
        {
            let sframe = transceiver.use_sframe() == Some(true);
            let mut used: HashSet<u8> = codecs.iter().map(|c| c.payload_type).collect();
            used.extend(offered.iter().map(|c| c.payload_type));
            let available_formats = if sframe {
                media_engine.codecs_for_section(transceiver.kind(), true)
            } else {
                media_engine
                    .registered_codecs_by_kind(transceiver.kind())
                    .to_vec()
            };
            for available in &available_formats {
                if crate::rtp_transceiver::rtp_sender::rtp_codec::is_repair_codec(
                    &available.rtp_codec,
                ) || is_fec_mime_type(&available.rtp_codec.mime_type)
                    || !matches!(
                        codec_parameters_fuzzy_search(&available.rtp_codec, offered).1,
                        CodecMatch::None
                    )
                {
                    continue;
                }
                let Some(&payload_type) = params.answer_payload_types.get(&(
                    sframe,
                    transceiver.kind(),
                    available.payload_type,
                )) else {
                    continue;
                };
                if used.contains(&payload_type) {
                    continue;
                }
                used.insert(payload_type);
                let name = available
                    .rtp_codec
                    .mime_type
                    .trim_start_matches("audio/")
                    .trim_start_matches("video/")
                    .trim_start_matches("application/")
                    .to_owned();
                media = media.with_codec(
                    payload_type,
                    name,
                    available.rtp_codec.clock_rate,
                    available.rtp_codec.channels,
                    media_engine.local_fmtp_line(transceiver.kind(), available, true),
                );
            }
        }
        if ccfb {
            media = media.with_value_attribute(
                ATTR_KEY_RTCP_FB.to_owned(),
                format!("* {TYPE_RTCP_FB_ACK} {RTCP_FB_ACK_CCFB}"),
            );
        }
        if nack_ecn {
            media = media.with_value_attribute(
                ATTR_KEY_RTCP_FB.to_owned(),
                format!(
                    "* {} {}",
                    crate::rtp_transceiver::rtp_sender::TYPE_RTCP_FB_NACK,
                    crate::rtp_transceiver::rtp_sender::rtcp_parameters::RTCP_FB_NACK_ECN
                ),
            );
        }
        // RFC 3611 section 5: XR use is signalled with `a=rtcp-xr`. An offer asks for
        // receiver reference times when this endpoint takes them (`rcvr-rtt=all`, both ways);
        // an answer to an offer with the attribute states what it takes of it, an empty
        // attribute for nothing (section 5.2: "it SHOULD include an empty 'a=rtcp-xr'
        // attribute"); an answer to an offer without it has none (section 5.1: omitted when
        // XR is not used).
        // The other formats (`ecn-sum`, RFC 6679 section 7.1: "the "rtcp-xr" attribute with
        // the "ecn-sum" parameter MUST also be used") follow in the same attribute: an
        // answer's feedback is already what the offer had of them.
        let with_xr_formats = |first: Option<String>| -> Option<String> {
            let formats: Vec<String> = first.into_iter().chain(xr_formats.clone()).collect();
            (!formats.is_empty()).then(|| formats.join(" "))
        };
        let rtcp_xr = match &media_section.offered_rtcp_xr {
            None if is_offer => with_xr_formats(rrtr.then(|| format!("{XR_FORMAT_RCVR_RTT}=all"))),
            None => None,
            Some(offered) => Some(
                with_xr_formats(rrtr.then(|| {
                    offered
                        .iter()
                        .find(|f| is_rcvr_rtt(f))
                        .cloned()
                        .unwrap_or_else(|| format!("{XR_FORMAT_RCVR_RTT}=all"))
                }))
                .unwrap_or_default(),
            ),
        };
        if let Some(rtcp_xr) = rtcp_xr {
            media = media.with_value_attribute(ATTR_KEY_RTCP_XR.to_owned(), rtcp_xr);
        }
        // RFC 6679 section 6.1.1 (RFC 8888 section 7): ECN for RTP. An offer states it in
        // every RTP section (the attribute is IDENTICAL across a BUNDLE group, RFC 8859 section
        // 7.4), an answer only where the offer had a method this endpoint implements. Section
        // 6.1.3: only with a profile that has timely feedback (AVPF) and never over TCP.
        if let Some(preferred) = params.ecn {
            let feedback_profile = media_section.offered_protos.as_ref().is_none_or(|protos| {
                protos
                    .first()
                    .is_some_and(|p| !p.eq_ignore_ascii_case("TCP"))
                    && protos
                        .iter()
                        .any(|p| p.eq_ignore_ascii_case("AVPF") || p.eq_ignore_ascii_case("SAVPF"))
            });
            let value = if !feedback_profile {
                None
            } else if is_offer {
                Some(ecn::offer_value(preferred))
            } else {
                media_section
                    .offered_ecn
                    .as_ref()
                    .and_then(ecn::answer_value)
            };
            if let Some(value) = value {
                media = media.with_value_attribute(ecn::ATTR_KEY_ECN_CAPABLE_RTP.to_owned(), value);
            }
        }
        // RFC 8866 sections 6.4, 6.5 (RFC 7587 section 7 for Opus): the packet times this
        // endpoint wants to receive.
        if transceiver.kind() == RtpCodecKind::Audio && !codecs.is_empty() {
            let packet_time = media_engine.audio_packet_time;
            if let Some(ptime) = packet_time.ptime {
                media = media.with_value_attribute(ATTR_KEY_PTIME.to_owned(), ptime.to_string());
            }
            if let Some(maxptime) = packet_time.maxptime {
                media =
                    media.with_value_attribute(ATTR_KEY_MAXPTIME.to_owned(), maxptime.to_string());
            }
        }
        // RFC 9429 section 5.3.1: "the media formats in the answer MUST include at least one
        // format that is present in the offer ... If no common format exists, the "m=" section
        // is rejected". The transceiver's list falls back to every registered format when the
        // offer matched none of them, so an answer checks it against the offer.
        let no_common_format = !is_offer
            && media_section
                .offered_codecs
                .as_ref()
                .is_some_and(|offered| {
                    !codecs.iter().any(|codec| {
                        !matches!(
                            codec_parameters_fuzzy_search(&codec.rtp_codec, offered).1,
                            CodecMatch::None
                        )
                    })
                });
        if codecs.is_empty() || no_common_format {
            // If we are sender and have no codecs throw an error early
            if !no_common_format && transceiver.describes_sender() {
                return Err(Error::ErrSenderWithNoCodecs);
            }

            // Explicitly reject track if we don't have the codec
            // RFC 9429 Section 5.3.1: Set port=0 to reject, further processing can be skipped
            // However, mid attribute is still needed for offer/answer correlation with BUNDLE
            d = d.with_media(
                MediaDescription {
                    media_name: MediaName {
                        media: transceiver.kind().to_string(),
                        port: RangedPort {
                            value: 0,
                            range: None,
                        },
                        protos: vec![
                            "UDP".to_owned(),
                            "TLS".to_owned(),
                            "RTP".to_owned(),
                            "SAVPF".to_owned(),
                        ],
                        formats: vec!["0".to_owned()],
                    },
                    media_title: None,
                    // We need to include connection information even if we're rejecting a track, otherwise Firefox will fail to
                    // parse the SDP with an error like:
                    // SIPCC Failed to parse SDP: SDP Parse Error on line 50:  c= connection line not specified for every media level, validation failed.
                    // In addition this makes our SDP compliant with RFC 4566 Section 5.7: https://datatracker.ietf.org/doc/html/rfc4566#section-5.7
                    connection_information: vec![ConnectionInformation {
                        network_type: "IN".to_owned(),
                        address_type: "IP4".to_owned(),
                        address: Some(Address {
                            address: "0.0.0.0".to_owned(),
                            ttl: None,
                            range: None,
                        }),
                    }],
                    bandwidth: vec![],
                    encryption_key: None,
                    attributes: vec![],
                }
                .with_value_attribute(ATTR_KEY_MID.to_owned(), mid_value),
            );
            return Ok((d, false));
        }

        let parameters =
            media_engine.get_rtp_parameters_by_kind(transceiver.kind(), transceiver.direction());
        let to_negotiate = transceiver.header_extensions_to_negotiate();
        let to_negotiate = to_negotiate.as_deref();
        // (id, URI, encrypted form): one form per URI in an answer, both in an offer that
        // offers best-effort encryption (RFC 6904 section 4.1).
        let mut written: Vec<(u16, String, bool)> = vec![];
        for rtp_extension in &parameters.header_extensions {
            if let Some(uris) = to_negotiate
                && !uris.contains(&rtp_extension.uri)
            {
                continue;
            }
            let (id, encrypted) = if media_section.match_extensions.is_empty() {
                (rtp_extension.id, rtp_extension.encrypted)
            } else if let Some(offered) = media_section.match_extensions.get(&rtp_extension.uri) {
                (offered.id, offered.encrypted)
            } else {
                continue;
            };
            if written.iter().any(|(i, u, e)| {
                *i == id || (u == &rtp_extension.uri && (*e == encrypted || !is_offer))
            }) {
                continue;
            }
            written.push((id, rtp_extension.uri.clone(), encrypted));
        }
        if is_offer && let Some(uris) = to_negotiate {
            let taken: Vec<(u16, String)> =
                written.iter().map(|(i, u, _)| (*i, u.clone())).collect();
            for (id, uri, encrypted) in reoffered_header_extensions(
                media_engine,
                transceiver.kind(),
                transceiver.direction(),
                uris,
                &taken,
            ) {
                written.push((id, uri, encrypted));
            }
        }
        // RFC 6464 section 4: "the semantics chosen for a header extension element (including
        // its vad setting) for a particular extension identifier value MUST NOT be changed
        // within an RTP session". The extension attributes an id was negotiated with go with it:
        // an answer repeats the offer's, a later offer the ones the remote description gave it.
        let extension_attributes = |id: u16, uri: &str| -> Option<String> {
            // The mapping the remote description gave the id: the offer an answer answers, or
            // for a later offer the current remote description.
            media_section
                .match_extensions
                .get(uri)
                .filter(|matched| matched.id == id)
                .and_then(|matched| matched.attributes.clone())
                .filter(|attributes| !attributes.is_empty())
        };
        let ext_attr_of = |id: u16, uri: &str, encrypted: bool| -> Option<String> {
            let attributes = extension_attributes(id, uri);
            match (encrypted, attributes) {
                (true, Some(attributes)) => Some(format!("{uri} {attributes}")),
                (true, None) => Some(uri.to_owned()),
                (false, attributes) => attributes,
            }
        };
        for (id, uri, encrypted) in &written {
            // RFC 8285 section 7: an extension may be restricted to a direction. An offer
            // states the one the extension was registered for when the section sends and
            // receives (RFC 6465 section 5: a client that does not mix "would hence have to
            // always include the direction parameter ... with a value of 'recvonly'"); an
            // answer reverses what the offer restricted, within what was registered, and
            // leaves out an extension it can use in neither direction.
            // webrtc-extensions 4.1: the direction `[[HeaderExtensionsToNegotiate]]` gives
            // the extension, when the application set the list or an answer did.
            let registered = transceiver.header_extension_direction(uri).or_else(|| {
                media_engine
                    .header_extensions
                    .iter()
                    .find(|e| e.uri == *uri)
                    .and_then(|e| e.allowed_direction)
            });
            if registered == Some(RTCRtpTransceiverDirection::Inactive) {
                // Offered inactive; in an answer, only as the offer allowed.
                if is_offer || media_section.match_extensions.contains_key(uri) {
                    let ext_uri = Url::parse(if *encrypted { ENCRYPT_URI } else { uri })?;
                    let ext_attr = ext_attr_of(*id, uri, *encrypted);
                    media = media.with_extmap(sdp::extmap::ExtMap {
                        value: *id,
                        uri: Some(ext_uri),
                        direction: sdp::direction::Direction::Inactive,
                        ext_attr,
                    });
                }
                continue;
            }
            let Some(direction) = extension_direction(
                registered,
                media_section.match_extension_directions.get(uri).cloned(),
                media_section
                    .answer_direction
                    .unwrap_or_else(|| transceiver.direction()),
            ) else {
                continue;
            };
            let ext_uri = Url::parse(if *encrypted { ENCRYPT_URI } else { uri })?;
            let ext_attr = ext_attr_of(*id, uri, *encrypted);
            media = media.with_extmap(sdp::extmap::ExtMap {
                value: *id,
                uri: Some(ext_uri),
                direction,
                ext_attr,
            });
        }
        // RFC 6904 section 4.1: the clear form of an extension answered encrypted is
        // answered "inactive".
        for (id, uri) in &media_section.superseded_extensions {
            if written.iter().any(|(_, u, e)| u == uri && *e) {
                media = media.with_extmap(sdp::extmap::ExtMap {
                    value: *id,
                    uri: Some(Url::parse(uri)?),
                    direction: sdp::direction::Direction::Inactive,
                    ext_attr: None,
                });
            }
        }

        // The section's direction: an answer's is the transceiver's [[Direction]] intersected
        // with the reverse of the offered one (RFC 9429 section 5.3.1, RFC 3264 section 6.1);
        // an offer states [[Direction]] itself.
        let mut direction = media_section
            .answer_direction
            .unwrap_or_else(|| transceiver.direction());

        // RFC 9429 section 3.6.1 (and 5.2.1, 5.3.1): a receiving video section states the
        // frame sizes this endpoint can receive; when its limits permit none, the attribute
        // is left out and the section does not receive.
        let mut imageattrs = vec![];
        if transceiver.kind() == RtpCodecKind::Video && direction.has_recv() {
            let formats: Vec<(u8, String)> = codecs
                .iter()
                .filter(|codec| {
                    repair_family(&codec.rtp_codec).is_empty()
                        && !is_fec_mime_type(&codec.rtp_codec.mime_type)
                })
                .map(|codec| (codec.payload_type, codec.rtp_codec.mime_type.clone()))
                .collect();
            match imageattr::imageattr_lines(
                &formats,
                params.video_receive_limits,
                &params.codec_video_receive_limits,
            ) {
                Some(lines) => imageattrs = lines,
                None => {
                    direction = if direction.has_send() {
                        RTCRtpTransceiverDirection::Sendonly
                    } else {
                        RTCRtpTransceiverDirection::Inactive
                    }
                }
            }
        }
        for line in imageattrs {
            media = media.with_value_attribute(ATTR_KEY_IMAGEATTR.to_owned(), line);
        }

        // What this endpoint would like to receive (RFC 3264 sections 5 and 6:
        // `RTCRtpTransceiver::set_receive_bandwidth`), in a section that receives.
        if let Some(tias) = transceiver.receive_bandwidth()
            && direction.has_recv()
        {
            media.bandwidth.extend(receive_bandwidth_lines(tias));
        }

        // `a=rid` and `a=simulcast` (RFC 8851, RFC 8853).
        let formats: HashSet<u8> = codecs.iter().map(|codec| codec.payload_type).collect();
        // RFC 8851 section 6.3 step 4: a `pt=` keeps the formats this description has, and a
        // line that would keep none is discarded. `None`: the line is discarded.
        let kept_formats = |rid: &SimulcastRid| -> Option<Vec<u8>> {
            let kept: Vec<u8> = rid
                .formats
                .iter()
                .copied()
                .filter(|pt| formats.contains(pt))
                .collect();
            (rid.formats.is_empty() || !kept.is_empty()).then_some(kept)
        };
        // RFC 8853 section 5.2: `~` marks a stream initially paused, which "MUST" go with
        // RFC 7728 pause/resume negotiated for the section: the section's formats carry
        // `ccm pause` (offered, or negotiated in an answer), or the setting writes it anyway.
        let pauses = codecs.iter().any(|codec| {
            codec.rtp_codec.rtcp_feedback.iter().any(|feedback| {
                feedback.typ == crate::rtp_transceiver::rtp_sender::TYPE_RTCP_FB_CCM
                    && interceptor::PauseCapability::parse(&feedback.parameter).is_some()
            })
        });
        let sc_id = |id: &str, paused: bool| -> String {
            if paused && (params.rid_pause_marks || pauses) {
                format!("~{id}")
            } else {
                id.to_owned()
            }
        };
        let mut recv_sc_list: Vec<String> = vec![];
        let mut send_sc_list: Vec<String> = vec![];
        // The streams the remote side sends: each of its `send` rids is answered `recv` with
        // its restrictions kept (RFC 8851 section 6.3), and mirrored in a later offer.
        if direction.has_recv() {
            for rid in media_section
                .rid_map
                .iter()
                .filter(|rid| rid.direction == SimulcastDirection::Send)
            {
                let Some(pts) = kept_formats(rid) else {
                    continue;
                };
                let line = if !is_offer && params.w3c_simulcast_answer {
                    rid.bare_line(SimulcastDirection::Recv)
                } else {
                    rid.line(SimulcastDirection::Recv, pts)
                };
                media = media.with_value_attribute(SDP_ATTRIBUTE_RID.to_owned(), line);
                if rid.simulcast {
                    recv_sc_list.push(sc_id(&rid.id, rid.paused));
                }
            }
        }
        // An offer that asks to receive simulcast (RFC 8853 section 5.3.1): the streams the
        // application named, unless the remote side's send streams are mirrored above.
        if is_offer
            && direction.has_recv()
            && recv_sc_list.is_empty()
            && transceiver.receive_simulcast().len() > 1
        {
            for rid in transceiver.receive_simulcast() {
                media =
                    media.with_value_attribute(SDP_ATTRIBUTE_RID.to_owned(), format!("{rid} recv"));
                recv_sc_list.push(rid.clone());
            }
        }
        // The streams this endpoint sends: one `a=rid ... send` per encoding of a sender with
        // several encodings (RFC 9429 section 5.2.1). An answer has only the ones the offer
        // asked to receive (RFC 8853 section 5.3.2: "The answerer MUST NOT add any simulcast
        // streams"), with the offered restrictions (RFC 8851 section 6.3); an offer has each
        // encoding, with the restrictions the application gave it.
        if direction.has_send()
            && let Some(sender) = transceiver.sender()
        {
            // An offer also lists the streams remote answers rejected, should the sender keep
            // them for it (`with_rejected_rids_kept_in_offers`, RFC 9429 section 5.2.2: the
            // a=rid and a=simulcast lines "MUST stay the same").
            let encodings: Vec<(_, bool)> = if is_offer {
                sender.offered_encodings()
            } else {
                sender
                    .send_encodings()
                    .iter()
                    .map(|encoding| (encoding, false))
                    .collect()
            };
            let is_simulcast = encodings.len() > 1
                && encodings
                    .iter()
                    .all(|(encoding, _)| !encoding.rtp_coding_parameters.rid.is_empty());
            if is_simulcast {
                let mut lines = 0;
                for (encoding, rejected) in encodings {
                    let coding = &encoding.rtp_coding_parameters;
                    let (rid, listed) = if is_offer {
                        (
                            // What the offer that negotiated the stream said, should an
                            // answer have tightened it (RFC 9429 section 5.2.2).
                            SimulcastRid::from_restrictions(
                                &coding.rid,
                                SimulcastDirection::Send,
                                sender
                                    .offered_rid_restrictions(&coding.rid)
                                    .unwrap_or(&coding.rid_restrictions),
                            ),
                            true,
                        )
                    } else {
                        let Some(offered) = media_section.rid_map.iter().find(|rid| {
                            rid.direction == SimulcastDirection::Recv && rid.id == coding.rid
                        }) else {
                            continue;
                        };
                        (offered.clone(), offered.simulcast)
                    };
                    let Some(pts) = kept_formats(&rid) else {
                        continue;
                    };
                    let line = if !is_offer && params.w3c_simulcast_answer {
                        rid.bare_line(SimulcastDirection::Send)
                    } else {
                        rid.line(SimulcastDirection::Send, pts)
                    };
                    media = media.with_value_attribute(SDP_ATTRIBUTE_RID.to_owned(), line);
                    lines += 1;
                    if listed {
                        // A rejected stream is not sent: paused, in RFC 8853 section 5.3.4's
                        // "current pause state".
                        let paused = !encoding.active
                            || rejected
                            || (!is_offer && rid.paused && !ignore_rid_pause_for_recv);
                        send_sc_list.push(sc_id(&coding.rid, paused));
                    }
                }
                // RFC 9429 section 5.2.1: an `a=simulcast` line when "more than one 'a=rid'
                // line has been generated".
                if is_offer && lines < 2 {
                    send_sc_list.clear();
                }
            }
        }

        media = RTCPeerConnection::add_sender_sdp(
            media,
            media_engine,
            transceiver,
            write_ssrc_attributes_for_simulcast,
            repair_flows,
            params.msid_appdata,
        )?;
        // RFC 8853 section 5.1: one line, each direction at most once.
        let mut sc_attr = vec![];
        if !recv_sc_list.is_empty() {
            sc_attr.push(format!("recv {}", recv_sc_list.join(";")));
        }
        if !send_sc_list.is_empty() {
            sc_attr.push(format!("send {}", send_sc_list.join(";")));
        }
        if !sc_attr.is_empty() {
            media =
                media.with_value_attribute(SDP_ATTRIBUTE_SIMULCAST.to_owned(), sc_attr.join(" "));
        }

        media = media.with_property_attribute(direction.to_string());

        for fingerprint in dtls_fingerprints {
            media = media.with_fingerprint(
                fingerprint.algorithm.to_owned(),
                fingerprint.value.to_uppercase(),
            );
        }

        if should_add_candidates {
            media = add_candidates_to_media_descriptions(candidates, media, ice_gathering_state)?;
        }

        Ok((d.with_media(media), true))
    }

    /// The sender's `a=msid` lines and source attributes. Its `a=rid` lines are the caller's.
    fn add_sender_sdp(
        mut media: MediaDescription,
        media_engine: &MediaEngine,
        transceiver: &mut RTCRtpTransceiverInternal,
        write_ssrc_attributes_for_simulcast: bool,
        repair_flows: RepairFlows,
        msid_appdata: bool,
    ) -> Result<MediaDescription> {
        let cname = media_engine.rtcp_cname.as_str();
        // Every transceiver has a sender; one that has neither a track nor a sending
        // direction is not described (RFC 9429 section 5.2.1).
        let negotiated_header_extensions = transceiver.negotiated_header_extensions().to_vec();
        let mut transceiver_msid = None;
        if transceiver.describes_sender()
            && let Some(sender) = transceiver.sender_mut()
        {
            let (encodings, track) = (
                sender
                    .get_parameters(media_engine, &negotiated_header_extensions)
                    .encodings
                    .clone(),
                sender.track(),
            );

            let is_simulcast = encodings.len() > 1
                && encodings
                    .iter()
                    .all(|encoding| !encoding.rtp_coding_parameters.rid.is_empty());

            // One `a=msid` line per MediaStream the sender is associated with, "omitting the
            // "appdata" field" (RFC 9429 section 5.2.1; the track id with
            // `with_msid_appdata`); a sender in no stream writes the stream id `-`.
            let track_id = track.track_id().to_string();
            let mut stream_ids: Vec<String> = vec![];
            for stream_id in sender.streams() {
                if !stream_ids.contains(stream_id) {
                    stream_ids.push(stream_id.clone());
                }
            }
            if stream_ids.is_empty() {
                stream_ids.push("-".to_owned());
            }
            // RFC 8830 section 2: `msid-id = 1*64token-char` and `msid-appdata =
            // 1*64token-char`. A stream or track id the application chose that is not one
            // cannot be written: the line would not parse (a space would even make it three
            // tokens), so the description is not made. The track id is checked also without
            // appdata: the source-level `msid` attribute carries it.
            for id in stream_ids.iter().chain(std::iter::once(&track_id)) {
                if !is_msid_token(id) {
                    return Err(Error::SdpInvalidValue(format!(
                        "the id {id:?} cannot be written in a=msid: an msid-id or appdata is 1 \
                         to 64 token characters (RFC 8830 section 2)"
                    )));
                }
            }
            // The source-level `msid` (RFC 8830 appendix A) names the same first stream.
            let source_stream = stream_ids[0].clone();
            let msid: Vec<String> = stream_ids
                .into_iter()
                .map(|stream_id| {
                    if msid_appdata {
                        format!("msid:{stream_id} {track_id}")
                    } else {
                        format!("msid:{stream_id}")
                    }
                })
                .collect();
            for line in &msid {
                media = media.with_property_attribute(line.clone());
            }
            transceiver_msid = Some(msid);

            if write_ssrc_attributes_for_simulcast || !is_simulcast {
                for encoding in &encodings {
                    if let Some(&ssrc) = encoding.rtp_coding_parameters.ssrc.as_ref() {
                        let rtx_flow = encoding
                            .rtp_coding_parameters
                            .rtx
                            .as_ref()
                            .filter(|_| repair_flows.rtx);
                        let fec_flow = encoding
                            .rtp_coding_parameters
                            .fec
                            .as_ref()
                            .filter(|_| repair_flows.fec);
                        if let Some(rtx) = rtx_flow {
                            media = media.with_value_attribute(
                                ATTR_KEY_SSRC_GROUP.to_owned(),
                                format!(
                                    "{} {} {}",
                                    SEMANTIC_TOKEN_FLOW_IDENTIFICATION, ssrc, rtx.ssrc
                                ),
                            );
                        }

                        if let Some(fec) = fec_flow {
                            // `FEC-FR` (RFC 5956), not the older `FEC` semantic of RFC 4756:
                            // FlexFEC repair flows are grouped under the FEC framework, and
                            // `parse_media_section` below only recognises `FEC-FR`, so writing
                            // `FEC` here produced an offer this crate could not parse back.
                            media = media.with_value_attribute(
                                ATTR_KEY_SSRC_GROUP.to_owned(),
                                format!(
                                    "{} {} {}",
                                    SEMANTIC_TOKEN_FORWARD_ERROR_CORRECTION_FRAMEWORK,
                                    ssrc,
                                    fec.ssrc
                                ),
                            );
                        }

                        let mut sources = vec![ssrc];
                        sources.extend(rtx_flow.map(|rtx| rtx.ssrc));
                        sources.extend(fec_flow.map(|fec| fec.ssrc));
                        for source in sources {
                            media =
                                with_source_attributes(media, source, &source_stream, track, cname);
                            // RFC 5576 sections 5 and 6.2: a source that moved after a
                            // collision names the SSRCs it had, once.
                            let previous = sender.previous_ssrcs(source);
                            if !previous.is_empty() {
                                let previous: Vec<String> =
                                    previous.iter().map(|ssrc| ssrc.to_string()).collect();
                                media = media.with_value_attribute(
                                    ATTR_KEY_SSRC.to_owned(),
                                    format!("{source} previous-ssrc:{}", previous.join(" ")),
                                );
                            }
                        }
                    }
                }
            }
        }
        // RFC 9429 sections 5.2.2 and 5.3.2: "the 'a=msid' lines MUST stay the same" for a
        // transceiver that is not stopped, "regardless of changes to the transceiver's
        // direction or track": one that no longer has a track or a sending direction keeps
        // the lines its section had.
        match transceiver_msid {
            Some(msid) => transceiver.set_described_msid(msid),
            None if !transceiver.stopped() => {
                for line in transceiver.described_msid() {
                    media = media.with_property_attribute(line.clone());
                }
            }
            None => {}
        }

        Ok(media)
    }
}

/// The source attributes of one of a sender's SSRCs (RFC 5576 section 4.1): `cname` (section
/// 6.1: "the same as the CNAME that the source uses in RTCP", so the connection's one CNAME,
/// RFC 7022, whatever the track) and `msid` (RFC 8830 appendix A, registered as a source
/// attribute). The Plan B
/// `mslabel` and `label` attributes are not written: RFC 5576 section 4.1 has source
/// attributes registered with IANA, and neither is.
fn with_source_attributes(
    media: MediaDescription,
    ssrc: SSRC,
    stream_id: &str,
    track: &MediaStreamTrack,
    cname: &str,
) -> MediaDescription {
    media
        .with_value_attribute(ATTR_KEY_SSRC.to_owned(), format!("{ssrc} cname:{cname}"))
        .with_value_attribute(
            ATTR_KEY_SSRC.to_owned(),
            format!("{ssrc} msid:{stream_id} {}", track.track_id()),
        )
}

/// Whether an m-section has a format for a sender's RTX (RFC 4588) and FlexFEC
/// (draft-ietf-payload-flexible-fec-scheme-03 `video/flexfec-03`, or RFC 8627 `video/flexfec`)
/// flows.
#[derive(Debug, Copy, Clone)]
pub(crate) struct RepairFlows {
    pub(crate) rtx: bool,
    pub(crate) fec: bool,
}

/// Rejects a section of an answer that was written in full: port zero, and no `a=candidate`
/// lines (RFC 8839 section 4.2.1.6: with the port set to zero "the agent SHOULD NOT include
/// ICE-related SDP "candidate" attributes in that "m=" section"), nor `a=end-of-candidates`.
/// Whether it took candidates out: the next section written takes them then.
fn reject_written_section(media: &mut MediaDescription) -> bool {
    media.media_name.port = RangedPort {
        value: 0,
        range: None,
    };
    let before = media.attributes.len();
    media
        .attributes
        .retain(|a| a.key != "candidate" && a.key != "end-of-candidates");
    media.attributes.len() != before
}

/// Makes a section of an initial offer bundle-only (RFC 9143 sections 6 and 7.2.1): port
/// zero, `a=bundle-only`, and none of the BUNDLE attributes (the IDENTICAL and TRANSPORT
/// categories of RFC 8859), which "the offerer MUST NOT include ... in bundle-only 'm='
/// sections" (RFC 9143 section 7.1.3): they are the offerer-tagged section's.
///
/// With `rtcp_mux` (`SettingEngineBuilder::with_bundle_only_sections_in_browser_form`)
/// an RTP section keeps one BUNDLE attribute, `a=rtcp-mux`, against RFC 9143 sections 7.1.3 and
/// 9.3.1.1: Chromium, WebKit and Firefox refuse an offer whose bundle-only RTP section lacks it.
fn make_bundle_only(media: &mut MediaDescription, rtcp_mux: bool) {
    media.media_name.port = RangedPort {
        value: 0,
        range: None,
    };
    media
        .attributes
        .retain(|a| !BUNDLE_ATTRIBUTES.contains(&a.key.as_str()) && a.key != "end-of-candidates");
    if rtcp_mux && media.media_name.media != MEDIA_SECTION_APPLICATION {
        media
            .attributes
            .push(sdp::description::common::Attribute::new(
                ATTR_KEY_RTCPMUX.to_owned(),
                None,
            ));
    }
    media
        .attributes
        .push(sdp::description::common::Attribute::new(
            ATTR_KEY_BUNDLE_ONLY.to_owned(),
            None,
        ));
}

/// Whether a BUNDLE attribute (`a=rtcp-mux`, `a=rtcp-rsize`: RFC 8859 category IDENTICAL)
/// applies to `media`: the section has it, or the tagged section of its BUNDLE group has it.
/// RFC 9143 section 7.1.3: in an initial offer a bundle-only section leaves the BUNDLE
/// attributes to the offerer-tagged section, and in a subsequent offer or an answer they are
/// "only in the tagged 'm=' section" and "will apply to each bundled 'm=' section".
pub(crate) fn has_bundle_attribute(
    desc: &SessionDescription,
    media: &MediaDescription,
    key: &str,
) -> bool {
    media.has_attribute(key) || tagged_section(desc, media).is_some_and(|m| m.has_attribute(key))
}

/// Whether an RTP section of a remote description multiplexes RTP and RTCP. A section says so
/// itself with `a=rtcp-mux`. In an initial offer every bundled RTP section does, the
/// bundle-only ones excepted (RFC 9143 section 9.3.1.1: "the offerer MUST include an SDP
/// 'rtcp-mux' attribute in each bundled 'm=' section (excluding any bundle-only 'm='
/// sections)"), so only a bundle-only section takes the attribute from the offerer-tagged
/// one there. In a subsequent offer or an answer the attribute is in the tagged section only
/// (section 7.1.3) and applies to every bundled section.
pub(crate) fn section_multiplexes_rtcp(
    desc: &SessionDescription,
    media: &MediaDescription,
    initial_offer: bool,
) -> bool {
    if has_rtcp_mux(media) {
        return true;
    }
    if initial_offer && !media.has_attribute(ATTR_KEY_BUNDLE_ONLY) {
        return false;
    }
    has_bundle_attribute(desc, media, ATTR_KEY_RTCPMUX)
}

/// The tagged section of the BUNDLE group `media` is in: the first tag of the group that is
/// neither rejected nor bundle-only (RFC 9143 sections 7.2 and 7.3.1).
pub(crate) fn tagged_section<'a>(
    desc: &'a SessionDescription,
    media: &MediaDescription,
) -> Option<&'a MediaDescription> {
    let mid = get_mid_value(media);
    bundle_groups(desc)
        .into_iter()
        .find(|group| mid.is_some_and(|mid| group.contains(&mid.as_str())))
        .and_then(|group| {
            group.into_iter().find_map(|tag| {
                desc.media_descriptions.iter().find(|candidate| {
                    get_mid_value(candidate).is_some_and(|mid| mid == tag)
                        && !candidate.has_attribute(ATTR_KEY_BUNDLE_ONLY)
                        && !is_rejected_media(candidate)
                })
            })
        })
}

/// The BUNDLE attributes this endpoint writes (RFC 8859 categories IDENTICAL and TRANSPORT).
const BUNDLE_ATTRIBUTES: [&str; 11] = [
    ATTR_KEY_RTCP,
    ecn::ATTR_KEY_ECN_CAPABLE_RTP,
    "ice-ufrag",
    "ice-pwd",
    "ice-options",
    "fingerprint",
    "setup",
    "candidate",
    ATTR_KEY_RTCPMUX,
    ATTR_KEY_RTCP_MUX_ONLY,
    ATTR_KEY_RTCPRSIZE,
];

/// What a generated description does about BUNDLE (RFC 9143).
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum BundleMode {
    /// An offer. An initial one (`answered` empty) puts every media section that is not
    /// rejected in one BUNDLE group. A subsequent one keeps the BUNDLE groups of the most
    /// recent answer (RFC 9429 section 5.2.2: "the last answer's mids, minus rejected, plus
    /// new or re-enabled sections"; RFC 9143 section 7.5.2: a section is not moved between
    /// groups): `groups` are their tags, `answered` the mids that answer accepted. A section
    /// the answer did not accept (new, or re-enabled) joins the first group, or a new one
    /// when there is none; one it accepted outside every group stays outside.
    Offer {
        groups: Vec<Vec<String>>,
        answered: Vec<String>,
    },
    /// An answer to an offer with these BUNDLE groups (each its identification-tags, in the
    /// offer's order), or with none. Each group is answered on its own (RFC 9143 section 5:
    /// "an 'm=' line ... can only be associated with a single BUNDLE group"): its accepted
    /// sections, in its order (section 7.3.1: the answerer-tagged section is the first the
    /// offer suggested that is accepted). A section outside every group has a transport of its
    /// own (rejected under `must-bundle`). With no group, none is written and no section is
    /// rejected for it (section 7.3: "The answerer MUST NOT include a BUNDLE group in the
    /// answer unless the offer contained one"; RFC 9429 section 5.3.1).
    Answer(Vec<Vec<String>>),
}

impl BundleMode {
    /// An initial offer: one BUNDLE group.
    pub(crate) fn initial_offer() -> Self {
        BundleMode::Offer {
            groups: vec![],
            answered: vec![],
        }
    }

    /// Whether the description is an offer.
    pub(crate) fn is_offer(&self) -> bool {
        matches!(self, BundleMode::Offer { .. })
    }

    /// The mode of the answer to `offer`: its non-empty `a=group:BUNDLE` lines (an `a=group`
    /// line of other semantics, such as LS, is not one).
    pub(crate) fn answering(offer: &SessionDescription) -> Self {
        BundleMode::Answer(
            bundle_groups(offer)
                .into_iter()
                .filter(|group| !group.is_empty())
                .map(|group| group.into_iter().map(str::to_owned).collect())
                .collect(),
        )
    }

    /// The mode of an offer after `answer`, the most recent answer: its BUNDLE groups and the
    /// sections it accepted.
    pub(crate) fn following(answer: &SessionDescription) -> Self {
        BundleMode::Offer {
            groups: bundle_groups(answer)
                .into_iter()
                .filter(|group| !group.is_empty())
                .map(|group| group.into_iter().map(str::to_owned).collect())
                .collect(),
            answered: answer
                .media_descriptions
                .iter()
                .filter(|m| !is_rejected_media(m))
                .filter_map(|m| get_mid_value(m).cloned())
                .collect(),
        }
    }

    /// A subsequent offer with the application's requests applied
    /// (`RTCRtpTransceiver::set_bundle_request`): the sections `out` leave their group and stay
    /// outside every group (RFC 9143 section 7.5.2), the sections `into` outside every group
    /// join the first one (section 7.5.1). A section is never moved from one group to another
    /// (section 7.5.2-2). Answers are left as they are.
    pub(crate) fn with_requests(self, out: &[String], into: &[String]) -> Self {
        match self {
            BundleMode::Offer {
                mut groups,
                mut answered,
            } => {
                for group in &mut groups {
                    group.retain(|mid| !out.contains(mid));
                }
                for mid in out {
                    if !answered.contains(mid) {
                        answered.push(mid.clone());
                    }
                }
                for mid in into {
                    if groups.iter().any(|group| group.contains(mid)) {
                        continue;
                    }
                    match groups.first_mut() {
                        Some(first) => first.push(mid.clone()),
                        None => groups.push(vec![mid.clone()]),
                    }
                }
                BundleMode::Offer { groups, answered }
            }
            answer => answer,
        }
    }

    /// The group of the section `mid` in the description (an index into the groups it
    /// writes), or `None` for a section outside every group.
    fn group_of(&self, mid: &str) -> Option<usize> {
        match self {
            BundleMode::Offer { groups, answered } => {
                if let Some(index) = groups.iter().position(|g| g.iter().any(|t| t == mid)) {
                    Some(index)
                } else if answered.iter().any(|a| a == mid) {
                    None
                } else {
                    Some(0)
                }
            }
            BundleMode::Answer(offered) => offered.iter().position(|g| g.iter().any(|t| t == mid)),
        }
    }
}

#[derive(Default)]
pub(crate) struct MediaSection {
    pub(crate) mid: String,
    pub(crate) transceiver_index: usize,
    pub(crate) data: bool,
    /// RFC 8829 §5.3.1: this m-line should be reflected as rejected (port=0) in the answer.
    /// Used when the remote offer contains a rejected m-line (no direction attribute / port=0).
    pub(crate) rejected: bool,
    /// Media kind string ("video", "audio", or "application") — only meaningful when `rejected` is true.
    pub(crate) rejected_kind: String,
    /// A rejected m-line for a stopped transceiver: it also says `a=inactive` (W3C `stop()`,
    /// RFC 9429 Section 5.2.2), as browsers write it.
    pub(crate) stopped: bool,
    /// For a rejected m-section of a media type this endpoint doesn't know:
    /// the protocol and formats to reproduce (the offer's), since only the
    /// port changes in an answer (RFC 9429 5.3.1).
    pub(crate) rejected_name: Option<MediaName>,
    /// In an answer, the direction the section states: the transceiver's [[Direction]]
    /// intersected with the reverse of the offered direction (RFC 9429 section 5.3.1). `None`
    /// in an offer, which states [[Direction]].
    pub(crate) answer_direction: Option<RTCRtpTransceiverDirection>,
    pub(crate) match_extensions: HashMap<String, SectionExtension>,
    /// Answering: the offer's clear mappings of extensions it also offered encrypted
    /// ([`superseded_clear_extensions`]), answered `inactive`.
    pub(crate) superseded_extensions: Vec<(u16, String)>,
    /// In an answer, the direction each extension (by URI) is answered with when the offer
    /// restricted it: the reverse of the offered one (RFC 8285 section 7: "if an extension
    /// map is offered as 'sendonly', and the answerer wishes to use it, it MUST be marked as
    /// 'recvonly' in the SDP answer", and the other way round; `inactive` stays).
    pub(crate) match_extension_directions: HashMap<String, sdp::direction::Direction>,
    pub(crate) rid_map: Vec<SimulcastRid>,
    /// In an answer, the `<proto>` of the offered m= line, which the answer repeats (RFC 9429
    /// section 5.1.2: "The profile in any 'm=' line in any generated answer MUST exactly match
    /// the profile provided in the offer"). `None` in an offer, which states this endpoint's
    /// own profile.
    pub(crate) offered_protos: Option<Vec<String>>,
    /// Whether the section says `a=rtcp-rsize`, when that is not this endpoint's choice: in
    /// an answer, whether the offered section had it (RFC 9429 section 5.3.1: "If present in
    /// the offer"); in a subsequent offer, for a section the last exchange negotiated,
    /// whether the most recent answer had it (section 5.2.2: "MUST NOT be added unless
    /// present in the most recent answer"). `None` for a new section of an offer, which
    /// says it.
    pub(crate) offered_rtcp_rsize: Option<bool>,
    /// An offer's section that the last completed exchange already negotiated: it gets no
    /// `a=rtcp-mux-only` (RFC 9429 section 5.2.2: "The 'a=rtcp-mux-only' line MUST NOT be
    /// added").
    pub(crate) renegotiated: bool,
    /// In an answer, the codecs of the offered section with their `a=rtcp-fb`: the answer
    /// keeps only feedback the offer has for the format (RFC 4585 section 4.2: "The answerer
    /// MUST NOT add feedback parameters"), also when the transceiver's codecs still carry
    /// what an earlier offer had. `None` in an offer.
    pub(crate) offered_codecs: Option<Vec<RTCRtpCodecParameters>>,
    /// In an answer, the `xr-format`s of the offered section's `a=rtcp-xr` (RFC 3611 section
    /// 5.2), `None` when it had none or in an offer.
    pub(crate) offered_rtcp_xr: Option<Vec<String>>,
    /// In an answer, the offered section's `a=ecn-capable-rtp` (RFC 6679 section 6.1.1).
    pub(crate) offered_ecn: Option<ecn::EcnCapability>,
    /// The section is a FEC session's (RFC 5109 section 14.1): written by
    /// [`fec_session::add_fec_media_section`], outside every BUNDLE group, and grouped with
    /// the media section it protects.
    pub(crate) fec: Option<fec_session::FecSection>,
}

/// `a=rtcp-mux-only` (RFC 8858 section 3).
pub(crate) const ATTR_KEY_RTCP_MUX_ONLY: &str = "rtcp-mux-only";

/// Whether an audio or video m= section signals RTP/RTCP multiplexing (RFC 5761 section 5.1.1).
pub(crate) fn has_rtcp_mux(media: &MediaDescription) -> bool {
    media.has_attribute(ATTR_KEY_RTCPMUX)
}

/// Whether `media` is an RTP (audio or video) section that is not rejected.
pub(crate) fn is_live_rtp_section(media: &MediaDescription) -> bool {
    !is_rejected_media(media)
        && matches!(
            RtpCodecKind::from(media.media_name.media.as_str()),
            RtpCodecKind::Audio | RtpCodecKind::Video
        )
}

/// The profiles of a media (RTP) m= line RFC 9429 section 5.1.2 has accepted in an offer:
/// whatever the string, the section is DTLS-SRTP with feedback when it carries
/// `a=fingerprint`.
const RTP_PROFILES: [&str; 8] = [
    "RTP/AVP",
    "RTP/AVPF",
    "RTP/SAVP",
    "RTP/SAVPF",
    "TCP/DTLS/RTP/SAVP",
    "TCP/DTLS/RTP/SAVPF",
    "UDP/TLS/RTP/SAVP",
    "UDP/TLS/RTP/SAVPF",
];

/// Whether an audio or video m= line's `<proto>` is one of the RTP profiles RFC 9429 section
/// 5.1.2 lists. Another one (`udptl`, say) is not RTP this endpoint can answer.
pub(crate) fn is_rtp_profile(media: &MediaDescription) -> bool {
    RTP_PROFILES.contains(&media.media_name.protos.join("/").as_str())
}

pub(crate) struct PopulateSdpParams {
    pub(crate) media_description_fingerprint: bool,
    pub(crate) is_ice_lite: bool,
    pub(crate) is_extmap_allow_mixed: bool,
    pub(crate) connection_role: ConnectionRole,
    pub(crate) ice_gathering_state: RTCIceGatheringState,
    pub(crate) bundle: BundleMode,
    /// Answering: the mid of the offer's offerer-tagged section when it carried
    /// `a=rtcp-mux-only`. The answer then says so in its answerer-tagged section (RFC 9143
    /// section 9.3.1.2).
    pub(crate) offered_tag_rtcp_mux_only: bool,
    /// The RTCP mux policy is "require" (the default): new m= sections of an offer say
    /// `a=rtcp-mux-only`.
    pub(crate) rtcp_mux_only: bool,
    /// `SettingEngineBuilder::with_rtcp_mux_only_in_subsequent_offers`: under the "require"
    /// policy the sections a subsequent offer carries over say `a=rtcp-mux-only` too.
    pub(crate) rtcp_mux_only_renegotiated: bool,
    /// The bundle policy (RFC 9429 section 4.1.1), `Unspecified` being the default,
    /// `balanced`. It decides which m= sections of an initial offer are bundle-only, and which
    /// sections of an offer without a BUNDLE group an answer accepts.
    pub(crate) bundle_policy: RTCBundlePolicy,
    /// The description is an initial offer: the only one that marks sections bundle-only
    /// (RFC 9429 section 5.2.2: in a subsequent offer "an 'a=bundle-only' line ... MUST NOT
    /// be added").
    pub(crate) initial_offer: bool,
    /// `SettingEngineBuilder::with_bundle_attributes_repeated(false)`: the form of RFC 9143
    /// section 7.1.3.
    pub(crate) bundle_attributes_in_tagged_section_only: bool,
    /// `SettingEngineBuilder::with_bundle_only_sections_in_browser_form`:
    /// an initial offer's bundle-only RTP sections say `a=rtcp-mux`, every bundle-only section
    /// says its group's ICE credentials, and when it has a bundle-only section its fingerprints
    /// are at session level too.
    pub(crate) bundle_only_browser_form: bool,
    /// `SettingEngineBuilder::with_answer_offered_formats_only`: an answer lists only formats
    /// the offer has.
    pub(crate) answer_offered_formats_only: bool,
    pub(crate) sctp_max_message_size: usize,
    /// The data section's `a=sctp-port`.
    pub(crate) sctp_port: u16,
    /// Whether the data section's proto is `TCP/DTLS/SCTP` (an answer to such an offer).
    pub(crate) sctp_over_tcp: bool,
    pub(crate) ignore_rid_pause_for_recv: bool,
    pub(crate) rid_pause_marks: bool,
    /// The video receive limits (`a=imageattr`, RFC 9429 section 3.6.1).
    pub(crate) video_receive_limits: Option<RTCVideoResolutionRange>,
    pub(crate) codec_video_receive_limits: Vec<(String, RTCVideoResolutionRange)>,
    /// `SettingEngineBuilder::with_w3c_simulcast_answer`.
    pub(crate) w3c_simulcast_answer: bool,
    /// `SettingEngineBuilder::with_msid_appdata`.
    pub(crate) msid_appdata: bool,
    pub(crate) write_ssrc_attributes_for_simulcast: bool,
    /// The Ta this endpoint proposes (`ice::Agent::proposed_pacing`): `a=ice-pacing` when it is
    /// not the default.
    pub(crate) ice_pacing: Option<std::time::Duration>,
    /// `SettingEngineBuilder::with_ice_options_in_media_sections`: `a=ice-options` after each
    /// section's `a=ice-pwd` instead of at session level.
    pub(crate) ice_options_in_media_sections: bool,
    /// The options of the `a=ice-options` line, in order (empty: no line): `trickle ice2` in an
    /// offer; in an answer as `SettingEngineBuilder::with_answer_ice_options` says.
    pub(crate) ice_options: Vec<&'static str>,
    /// In an offer, the `a=group:LS` groups of the most recent answer; in an answer, the
    /// offer's (RFC 9429 sections 5.2.2, 5.3.1).
    pub(crate) ls_groups: Vec<Vec<String>>,
    /// Once ICE has selected a pair (and no restart is staged), the `m=` / `c=` destination of
    /// the sections that carry the candidates: the selected pair's local candidate (RFC 8839
    /// sections 4.2.1.2, 4.3.4, 4.4.1.2.2), or the one an offer's `a=remote-candidates` names.
    pub(crate) selected_destination: Option<(std::net::IpAddr, u16)>,
    /// The values of the `a=remote-candidates` lines (RFC 8839 sections 4.4.1.2.2, 5.2) an
    /// offer of the controlling agent carries once ICE has selected a pair.
    pub(crate) remote_candidates: Vec<String>,
    /// ECN signalled with `a=ecn-capable-rtp`, preferring this initiation (RFC 6679 section
    /// 6.1); `None` when ECN is off or used without signalling.
    pub(crate) ecn: Option<interceptor::EcnInitiation>,
}

impl RTCPeerConnection {
    /// Each mid's first transceiver in `local_transceivers`, so a pass over every m-section of
    /// a description looks mids up instead of scanning the transceivers for each one.
    pub(crate) fn transceiver_index_by_mid(
        local_transceivers: &[RTCRtpTransceiverInternal],
    ) -> HashMap<String, usize> {
        let mut by_mid = HashMap::with_capacity(local_transceivers.len());
        for (i, t) in local_transceivers.iter().enumerate() {
            if let Some(mid) = t.mid() {
                by_mid.entry(mid.clone()).or_insert(i);
            }
        }
        by_mid
    }

    /// Given a direction+type pluck a transceiver from the passed list and return its index;
    /// `None` when no entry satisfies the requested type+direction
    pub(crate) fn satisfy_type_and_direction(
        remote_kind: RtpCodecKind,
        remote_direction: RTCRtpTransceiverDirection,
        local_transceivers: &[RTCRtpTransceiverInternal],
    ) -> Option<usize> {
        // Get direction order from most preferred to least
        let get_preferred_directions = || -> Vec<RTCRtpTransceiverDirection> {
            match remote_direction {
                RTCRtpTransceiverDirection::Sendrecv => vec![
                    RTCRtpTransceiverDirection::Recvonly,
                    RTCRtpTransceiverDirection::Sendrecv,
                ],
                RTCRtpTransceiverDirection::Sendonly => vec![RTCRtpTransceiverDirection::Recvonly],
                RTCRtpTransceiverDirection::Recvonly => vec![
                    RTCRtpTransceiverDirection::Sendonly,
                    RTCRtpTransceiverDirection::Sendrecv,
                ],
                _ => vec![],
            }
        };

        for possible_direction in get_preferred_directions() {
            // Find the index first to avoid multiple mutable borrows
            if let Some(index) = local_transceivers.iter().position(|t| {
                t.mid().is_none()
                    && !t.stopped()
                    && t.associable_with_remote_offer()
                    && t.kind() == remote_kind
                    && possible_direction == t.direction()
            }) {
                return Some(index);
            }
        }

        None
    }

    /// populate_sdp serializes a PeerConnections state into an SDP
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn populate_sdp(
        mut d: SessionDescription,
        dtls_fingerprints: &[RTCDtlsFingerprint],
        media_engine: &MediaEngine,
        transceivers: &mut [RTCRtpTransceiverInternal],
        candidates: &[RTCIceCandidate],
        ice_params: &RTCIceParameters,
        media_sections: &[MediaSection],
        params: PopulateSdpParams,
    ) -> Result<SessionDescription> {
        let media_dtls_fingerprints = if params.media_description_fingerprint {
            dtls_fingerprints.to_vec()
        } else {
            vec![]
        };

        // The mids of each BUNDLE group, in media section order.
        let mut bundled: Vec<Vec<String>> = vec![];
        // The media types (`audio`, `video`, `application`) of the sections so far that carry
        // their own transport parameters, for the bundle policy.
        let mut with_transport: Vec<String> = vec![];
        // Whether a section was made bundle-only (an initial offer).
        let mut any_bundle_only = false;

        let answer_payload_types = answer_payload_types(media_engine, media_sections);
        let mut candidates_added = false;
        let offers_over_tcp = params.bundle.is_offer() && params.sctp_over_tcp;
        for m in media_sections.iter() {
            // RFC 8829 §5.3.1: reflect rejected m-lines (port=0) in the answer.
            // These must appear in the same position as in the offer to preserve m-line indexing.
            if m.rejected {
                let (rejected_protos, rejected_formats) = if let Some(name) = &m.rejected_name {
                    (name.protos.clone(), name.formats.clone())
                } else if m.rejected_kind == "application" {
                    (
                        vec!["UDP".to_owned(), "DTLS".to_owned(), "SCTP".to_owned()],
                        vec!["webrtc-datachannel".to_owned()],
                    )
                } else {
                    (
                        vec![
                            "UDP".to_owned(),
                            "TLS".to_owned(),
                            "RTP".to_owned(),
                            "SAVPF".to_owned(),
                        ],
                        vec!["0".to_owned()],
                    )
                };

                d = d.with_media(
                    MediaDescription {
                        media_name: MediaName {
                            media: m.rejected_kind.clone(),
                            port: RangedPort {
                                value: 0,
                                range: None,
                            },
                            protos: rejected_protos,
                            formats: rejected_formats,
                        },
                        media_title: None,
                        connection_information: vec![ConnectionInformation {
                            network_type: "IN".to_owned(),
                            address_type: "IP4".to_owned(),
                            address: Some(Address {
                                address: "0.0.0.0".to_owned(),
                                ttl: None,
                                range: None,
                            }),
                        }],
                        bandwidth: vec![],
                        encryption_key: None,
                        attributes: vec![],
                    }
                    .with_value_attribute(ATTR_KEY_MID.to_owned(), m.mid.clone()),
                );
                if let (Some(protos), Some(desc)) =
                    (&m.offered_protos, d.media_descriptions.last_mut())
                {
                    desc.media_name.protos.clone_from(protos);
                }
                if m.stopped
                    && let Some(desc) = d.media_descriptions.last_mut()
                {
                    let rejected = std::mem::take(desc);
                    *desc = rejected.with_property_attribute("inactive".to_owned());
                }
                continue; // rejected m-lines are not added to BUNDLE
            }

            if m.data && m.transceiver_index != usize::MAX {
                return Err(Error::ErrSDPMediaSectionMediaDataChanInvalid);
            } else if !m.data && m.transceiver_index >= transceivers.len() {
                return Err(Error::ErrSDPMediaSectionTrackInvalid);
            }

            let should_add_candidates = !candidates_added;

            let should_add_id = if m.data {
                let params = AddDataMediaSectionParams {
                    should_add_candidates,
                    mid_value: m.mid.clone(),
                    ice_params: ice_params.clone(),
                    dtls_role: params.connection_role,
                    ice_gathering_state: params.ice_gathering_state,
                    sctp_max_message_size: params.sctp_max_message_size,
                    sctp_port: params.sctp_port,
                    sctp_over_tcp: params.sctp_over_tcp,
                };
                d = add_data_media_section(d, &media_dtls_fingerprints, candidates, params)?;
                true
            } else if let Some(section) = &m.fec {
                let kind = transceivers[m.transceiver_index].kind().to_string();
                d = fec_session::add_fec_media_section(
                    d,
                    &media_dtls_fingerprints,
                    candidates,
                    fec_session::AddFecMediaSectionParams {
                        should_add_candidates,
                        mid_value: m.mid.clone(),
                        kind,
                        ice_params,
                        dtls_role: params.connection_role,
                        ice_gathering_state: params.ice_gathering_state,
                        section,
                    },
                )?;
                true
            } else {
                let params = AddTransceiverSdpParams {
                    should_add_candidates,
                    mid_value: m.mid.clone(),
                    dtls_role: params.connection_role,
                    ice_gathering_state: params.ice_gathering_state,
                    ignore_rid_pause_for_recv: params.ignore_rid_pause_for_recv,
                    rid_pause_marks: params.rid_pause_marks,
                    video_receive_limits: params.video_receive_limits,
                    codec_video_receive_limits: params.codec_video_receive_limits.clone(),
                    w3c_simulcast_answer: params.w3c_simulcast_answer,
                    msid_appdata: params.msid_appdata,
                    write_ssrc_attributes_for_simulcast: params.write_ssrc_attributes_for_simulcast,
                    is_offer: params.bundle.is_offer(),
                    rtcp_mux_only: params.rtcp_mux_only,
                    rtcp_mux_only_renegotiated: params.rtcp_mux_only_renegotiated,
                    ecn: params.ecn,
                    answer_payload_types: answer_payload_types.clone(),
                    answer_offered_formats_only: params.answer_offered_formats_only,
                };
                let (d1, should_add_id) = RTCPeerConnection::add_transceiver_sdp(
                    d,
                    &media_dtls_fingerprints,
                    media_engine,
                    transceivers,
                    ice_params,
                    candidates,
                    m,
                    params,
                )?;
                d = d1;
                // RFC 9429 section 5.1.2: the offered profile "is determined by the protocol
                // associated with the current default or selected ICE candidate", as for the
                // data section (`sctp_over_tcp`, RFC 8841 section 12.2): `TCP/DTLS/RTP/SAVPF`
                // (RFC 7850) when that candidate is a TCP one. An answer repeats the offer's.
                if offers_over_tcp
                    && let Some(desc) = d.media_descriptions.last_mut()
                    && desc.media_name.protos == ["UDP", "TLS", "RTP", "SAVPF"]
                {
                    desc.media_name.protos =
                        ["TCP", "DTLS", "RTP", "SAVPF"].map(str::to_owned).to_vec();
                    // RFC 6679 section 6.1.3: `a=ecn-capable-rtp` "MUST NOT be used for RTP
                    // sessions using TCP".
                    desc.attributes
                        .retain(|a| a.key != ecn::ATTR_KEY_ECN_CAPABLE_RTP);
                }
                should_add_id
            };

            candidates_added = true;

            if let (Some(protos), Some(desc)) = (&m.offered_protos, d.media_descriptions.last_mut())
            {
                if m.data && protos.as_slice() == ["DTLS", "SCTP"] {
                    into_legacy_data_section(desc);
                } else {
                    desc.media_name.protos.clone_from(protos);
                    // An RTP section offered with a profile without feedback (`RTP/SAVP`, not
                    // `.../SAVPF`) is answered without it: no `a=rtcp-fb` (RFC 4585 section
                    // 4.1: the feedback attributes are for the AVPF profiles) and no reduced
                    // size RTCP (RFC 5506 section 4: reduced-size RTCP "MUST only be used"
                    // with AVPF / SAVPF). The answer says what the session then negotiates.
                    if !m.data
                        && !protos.iter().any(|p| {
                            p.eq_ignore_ascii_case("AVPF") || p.eq_ignore_ascii_case("SAVPF")
                        })
                    {
                        desc.attributes
                            .retain(|a| a.key != ATTR_KEY_RTCP_FB && a.key != ATTR_KEY_RTCPRSIZE);
                    }
                }
            }

            if should_add_id {
                let media_type = d
                    .media_descriptions
                    .last()
                    .map(|desc| desc.media_name.media.clone())
                    .unwrap_or_default();
                // Whether the bundle policy leaves this section without a transport of its
                // own, given the sections before it (RFC 9429 section 4.1.1): `balanced`
                // (the default), "the second and any subsequent 'm=' sections of each type";
                // `must-bundle` (`max-bundle`), "all streams other than the first";
                // `max-compat`, none. An RTP section needs an RTP section before it to take
                // its BUNDLE attributes from (RFC 9143 section 9.3.1.1).
                let rtp = media_type != MEDIA_SECTION_APPLICATION;
                let has_carrier = if rtp {
                    with_transport
                        .iter()
                        .any(|t| t != MEDIA_SECTION_APPLICATION)
                } else {
                    !with_transport.is_empty()
                };
                let without_transport = has_carrier
                    && match params.bundle_policy {
                        RTCBundlePolicy::MaxCompat => false,
                        RTCBundlePolicy::MustBundle => true,
                        _ => with_transport.contains(&media_type),
                    };
                let group = params.bundle.group_of(&m.mid);
                let join = |bundled: &mut Vec<Vec<String>>, index: usize| {
                    if bundled.len() <= index {
                        bundled.resize(index + 1, vec![]);
                    }
                    bundled[index].push(m.mid.clone());
                };
                match &params.bundle {
                    BundleMode::Offer { .. } => {
                        // A section the offer leaves outside every group has a transport of
                        // its own, so it is never bundle-only (RFC 9143 section 6: a
                        // bundle-only section is one of the BUNDLE group).
                        if params.initial_offer
                            && without_transport
                            && group.is_some()
                            && let Some(desc) = d.media_descriptions.last_mut()
                        {
                            make_bundle_only(desc, params.bundle_only_browser_form);
                            any_bundle_only = true;
                        } else {
                            with_transport.push(media_type);
                        }
                        // A section the most recent answer accepted outside every group stays
                        // outside: it keeps its transport (RFC 9143 section 7.5).
                        if let Some(index) = group {
                            join(&mut bundled, index);
                        }
                    }
                    BundleMode::Answer(_) if group.is_some() => {
                        join(&mut bundled, group.unwrap_or_default());
                    }
                    BundleMode::Answer(offered)
                        if !offered.is_empty()
                            && params.bundle_policy != RTCBundlePolicy::MustBundle =>
                    {
                        // Outside the offered group: it has a transport of its own (RFC 9143
                        // section 7.3.2; `RTCPeerConnection::apply_transport_layout`).
                        with_transport.push(media_type);
                    }
                    BundleMode::Answer(offered) if !offered.is_empty() => {
                        // Outside the offered group under `must-bundle`: no transport but the
                        // BUNDLE one (RFC 9429 section 4.1.1).
                        if let Some(desc) = d.media_descriptions.last_mut()
                            && reject_written_section(desc)
                        {
                            candidates_added = false;
                        }
                    }
                    // No BUNDLE group offered: every accepted section is a transport of its
                    // own, and the policy says how many this endpoint takes (RFC 9429 section
                    // 4.1.1: balanced "will reject all but the first 'm=' section of each
                    // type", must-bundle "any 'm=' sections other than the first").
                    BundleMode::Answer(_) => {
                        if without_transport {
                            if let Some(desc) = d.media_descriptions.last_mut()
                                && reject_written_section(desc)
                            {
                                candidates_added = false;
                            }
                        } else {
                            with_transport.push(media_type);
                        }
                    }
                }
            }
        }

        // RFC 8122 section 5: "The fingerprint attribute may be either a session-level or a
        // media-level SDP attribute"; RFC 9429 section 5.2.1: the m= sections "MUST all have the
        // same fingerprint value or values [RFC8122], or these values MUST be session-level
        // attributes". With the setting, an initial offer with a bundle-only section has them at
        // session level as well, so the bundle-only sections (which carry none, RFC 9143 7.1.3)
        // see one: Chromium and WebKit otherwise answer a bundle-only data section with port
        // zero, and Firefox does not apply the offer.
        if !params.media_description_fingerprint
            || (params.bundle_only_browser_form && any_bundle_only)
        {
            for fingerprint in dtls_fingerprints {
                d = d.with_fingerprint(
                    fingerprint.algorithm.clone(),
                    fingerprint.value.to_uppercase(),
                );
            }
        }

        // RFC 8445 section 10: "an agent compliant to this specification MUST inform the
        // peer about the compliance using the 'ice2' option" (RFC 8839 section 5.6:
        // `a=ice-options`), lite agents included. `trickle` too: this side accepts trickled
        // candidates (`add_remote_candidate` at any time after the remote description) and
        // trickles its own (JSEP RFC 9429 §5.2.1 / §5.3.1), and RFC 8840 §4: "Trickle ICE
        // Agents MUST indicate support for Trickle ICE by including the ice-option "trickle"
        // within all SDP Offers and Answers". A lite agent is one as well: it takes trickled
        // candidates and trickles its own (its TCP candidates come after the description),
        // and RFC 8838 Appendix B has an ICE-lite agent capable of Trickle ICE "indicate
        // support for Trickle ICE". Without it the full peer takes the lite agent's
        // description for all its candidates (W3C webrtc-pc 5.6.4, `canTrickleIceCandidates`
        // false) and may report "failed" before the trickled ones arrive.
        if params.is_ice_lite {
            // RFC 8839 §5.3
            d = d.with_property_attribute(ATTR_KEY_ICELITE.to_owned());
        }
        // Offers say `trickle ice2`, lite agents' too. An answer says what
        // `SettingEngineBuilder::with_answer_ice_options` gives: by default RFC 9429 section
        // 5.3.1's form, each of the two only "if such an option was present in the offer",
        // against RFC 8840 section 4.1.3 and RFC 8445 section 10 (`answer_ice_options`;
        // spec-issues row 28). No line for no option (RFC 8839 section 5.6: one or more tags).
        let ice_options = params.ice_options.join(" ");
        // RFC 8839 section 5.6: "session-level or media-level".
        if ice_options.is_empty() {
            // Nothing to say: no line.
        } else if params.ice_options_in_media_sections {
            for media in &mut d.media_descriptions {
                if let Some(at) = media.attributes.iter().position(|a| a.key == "ice-pwd") {
                    media.attributes.insert(
                        at + 1,
                        sdp::description::common::Attribute::new(
                            ATTR_KEY_ICE_OPTIONS.to_owned(),
                            Some(ice_options.clone()),
                        ),
                    );
                }
            }
        } else {
            d = d.with_value_attribute(ATTR_KEY_ICE_OPTIONS.to_owned(), ice_options);
        }
        // RFC 8445 section 14.2: an agent that wants a Ta other than the default "MUST
        // indicate the proposed value to its peer"; RFC 8839 section 5.5: `a=ice-pacing`, in
        // milliseconds, at session level.
        if let Some(ta) = params.ice_pacing {
            d = d.with_value_attribute(ATTR_KEY_ICE_PACING.to_owned(), ta.as_millis().to_string());
        }

        if params.is_extmap_allow_mixed {
            // RFC 8285 6.
            d = d.with_property_attribute(ATTR_KEY_EXTMAP_ALLOW_MIXED.to_owned());
        }

        bundled.retain(|group| !group.is_empty());
        if let BundleMode::Answer(offered) = &params.bundle {
            // The offer's order: each group's first accepted tag is its answerer-tagged
            // section.
            for group in bundled.iter_mut() {
                if let Some(tags) = offered
                    .iter()
                    .find(|tags| group.first().is_some_and(|mid| tags.contains(mid)))
                {
                    group.sort_by_key(|mid| tags.iter().position(|tag| tag == mid));
                }
            }
        }
        for (index, bundled) in bundled.iter().enumerate() {
            if index == 0
                && params.offered_tag_rtcp_mux_only
                && let Some(tag) = bundled.first()
                && let Some(tagged) = d.media_descriptions.iter_mut().find(|media| {
                    get_mid_value(media) == Some(tag)
                        && media.has_attribute(ATTR_KEY_RTCPMUX)
                        && !media.has_attribute(ATTR_KEY_RTCP_MUX_ONLY)
                })
            {
                let at = tagged
                    .attributes
                    .iter()
                    .position(|a| a.key == ATTR_KEY_RTCPMUX)
                    .map_or(tagged.attributes.len(), |i| i + 1);
                tagged.attributes.insert(
                    at,
                    sdp::description::common::Attribute::new(
                        ATTR_KEY_RTCP_MUX_ONLY.to_owned(),
                        None,
                    ),
                );
            }
            // RFC 9143 section 7.1.3: in an answer or a subsequent offer only the tagged section
            // (the first of the group) carries the BUNDLE attributes, unless the application
            // asked for the browsers' repeated form.
            if params.bundle_attributes_in_tagged_section_only && !params.initial_offer {
                // The tagged section speaks for the group, also when it is not RTP itself (RFC
                // 9143 section 7.1.3, the note: "the tagged 'm=' section might contain an SDP
                // 'rtcp-mux' attribute even if the tagged 'm=' section does not describe
                // RTP-based media"; section 9.3.1.2: "MUST include an SDP 'rtcp-mux' attribute
                // in the answerer-tagged 'm=' section"). So when the tagged section is the data
                // section it takes `a=rtcp-mux` from the RTP sections that are about to lose it,
                // and `a=rtcp-rsize` when each of them has it.
                let others: Vec<&MediaDescription> = bundled
                    .iter()
                    .skip(1)
                    .filter_map(|mid| {
                        d.media_descriptions
                            .iter()
                            .find(|media| get_mid_value(media) == Some(mid))
                    })
                    .filter(|media| media.media_name.media != MEDIA_SECTION_APPLICATION)
                    .collect();
                let mux = others
                    .iter()
                    .any(|media| media.has_attribute(ATTR_KEY_RTCPMUX));
                let rsize = !others.is_empty()
                    && others
                        .iter()
                        .all(|media| media.has_attribute(ATTR_KEY_RTCPRSIZE));
                if let Some(tagged) = bundled.first().and_then(|tag| {
                    d.media_descriptions
                        .iter_mut()
                        .find(|media| get_mid_value(media) == Some(tag))
                }) && tagged.media_name.media == MEDIA_SECTION_APPLICATION
                {
                    for (key, wanted) in [(ATTR_KEY_RTCPMUX, mux), (ATTR_KEY_RTCPRSIZE, rsize)] {
                        if wanted && !tagged.has_attribute(key) {
                            tagged
                                .attributes
                                .push(sdp::description::common::Attribute::new(
                                    key.to_owned(),
                                    None,
                                ));
                        }
                    }
                }
                for mid in bundled.iter().skip(1) {
                    if let Some(media) = d
                        .media_descriptions
                        .iter_mut()
                        .find(|media| get_mid_value(media) == Some(mid))
                    {
                        media.attributes.retain(|a| {
                            !BUNDLE_ATTRIBUTES.contains(&a.key.as_str())
                                && a.key != "end-of-candidates"
                        });
                    }
                }
            }
        }
        for group in &bundled {
            d = d.with_value_attribute(
                ATTR_KEY_GROUP.to_owned(),
                format!("BUNDLE {}", group.join(" ")),
            );
        }
        // RFC 5109 sections 14.1 and 14.3: a FEC session is grouped with the media section it
        // protects (RFC 5888, with the FEC-FR semantics of RFC 5956 or the FEC semantics of
        // RFC 4756), in an offer and, when the answerer accepts it, "by including the same
        // grouping in the answer". Only while both sections are accepted: a group names no
        // rejected section (RFC 5888 section 9.2).
        let accepted = |mid: &str| {
            d.media_descriptions.iter().any(|media| {
                get_mid_value(media).is_some_and(|m| m == mid) && !is_rejected_media(media)
            })
        };
        let fec_groups: Vec<String> = media_sections
            .iter()
            .filter(|m| !m.rejected)
            .filter_map(|m| m.fec.as_ref().map(|fec| (m, fec)))
            .filter(|(m, fec)| accepted(&m.mid) && accepted(&fec.protected_mid))
            .map(|(m, fec)| fec_session::fec_group_value(fec.semantics, &fec.protected_mid, &m.mid))
            .collect();
        for group in fec_groups {
            d = d.with_value_attribute(ATTR_KEY_GROUP.to_owned(), group);
        }

        // After ICE selected a pair: the sections that carry the candidates name it.
        for m in &mut d.media_descriptions {
            if m.media_name.port.value == 0 || m.attribute("candidate").is_none() {
                continue;
            }
            if let Some((ip, port)) = params.selected_destination {
                set_default_destination(m, ip, port);
            }
            for value in &params.remote_candidates {
                m.attributes.push(sdp::description::common::Attribute::new(
                    ATTR_KEY_REMOTE_CANDIDATES.to_owned(),
                    Some(value.clone()),
                ));
            }
        }
        share_bundle_destination(&mut d);

        // Lip synchronization groups (RFC 5888 section 7; RFC 9429 sections 5.2.1, 5.2.2,
        // 5.3.1), of the accepted RTP sections.
        let live: Vec<(String, Vec<String>)> = media_sections
            .iter()
            .filter(|m| !m.rejected && !m.data && m.transceiver_index < transceivers.len())
            .filter(|m| {
                d.media_descriptions.iter().any(|media| {
                    get_mid_value(media) == Some(&m.mid)
                        && (media.media_name.port.value != 0
                            || media.has_attribute(ATTR_KEY_BUNDLE_ONLY))
                })
            })
            .map(|m| {
                let streams = transceivers[m.transceiver_index]
                    .sender()
                    .as_ref()
                    .map(|sender| sender.associated_streams().to_vec())
                    .unwrap_or_default();
                (m.mid.clone(), streams)
            })
            .collect();
        for group in generated_ls_groups(&live, &params.ls_groups, params.bundle.is_offer()) {
            d = d
                .with_value_attribute(ATTR_KEY_GROUP.to_owned(), format!("LS {}", group.join(" ")));
        }
        make_msid_pairs_unique(&mut d);

        // `SettingEngineBuilder::with_bundle_only_sections_in_browser_form`: each bundle-only
        // section says its group's ICE credentials (the tagged section's), against RFC 9429
        // section 5.2.1 ("Bundle-only "m=" sections MUST NOT contain any ICE credentials") and
        // RFC 9143 section 7.1.3. Firefox compares each m= section's credentials in a later
        // remote description with the ones of the current one (JsepSessionImpl
        // IceCredentialsDiffer) and takes the credentials a later answer repeats in a section
        // that had none for an ICE restart; it also refuses a later description without them
        // in every section ("no ice-ufrag attribute at level 1"), so the tagged-only form of
        // RFC 9143 7.1.3 for later descriptions does not help (test-env run 45908363443).
        if params.bundle_only_browser_form && any_bundle_only {
            let credentials: Vec<Option<(String, String)>> = d
                .media_descriptions
                .iter()
                .map(|media| {
                    if !media.has_attribute(ATTR_KEY_BUNDLE_ONLY) {
                        return None;
                    }
                    let tagged = tagged_section(&d, media)?;
                    Some((
                        tagged.attribute("ice-ufrag")??.to_owned(),
                        tagged.attribute("ice-pwd")??.to_owned(),
                    ))
                })
                .collect();
            for (media, credentials) in d.media_descriptions.iter_mut().zip(credentials) {
                let Some((ufrag, pwd)) = credentials else {
                    continue;
                };
                let at = media
                    .attributes
                    .iter()
                    .position(|a| a.key == ATTR_KEY_BUNDLE_ONLY)
                    .unwrap_or(media.attributes.len());
                media.attributes.insert(
                    at,
                    sdp::description::common::Attribute::new("ice-pwd".to_owned(), Some(pwd)),
                );
                media.attributes.insert(
                    at,
                    sdp::description::common::Attribute::new("ice-ufrag".to_owned(), Some(ufrag)),
                );
            }
        }

        Ok(d)
    }
}

pub(crate) fn get_mid_value(media: &MediaDescription) -> Option<&String> {
    for attr in &media.attributes {
        if attr.key == "mid" {
            return attr.value.as_ref();
        }
    }
    None
}

pub(crate) fn get_peer_direction(media: &MediaDescription) -> RTCRtpTransceiverDirection {
    for a in &media.attributes {
        let direction = RTCRtpTransceiverDirection::from(a.key.as_str());
        if direction != RTCRtpTransceiverDirection::Unspecified {
            return direction;
        }
    }
    RTCRtpTransceiverDirection::Unspecified
}

/// The `a=tls-id` attribute of RFC 8842 section 4.
pub(crate) const ATTR_KEY_TLS_ID: &str = "tls-id";

/// RFC 8842 section 4: `tls-id-value = 20*255(tls-id-char)`,
/// `tls-id-char = ALPHA / DIGIT / "+" / "/" / "-" / "_"`.
pub(crate) fn is_valid_tls_id(value: &str) -> bool {
    (20..=255).contains(&value.len())
        && value
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b"+/-_".contains(&b))
}

/// The remote `a=tls-id` (RFC 8842 section 4), if the description has one.
///
/// The attribute is media-level and its multiplexing category is IDENTICAL: it sits on the
/// BUNDLE-tag m-section, and any other section that repeats it must give the same value. A
/// value outside the syntax, or two sections of the one transport that disagree, make the
/// description [`Error::ErrSessionDescriptionInvalidTlsId`]. No peer is required to send it.
///
/// Each transport is a DTLS association of its own (RFC 8842 section 5), so sections on
/// different transports may state different values: sections are on one transport when they
/// share ICE credentials (an initial BUNDLE offer gives each section that is not bundle-only
/// its own, RFC 9143 section 7.2; a section outside every group has its own). The value
/// returned is the first section's that states one: the description (or the part of it,
/// `transport_layout::description_for`) the caller sets up starts with its transport.
pub(crate) fn extract_tls_id(desc: &SessionDescription) -> Result<Option<String>> {
    let mut first: Option<&str> = None;
    let mut by_transport: HashMap<Option<&str>, &str> = HashMap::new();
    for m in &desc.media_descriptions {
        for attribute in m.attributes.iter().filter(|a| a.key == ATTR_KEY_TLS_ID) {
            let value = attribute
                .value
                .as_deref()
                .filter(|value| is_valid_tls_id(value))
                .ok_or(Error::ErrSessionDescriptionInvalidTlsId)?;
            if is_rejected_media(m) {
                continue;
            }
            let (ufrag, _) = media_ice_credentials(desc, m);
            if by_transport
                .insert(ufrag, value)
                .is_some_and(|earlier| earlier != value)
            {
                return Err(Error::ErrSessionDescriptionInvalidTlsId);
            }
            first.get_or_insert(value);
        }
    }
    Ok(first.map(str::to_owned))
}

/// Whether the description has an RTP media section that is not rejected: such a session needs
/// SRTP keys from the DTLS association (RFC 5764, RFC 8827 section 6.5).
pub(crate) fn has_rtp_media(desc: &SessionDescription) -> bool {
    desc.media_descriptions
        .iter()
        .any(|m| !is_rejected_media(m) && matches!(m.media_name.media.as_str(), "audio" | "video"))
}

/// Checks the syntax of every DTLS attribute of a remote description, at session level and in
/// every m-section, before any of the description is applied: `a=fingerprint` (RFC 8122 section
/// 5), `a=setup` (RFC 4145 section 4, RFC 8842 section 5.1) and `a=tls-id` (RFC 8842 section
/// 4). Whether the description has the fingerprints it needs is [`extract_fingerprints`]'s
/// question.
pub(crate) fn validate_dtls_attributes(
    desc: &SessionDescription,
    accept_lowercase_fingerprints: bool,
) -> Result<()> {
    let fingerprints = |attributes: &[sdp::description::common::Attribute]| -> Result<()> {
        for attribute in attributes.iter().filter(|a| a.key == "fingerprint") {
            parse_fingerprint_attribute(
                attribute
                    .value
                    .as_deref()
                    .ok_or(Error::ErrSessionDescriptionInvalidFingerprint)?,
                accept_lowercase_fingerprints,
            )?;
        }
        Ok(())
    };
    fingerprints(&desc.attributes)?;
    for m in &desc.media_descriptions {
        fingerprints(&m.attributes)?;
    }
    validate_setup_attributes(desc)?;
    // Every `tls-id` is well formed, a rejected section's too (RFC 8842 section 4).
    for m in &desc.media_descriptions {
        for attribute in m.attributes.iter().filter(|a| a.key == ATTR_KEY_TLS_ID) {
            if !attribute.value.as_deref().is_some_and(is_valid_tls_id) {
                return Err(Error::ErrSessionDescriptionInvalidTlsId);
            }
        }
    }
    // One `tls-id` per transport (RFC 8842 section 5): each BUNDLE group and each section
    // outside one is checked on its own.
    let groups = crate::peer_connection::transport_layout::transport_groups(desc);
    if groups.is_empty() {
        extract_tls_id(desc)?;
    }
    for group in groups {
        extract_tls_id(&crate::peer_connection::transport_layout::description_for(
            desc, &group,
        ))?;
    }
    Ok(())
}

/// Extracts the remote DTLS fingerprints (RFC 8122 §5).
///
/// A section carries one `a=fingerprint` line per certificate and hash function (W3C
/// `RTCPeerConnection` writes one for each of its certificates), and the peer's certificate must
/// match one of them, so all of them are returned, the sha-256 ones first (which of them DTLS
/// verification uses is `preferred_fingerprints`' choice).
///
/// "If it is a session-level attribute, it applies to all TLS sessions for which no media-level
/// fingerprint attribute is defined": each m-section that is not rejected has its own
/// fingerprints, or the session-level ones when it has none. All of them share one transport,
/// so their sets must agree on the sha-256 values when they have any (else on every value), or
/// the description is [`Error::ErrSessionDescriptionConflictingFingerprints`]; a session-level
/// set that every section overrides applies to nothing and is not compared. A value that does
/// not follow the attribute's syntax is [`Error::ErrSessionDescriptionInvalidFingerprint`],
/// wherever it sits.
///
/// With BUNDLE, `a=fingerprint` is of the TRANSPORT category (RFC 8859 section 4.5 and
/// appendix A): the group's transport is set up from its tagged section, so that section's
/// fingerprints are the group's, and what the other bundled sections carry is not used (RFC
/// 9143 section 7.1.3: their transport attributes are the offerer's proposal for transports
/// BUNDLE replaces). They are therefore not compared, unless
/// [`check_bundled_fingerprints_agree`] is asked for.
pub(crate) fn extract_fingerprints(desc: &SessionDescription) -> Result<Vec<RTCDtlsFingerprint>> {
    fingerprints_in_force(desc, false)
}

/// The hardening of `SettingEngineBuilder::with_bundled_fingerprints_agreeing`: every bundled
/// section's fingerprints must agree with the tagged section's, as those of sections outside
/// the group already must ([`Error::ErrSessionDescriptionConflictingFingerprints`]). Stricter
/// than RFC 8859 section 4.5, which takes the tagged section's and ignores the others.
pub(crate) fn check_bundled_fingerprints_agree(desc: &SessionDescription) -> Result<()> {
    fingerprints_in_force(desc, true).map(|_| ())
}

fn fingerprints_in_force(
    desc: &SessionDescription,
    every_bundled_section: bool,
) -> Result<Vec<RTCDtlsFingerprint>> {
    let parse =
        |attributes: &[sdp::description::common::Attribute]| -> Result<Vec<RTCDtlsFingerprint>> {
            let mut fingerprints = vec![];
            for attribute in attributes.iter().filter(|a| a.key == "fingerprint") {
                fingerprints.push(parse_fingerprint_attribute(
                    attribute
                        .value
                        .as_deref()
                        .ok_or(Error::ErrSessionDescriptionInvalidFingerprint)?,
                    // The case of the digits is `validate_dtls_attributes`' question.
                    true,
                )?);
            }
            // sha-256 first; the order within an algorithm is kept.
            fingerprints.sort_by_key(|f| !f.algorithm.eq_ignore_ascii_case("sha-256"));
            Ok(fingerprints)
        };
    let compared = |fingerprints: &[RTCDtlsFingerprint]| -> Vec<(String, String)> {
        let has_sha256 = fingerprints
            .iter()
            .any(|f| f.algorithm.eq_ignore_ascii_case("sha-256"));
        let mut set: Vec<(String, String)> = fingerprints
            .iter()
            .filter(|f| !has_sha256 || f.algorithm.eq_ignore_ascii_case("sha-256"))
            .map(|f| (f.algorithm.to_lowercase(), f.value.to_lowercase()))
            .collect();
        set.sort();
        set.dedup();
        set
    };

    let session_level = parse(&desc.attributes)?;
    // The fingerprints in force for each m-section that has a transport, and those of the
    // rejected ones, which only count when nothing else gives any.
    let mut in_force = vec![];
    let mut rejected = vec![];
    for m in &desc.media_descriptions {
        let media_level = parse(&m.attributes)?;
        // A bundled section other than its group's tagged one: its transport attributes are
        // not the group's (RFC 8859 section 4.5). Still parsed, so a malformed value refuses
        // the description wherever it sits.
        let untagged = tagged_section(desc, m).is_some_and(|tagged| !std::ptr::eq(tagged, m));
        if is_rejected_media(m) {
            rejected.push(media_level);
        } else if untagged && !every_bundled_section {
            continue;
        } else if media_level.is_empty() {
            in_force.push(session_level.clone());
        } else {
            in_force.push(media_level);
        }
    }
    in_force.retain(|level| !level.is_empty());
    if in_force.is_empty() {
        in_force.push(session_level);
        in_force.append(&mut rejected);
        in_force.retain(|level| !level.is_empty());
    }

    let Some(first) = in_force.first() else {
        return Err(Error::ErrSessionDescriptionNoFingerprint);
    };
    let expected = compared(first);
    if in_force[1..]
        .iter()
        .any(|level| compared(level) != expected)
    {
        return Err(Error::ErrSessionDescriptionConflictingFingerprints);
    }

    Ok(in_force.swap_remove(0))
}

/// RFC 8830 section 2: "Multiple media descriptions with the same value for 'msid-id' and
/// 'msid-appdata' are not permitted". W3C webrtc-pc lets one track be sent by several
/// transceivers (`addTransceiver(track)` twice), and the appdata this endpoint writes is the
/// track id (`with_msid_appdata`), so two sections would carry the same pair. Both allow
/// distinct appdata: a section whose `a=msid` repeats an earlier section's pair has its
/// appdata (and its source-level `msid`) made unique with a suffix, `<track id>-<n>`, kept
/// within the 64 token characters. The same sections give the same result every time, so a
/// later offer keeps the lines (RFC 9429 section 5.2.2). A line without appdata (the RFC 9429
/// form) is not a pair: the RFC 9429 section 5.2.1 examples have one stream in two sections.
fn make_msid_pairs_unique(desc: &mut SessionDescription) {
    let mut used: HashSet<(String, String)> = HashSet::new();
    for media in &mut desc.media_descriptions {
        // The line is `a=msid:<id> <appdata>`: written as a property attribute whose key
        // holds it all (`add_sender_sdp`), or parsed as key `msid` and a value.
        let msid_value = |a: &sdp::description::common::Attribute| -> Option<String> {
            if a.key == "msid" {
                a.value.clone()
            } else {
                a.key
                    .strip_prefix("msid:")
                    .filter(|_| a.value.is_none())
                    .map(str::to_owned)
            }
        };
        let pairs: Vec<(String, String)> = media
            .attributes
            .iter()
            .filter_map(|a| {
                let value = msid_value(a)?;
                let (id, appdata) = value.split_once(' ')?;
                Some((id.to_owned(), appdata.to_owned()))
            })
            .collect();
        let Some(appdata) = pairs.first().map(|(_, appdata)| appdata.clone()) else {
            continue;
        };
        let clashes = |appdata: &str, used: &HashSet<(String, String)>| {
            pairs
                .iter()
                .any(|(id, _)| used.contains(&(id.clone(), appdata.to_owned())))
        };
        let mut unique = appdata.clone();
        let mut n = 1u32;
        while clashes(&unique, &used) {
            let suffix = format!("-{n}");
            let keep = appdata.len().min(64 - suffix.len());
            unique = format!("{}{suffix}", &appdata[..keep]);
            n += 1;
        }
        for (id, _) in &pairs {
            used.insert((id.clone(), unique.clone()));
        }
        if unique == appdata {
            continue;
        }
        for a in media.attributes.iter_mut() {
            if a.value.is_none()
                && let Some(id) = a
                    .key
                    .strip_prefix("msid:")
                    .and_then(|v| v.split_once(' '))
                    .map(|(id, _)| id.to_owned())
            {
                a.key = format!("msid:{id} {unique}");
                continue;
            }
            let Some(value) = a.value.as_mut() else {
                continue;
            };
            if a.key == "msid" {
                if let Some((id, _)) = value.split_once(' ') {
                    *value = format!("{id} {unique}");
                }
            } else if a.key == ATTR_KEY_SSRC
                && let Some((ssrc, source)) = value.split_once(' ')
                && let Some(msid) = source.strip_prefix("msid:")
                && let Some((id, _)) = msid.split_once(' ')
            {
                *value = format!("{ssrc} msid:{id} {unique}");
            }
        }
    }
}

/// Inserts `a=<key>[:<value>]` at the end of m-section `index` of an SDP text, keeping every
/// other byte, with the text's own line ending. Returns the text unchanged if it has no such
/// m-section.
pub(crate) fn insert_media_line(sdp: &str, index: usize, key: &str, value: Option<&str>) -> String {
    let eol = if sdp.contains("\r\n") { "\r\n" } else { "\n" };
    let mut starts = vec![];
    let mut offset = 0;
    for line in sdp.split_inclusive('\n') {
        if line.starts_with("m=") {
            starts.push(offset);
        }
        offset += line.len();
    }
    if index >= starts.len() {
        return sdp.to_owned();
    }
    let end = starts.get(index + 1).copied().unwrap_or(sdp.len());
    let mut out = String::with_capacity(sdp.len() + key.len() + 64);
    out.push_str(&sdp[..end]);
    if !out.ends_with('\n') {
        out.push_str(eol);
    }
    out.push_str("a=");
    out.push_str(key);
    if let Some(value) = value {
        out.push(':');
        out.push_str(value);
    }
    out.push_str(eol);
    out.push_str(&sdp[end..]);
    out
}

/// The remote ICE credentials and candidates of a session description.
#[derive(Debug, Clone)]
pub(crate) struct RemoteIceDetails {
    pub(crate) ufrag: String,
    pub(crate) pwd: String,
    pub(crate) candidates: Vec<Candidate>,
}

/// Whether an m-section is rejected: port zero without `a=bundle-only` (RFC 8843 §6, an
/// m-section that is only reachable through its BUNDLE group also has port zero).
///
/// In an offer, port zero with `a=bundle-only` is a bundled section (RFC 9143 sections 7.2
/// and 13). In an answer port zero is always a rejection (section 7.3.3): this reads so for
/// answers only because no answer it is given carries `a=bundle-only`. This engine writes none
/// (RFC 9429 section 5.3.1) and a remote answer's is discarded when it is parsed, inside a
/// BUNDLE group too ([`discard_stray_bundle_only`] with `answers`). The callers that read
/// answers (`check_answer_against_offer`, the answer passes of `set_remote_description` and
/// `internal.rs`, `negotiated_sctp`, `describes_sctp_association`) rely on that; pinned by
/// `tests/data_channel_max_bundle_rtc2rtc.rs::a_bundle_only_attribute_in_an_answer_does_not_keep_a_zero_port_section`.
pub(crate) fn is_rejected_media(m: &MediaDescription) -> bool {
    m.media_name.port.value == 0 && !m.has_attribute(ATTR_KEY_BUNDLE_ONLY)
}

/// Whether `s` can be an `msid-id` or `msid-appdata` (RFC 8830 section 2: `1*64token-char`).
pub(crate) fn is_msid_token(s: &str) -> bool {
    s.len() <= 64 && is_sdp_token(s)
}

/// Whether `s` is a `token` of RFC 8866 section 9: one or more of the characters
/// `!#$%&'*+-.0-9A-Z^_`a-z{|}~`.
pub(crate) fn is_sdp_token(s: &str) -> bool {
    !s.is_empty()
        && s.bytes().all(|b| {
            matches!(b,
                0x21 | 0x23..=0x27 | 0x2A..=0x2B | 0x2D..=0x2E | 0x30..=0x39 | 0x41..=0x5A
                | 0x5E..=0x7E)
        })
}

/// `a=rtcp-xr` (RFC 3611 section 5.1).
pub(crate) const ATTR_KEY_RTCP_XR: &str = "rtcp-xr";
/// The `xr-format` of `a=rtcp-xr` that asks for receiver reference times and DLRR responses
/// (RFC 3611 section 5.1, `rcvr-rtt=<mode>`).
const XR_FORMAT_RCVR_RTT: &str = "rcvr-rtt";
/// The stream feedback type of an `a=rtcp-xr` format other than `rcvr-rtt` (RFC 3611 section
/// 5.1); its parameter is the `xr-format` in full.
pub const RTCP_FB_XR: &str = "xr";
/// The feedback parameter that marks `rrtr` as coming from `a=rtcp-xr:rcvr-rtt` rather
/// than from an `a=rtcp-fb` line (libwebrtc's name for the same thing): the `xr-format` in
/// full, `rcvr-rtt=<mode>[:<max size>]`, which starts with this.
pub(crate) const RRTR_FROM_RTCP_XR: &str = "rcvr-rtt";

/// Whether an `xr-format` is `rcvr-rtt` (with its mode and maximum size).
fn is_rcvr_rtt(format: &str) -> bool {
    format.split(['=', ':']).next() == Some(XR_FORMAT_RCVR_RTT)
}

/// The `xr-format`s of a section's `a=rtcp-xr`, `None` without one.
pub(crate) fn media_rtcp_xr(media: &MediaDescription) -> Option<Vec<String>> {
    media.attribute(ATTR_KEY_RTCP_XR).map(|value| {
        value
            .unwrap_or_default()
            .split_whitespace()
            .map(str::to_owned)
            .collect()
    })
}

/// Gives each audio and video section of a received description the session-level
/// `a=rtcp-xr` when it has none of its own (RFC 3611 section 5.1: the attribute "can be used
/// at the session or media level", and at media level it replaces the session's). Only the
/// parsed description changes.
pub(crate) fn inherit_session_rtcp_xr(desc: &mut SessionDescription) {
    let Some(session) = desc
        .attributes
        .iter()
        .find(|a| a.key == ATTR_KEY_RTCP_XR)
        .cloned()
    else {
        return;
    };
    for media in &mut desc.media_descriptions {
        if matches!(media.media_name.media.as_str(), "audio" | "video")
            && media.attribute(ATTR_KEY_RTCP_XR).is_none()
        {
            media.attributes.push(session.clone());
        }
    }
}

/// Gives each audio and video section of a received description the session-level
/// `a=extmap` lines it does not override (RFC 8285 section 5: the mappings may be "provided
/// per media stream ... or globally for all streams"; RFC 9429 section 5.8.1 stores them, and
/// section 5.3.1 has session-level attributes count as present in each m= section). A
/// section's own mapping for an id or a URI wins. Only the parsed description changes.
/// RFC 8285 section 5: "The definitions MUST be either all session level or all media level;
/// it is not permitted to mix the two styles." A received description that has `a=extmap`
/// lines at both levels is refused.
pub(crate) fn check_extmap_levels(desc: &SessionDescription) -> Result<()> {
    let at_session = desc.attributes.iter().any(|a| a.key == ATTR_KEY_EXT_MAP);
    if at_session
        && desc
            .media_descriptions
            .iter()
            .any(|m| m.attributes.iter().any(|a| a.key == ATTR_KEY_EXT_MAP))
    {
        return Err(Error::SdpInvalidValue(
            "a=extmap at both session and media level (RFC 8285 section 5)".to_owned(),
        ));
    }
    Ok(())
}

pub(crate) fn inherit_session_extmap(desc: &mut SessionDescription) {
    let session: Vec<(String, String, String)> = desc
        .attributes
        .iter()
        .filter(|a| a.key == ATTR_KEY_EXT_MAP)
        .filter_map(|a| a.value.clone())
        .filter_map(|value| {
            let mut tokens = value.split_whitespace();
            let id = tokens.next()?.split('/').next()?.to_owned();
            let uri = tokens.next()?.to_owned();
            Some((id, uri, value))
        })
        .collect();
    if session.is_empty() {
        return;
    }
    for media in &mut desc.media_descriptions {
        if !matches!(media.media_name.media.as_str(), "audio" | "video") {
            continue;
        }
        let own: Vec<(String, String)> = media
            .attributes
            .iter()
            .filter(|a| a.key == ATTR_KEY_EXT_MAP)
            .filter_map(|a| a.value.as_deref())
            .filter_map(|value| {
                let mut tokens = value.split_whitespace();
                let id = tokens.next()?.split('/').next()?.to_owned();
                Some((id, tokens.next()?.to_owned()))
            })
            .collect();
        for (id, uri, value) in &session {
            if !own
                .iter()
                .any(|(own_id, own_uri)| own_id == id || own_uri == uri)
            {
                media
                    .attributes
                    .push(sdp::description::common::Attribute::new(
                        ATTR_KEY_EXT_MAP.to_owned(),
                        Some(value.clone()),
                    ));
            }
        }
    }
}

/// Refuses a received description whose header extension mappings contradict each other
/// (RFC 8285 sections 5 and 7):
///
/// - an id in the valid range mapped to two different extensions in one m= section, or in
///   two m= sections of one BUNDLE group, which share one id space (section 5: "Each local
///   identifier potentially used in the stream is mapped to an extension"; section 7: "The
///   local identifiers MUST be unique in an RTP session"; "All the 'm=' lines in a BUNDLE
///   group are considered to be part of the same local identifier (ID) space");
/// - one extension (URI, form and attributes) mapped to two ids in a section (section 5:
///   "MUST NOT" appear more than once per stream) or, within a BUNDLE group, to different
///   ids (section 7: "it MUST use the same ID in all of these 'm=' lines").
///
/// The ids of the extended range (4096 to 4351) are left out: they may be repeated for
/// alternatives (section 7). Checked after the session-level mappings are inherited.
pub(crate) fn check_extmap_ids(desc: &SessionDescription) -> Result<()> {
    // (URI, encrypted form, attributes) under an id.
    type Mapping = (u16, (String, bool, Option<String>));
    // A section's mid and its mappings.
    type Section = (Option<String>, Vec<Mapping>);
    let sections: Vec<Section> = desc
        .media_descriptions
        .iter()
        .filter(|m| {
            !is_rejected_media(m) && matches!(m.media_name.media.as_str(), "audio" | "video")
        })
        .map(|m| {
            let lines = section_extmap_lines(m)?
                .into_iter()
                .map(|(uri, e)| (e.id, (uri, e.encrypted, e.attributes)))
                .collect();
            Ok((get_mid_value(m).cloned(), lines))
        })
        .collect::<Result<_>>()?;
    let groups = bundle_groups(desc);
    let group_of = |mid: &Option<String>| {
        mid.as_deref()
            .and_then(|mid| groups.iter().position(|g| g.contains(&mid)))
    };
    let mut scopes: HashMap<(Option<usize>, usize), Vec<Mapping>> = HashMap::new();
    for (n, (mid, lines)) in sections.iter().enumerate() {
        // A bundled section shares the group's id space; any other has its own.
        let scope = match group_of(mid) {
            Some(group) => (Some(group), 0),
            None => (None, n),
        };
        let seen = scopes.entry(scope).or_default();
        for (id, ext) in lines {
            for (seen_id, seen_ext) in seen.iter() {
                if seen_id == id && seen_ext != ext {
                    return Err(Error::SdpInvalidValue(format!(
                        "a=extmap id {id} maps both {} and {} (RFC 8285 sections 5 and 7)",
                        seen_ext.0, ext.0
                    )));
                }
                if seen_ext == ext && seen_id != id {
                    return Err(Error::SdpInvalidValue(format!(
                        "a=extmap maps {} to both id {seen_id} and id {id} (RFC 8285 sections 5 \
                         and 7)",
                        ext.0
                    )));
                }
            }
            seen.push((*id, ext.clone()));
        }
    }
    Ok(())
}

/// Gives the header extensions an offer numbered in the extended range (4096 to 4351) an id
/// this endpoint can use, or drops them (RFC 8285 section 7: "The answerer SHOULD select, at
/// most, one of the offered extensions with the same identifier and remap it to a free
/// identifier in the valid range for that extension to be usable"; likewise for more
/// extensions than the valid range holds).
///
/// Per section and extended id, the first alternative `supported` accepts for the section's
/// media kind is kept; it takes the id the description already maps that extension to, or
/// else the first id of [`local_extension_ids`] that no mapping of the description and none
/// in `taken` uses. The other alternatives, and extensions nothing accepts, are dropped. Only
/// the parsed description changes, so the media engine negotiates the remapped id and the
/// answer states it.
pub(crate) fn remap_answerer_assigned_extmaps(
    desc: &mut SessionDescription,
    supported: impl Fn(&str, &str) -> bool,
    taken: &[u16],
) {
    let parse = |value: &str| -> Option<(u32, String, String)> {
        let mut tokens = value.splitn(2, ' ');
        let entry = tokens.next()?;
        let rest = tokens.next()?.to_owned();
        let id = entry.split('/').next()?.parse::<u32>().ok()?;
        let uri = rest.split_whitespace().next()?;
        let effective = if uri == ENCRYPT_URI {
            rest.split_whitespace().nth(1).unwrap_or("").to_owned()
        } else {
            uri.to_owned()
        };
        Some((id, effective, rest))
    };
    let extended = |id: u32| (4096..=4351).contains(&id);
    if !desc.media_descriptions.iter().any(|m| {
        m.attributes
            .iter()
            .filter(|a| a.key == ATTR_KEY_EXT_MAP)
            .filter_map(|a| a.value.as_deref().and_then(parse))
            .any(|(id, _, _)| extended(id))
    }) {
        return;
    }
    // Ids the description maps in the valid range, and to what.
    let mut used: Vec<(u16, String)> = desc
        .media_descriptions
        .iter()
        .flat_map(|m| m.attributes.iter())
        .chain(desc.attributes.iter())
        .filter(|a| a.key == ATTR_KEY_EXT_MAP)
        .filter_map(|a| a.value.as_deref().and_then(parse))
        .filter(|(id, _, _)| (1..=255).contains(id))
        .map(|(id, _, rest)| (id as u16, rest))
        .collect();
    for media in &mut desc.media_descriptions {
        let kind = media.media_name.media.clone();
        let mut chosen: HashSet<u32> = HashSet::new();
        let mut attributes = Vec::with_capacity(media.attributes.len());
        for mut attribute in std::mem::take(&mut media.attributes) {
            let parsed = (attribute.key == ATTR_KEY_EXT_MAP)
                .then(|| attribute.value.as_deref().and_then(parse))
                .flatten();
            let Some((id, effective, rest)) = parsed.filter(|(id, _, _)| extended(*id)) else {
                attributes.push(attribute);
                continue;
            };
            if chosen.contains(&id) || !supported(&kind, &effective) {
                continue;
            }
            let new_id = used
                .iter()
                .find(|(_, r)| *r == rest)
                .map(|(i, _)| *i)
                .or_else(|| {
                    local_extension_ids()
                        .find(|i| !taken.contains(i) && !used.iter().any(|(u, _)| u == i))
                });
            let Some(new_id) = new_id else {
                continue;
            };
            chosen.insert(id);
            if !used.iter().any(|(u, r)| *u == new_id && *r == rest) {
                used.push((new_id, rest.clone()));
            }
            let direction = attribute
                .value
                .as_deref()
                .and_then(|v| v.split(' ').next())
                .and_then(|entry| entry.split_once('/'))
                .map(|(_, d)| format!("/{d}"))
                .unwrap_or_default();
            attribute.value = Some(format!("{new_id}{direction} {rest}"));
            attributes.push(attribute);
        }
        media.attributes = attributes;
    }
}

/// The direction an answer gives each extension of an offered section that restricts one
/// (RFC 8285 section 7), by URI: sendonly is answered recvonly, recvonly sendonly, inactive
/// inactive. An extension offered without a direction (or sendrecv) is not in the map.
pub(crate) fn answered_extension_directions(
    m: &MediaDescription,
) -> HashMap<String, sdp::direction::Direction> {
    use sdp::direction::Direction;
    let mut out = HashMap::new();
    for (uri, mapping) in rtp_extensions_from_media_description(m).unwrap_or_default() {
        let answered = match mapping.direction {
            Direction::SendOnly => Direction::RecvOnly,
            Direction::RecvOnly => Direction::SendOnly,
            Direction::Inactive => Direction::Inactive,
            _ => continue,
        };
        out.insert(uri, answered);
    }
    out
}

/// Drops the `a=bundle-only` attributes of a received description that do not mean
/// "this section has port zero because it is only reachable through its BUNDLE group":
///
/// - RFC 9143 section 6: "If an offerer or answerer receives a 'bundle-only' attribute in a
///   non-bundled 'm=' section, the offerer or answerer MUST discard the attribute." Without
///   it a port-zero section is what port zero says: rejected (RFC 3264 section 6).
/// - RFC 9143 sections 7.3.2 and 7.3.3 and RFC 9429 section 5.3.1: no m= section of an
///   answer has the attribute, so one in an answer is discarded too. [`is_rejected_media`]
///   relies on this for every answer it reads: a zero port in an answer is a rejection.
///
/// Only the parsed description changes: the SDP text stays as given.
pub(crate) fn discard_stray_bundle_only(desc: &mut SessionDescription, answers: bool) {
    let bundled: HashSet<String> = bundle_groups(desc)
        .into_iter()
        .flatten()
        .map(str::to_owned)
        .collect();
    for media in &mut desc.media_descriptions {
        let in_group = get_mid_value(media).is_some_and(|mid| bundled.contains(mid.as_str()));
        if answers || !in_group {
            media.attributes.retain(|a| a.key != ATTR_KEY_BUNDLE_ONLY);
        }
    }
}

/// RFC 9429 section 5.8: "If any line is not well formed or cannot be parsed as described,
/// the parser MUST stop with an error and reject the session description, even if the value
/// is to be discarded." `unmarshal` checks every line type; this checks the value of every
/// attribute, at session and media level, by the grammar of its name
/// ([`sdp::attribute::check_attribute`]: `a=rtcp` by RFC 3605 section 2.1, which section
/// 5.8.2 asks to be parsed although its value is ignored, and every other attribute rtci-sdp
/// has a type for; an unknown attribute is ignored, RFC 8866 section 5.13).
///
/// The exceptions are the lines another specification has the receiver ignore when they are
/// malformed, which the reader of each then skips:
/// - `a=msid`: RFC 8830 section 2, "If the 'msid' attribute does not conform to the ABNF
///   given here, it SHOULD be ignored" (`media_msid`), and the `msid` source attribute
///   (`a=ssrc:<id> msid:...`, appendix A) likewise;
/// - `a=rid`: RFC 8851 section 6.2.2 step 1, "In the case of a syntax error, the 'a=rid'
///   line is discarded" (`section_rids`).
///
/// Unless `strict`, white space at the end of a value is not held against it
/// (`SettingEngineBuilder::with_strict_sdp_attribute_grammar`: webrtc-rs 0.17.x ends an
/// `a=rtcp-fb` without parameters with a space, against RFC 4585 section 4.2's
/// `rtcp-fb-param`; Pion did before v4.1.5).
///
/// `a=simulcast` is checked with `rid_ids` (`SettingEngine::rid_id_grammar`), the rid-id
/// grammar `section_rids` reads it with.
pub(crate) fn check_attribute_lines(
    desc: &SessionDescription,
    strict: bool,
    rid_ids: RidIdGrammar,
) -> Result<()> {
    // RFC 8866 section 6.7: "At most one occurrence of "a=recvonly", "a=sendrecv",
    // "a=sendonly", or "a=inactive" MAY appear at session level, and at most one MAY appear
    // in each media description": a level with two is ambiguous, and refused.
    desc.direction()?;
    for media in &desc.media_descriptions {
        media.direction()?;
    }
    let lines = desc.attributes.iter().chain(
        desc.media_descriptions
            .iter()
            .flat_map(|media| media.attributes.iter()),
    );
    for a in lines.filter(|a| !MALFORMED_IGNORED.contains(&a.key.as_str())) {
        let trimmed;
        let a = match a.value.as_deref() {
            Some(value) if !strict && value.len() != value.trim_end().len() => {
                trimmed = sdp::description::common::Attribute::new(
                    a.key.clone(),
                    Some(value.trim_end().to_owned()),
                );
                &trimmed
            }
            _ => a,
        };
        match a.value.as_deref().and_then(|v| v.split_once(' ')) {
            // `msid` is also a source attribute (RFC 8830 appendix A), ignored when malformed
            // as the media-level one is: the line's SSRC and attribute name are checked.
            Some((id, source)) if a.key == ATTR_KEY_SSRC && source.starts_with("msid:") => {
                sdp::attribute::check_attribute(&sdp::description::common::Attribute::new(
                    ATTR_KEY_SSRC.to_owned(),
                    Some(format!("{id} msid-ignored")),
                ))?;
            }
            _ if a.key == SDP_ATTRIBUTE_SIMULCAST => {
                sdp::attribute::Simulcast::parse_with(
                    a.value.as_deref().unwrap_or_default(),
                    rid_ids,
                )?;
            }
            _ => sdp::attribute::check_attribute(a)?,
        }
    }
    Ok(())
}

/// The attributes whose malformed lines are ignored rather than refused (see
/// [`check_attribute_lines`]).
const MALFORMED_IGNORED: [&str; 2] = ["msid", "rid"];

/// RFC 5888 section 6: "'a=group' lines that contain identification-tags that do not
/// correspond to any 'm' line within the session description MUST be ignored. The
/// application acts as if the 'a=group' line did not exist." Such lines (of any semantics)
/// are taken out of the parsed description; the SDP text stays as given. In an answer a
/// BUNDLE group is kept: RFC 9143 section 7.4 makes one that names a section the offer did
/// not bundle an error, which the answer check reports.
pub(crate) fn discard_groups_with_unknown_tags(desc: &mut SessionDescription, answers: bool) {
    let mids: HashSet<String> = desc
        .media_descriptions
        .iter()
        .filter_map(|media| get_mid_value(media).cloned())
        .collect();
    desc.attributes.retain(|a| {
        a.key != ATTR_KEY_GROUP
            || (answers
                && a.value
                    .as_deref()
                    .is_some_and(|value| value.split_whitespace().next() == Some("BUNDLE")))
            || a.value.as_deref().is_none_or(|value| {
                value
                    .split_whitespace()
                    .skip(1)
                    .all(|tag| mids.contains(tag))
            })
    });
}

/// The mids of the description's first `a=group:BUNDLE` (RFC 8843 §7.1), in order.
/// The SSRCs a description mentions (`a=ssrc` and `a=ssrc-group` lines, RFC 5576 sections 4.1,
/// 4.2), in any section.
pub(crate) fn described_ssrcs(desc: &SessionDescription) -> HashSet<SSRC> {
    let mut ssrcs = HashSet::new();
    for media in &desc.media_descriptions {
        for a in &media.attributes {
            let Some(value) = a.value.as_deref() else {
                continue;
            };
            match a.key.as_str() {
                "ssrc" => ssrcs.extend(
                    value
                        .split_whitespace()
                        .next()
                        .and_then(|id| id.parse::<SSRC>().ok()),
                ),
                "ssrc-group" => ssrcs.extend(
                    value
                        .split_whitespace()
                        .skip(1)
                        .filter_map(|id| id.parse::<SSRC>().ok()),
                ),
                _ => {}
            }
        }
    }
    ssrcs
}

/// The CNAME each SSRC of a description is declared with (`a=ssrc:<ssrc> cname:<cname>`, RFC
/// 5576 section 6.1), in any section: "This MUST be the CNAME value that the media sender will
/// place in its RTCP SDES packets". An SSRC declared twice keeps its first one (section 6.1:
/// the attribute "MUST NOT occur more than once for the same ssrc-id within a given media
/// stream"). At most [`MAX_REMOTE_CNAMES`](crate::peer_connection::handler::interceptor::MAX_REMOTE_CNAMES).
pub(crate) fn declared_cnames(desc: &SessionDescription) -> HashMap<SSRC, String> {
    use crate::peer_connection::handler::interceptor::MAX_REMOTE_CNAMES;
    let mut cnames = HashMap::new();
    for media in &desc.media_descriptions {
        for a in &media.attributes {
            if a.key != ATTR_KEY_SSRC {
                continue;
            }
            let Some((id, attribute)) = a.value.as_deref().and_then(|v| v.split_once(' ')) else {
                continue;
            };
            let (Ok(ssrc), Some(cname)) = (id.parse::<SSRC>(), attribute.strip_prefix("cname:"))
            else {
                continue;
            };
            if cnames.len() < MAX_REMOTE_CNAMES {
                cnames.entry(ssrc).or_insert_with(|| cname.to_owned());
            }
        }
    }
    cnames
}

/// The decoding dependencies of a description (RFC 5583): for each media section in an
/// `a=group:DDP` group, its mid and its `a=depend` (section 5.2.2). A group whose sections do
/// not all state the same dependency type ("In a DDP group, all media streams MUST have the
/// same type of decoding dependency") is left out, as is a malformed `a=depend`.
pub(crate) fn decoding_dependencies(
    desc: &SessionDescription,
) -> Vec<(String, sdp::attribute::Depend)> {
    use sdp::attribute::{Depend, TypedAttribute};
    let mut out: Vec<(String, Depend)> = vec![];
    for group in desc
        .attributes
        .iter()
        .filter(|a| a.key == ATTR_KEY_GROUP)
        .filter_map(|a| a.value.as_deref())
        .filter_map(|value| {
            let mut tokens = value.split_whitespace();
            (tokens.next() == Some("DDP")).then(|| tokens.map(str::to_owned).collect::<Vec<_>>())
        })
    {
        let members: Vec<(String, Depend)> = desc
            .media_descriptions
            .iter()
            .filter_map(|m| {
                let mid = get_mid_value(m)?;
                if !group.contains(mid) {
                    return None;
                }
                let depend = m
                    .attribute(Depend::NAME)
                    .flatten()
                    .and_then(|v| Depend::parse(v).ok())?;
                Some((mid.clone(), depend))
            })
            .collect();
        let mut types = members
            .iter()
            .flat_map(|(_, d)| d.dependencies.iter().map(|dependency| &dependency.typ));
        let first = types.next();
        if first.is_some() && types.all(|t| Some(t) == first) {
            out.extend(members);
        }
    }
    out
}

/// The tokens of an `a=group` line (its semantics first), `None` for another attribute.
fn group_tokens(a: &sdp::description::common::Attribute) -> Option<Vec<&str>> {
    (a.key == ATTR_KEY_GROUP).then(|| {
        a.value
            .as_deref()
            .unwrap_or("")
            .split_whitespace()
            .collect()
    })
}

/// The `a=group` semantics this endpoint acts on: BUNDLE (RFC 9143), lip synchronization
/// (RFC 5888 section 7) and decoding dependency (RFC 5583).
const UNDERSTOOD_GROUP_SEMANTICS: [&str; 3] = ["BUNDLE", "LS", "DDP"];

/// RFC 5888 section 9.3: "If a server receives an offer that contains empty "a=group" lines,
/// it SHOULD add its capabilities also in the form of empty "a=group" lines to its answer."
/// An offer with an `a=group` line that names no identification-tag is answered with an empty
/// `a=group` line for each semantics this endpoint understands and the answer does not use.
pub(crate) fn answer_group_capabilities(
    offer: &SessionDescription,
    answer: &mut SessionDescription,
) {
    let offered_empty = offer
        .attributes
        .iter()
        .filter_map(group_tokens)
        .any(|tokens| tokens.len() == 1);
    if !offered_empty {
        return;
    }
    for semantics in UNDERSTOOD_GROUP_SEMANTICS {
        let used = answer
            .attributes
            .iter()
            .filter_map(group_tokens)
            .any(|tokens| tokens.first() == Some(&semantics));
        if !used {
            answer
                .attributes
                .push(sdp::description::common::Attribute::new(
                    ATTR_KEY_GROUP.to_owned(),
                    Some(semantics.to_owned()),
                ));
        }
    }
}

/// RFC 5583 section 6.1 (with RFC 5888 section 9.2, which it follows) in an answer to
/// `offer`: an answerer that understands DDP keeps the offered dependencies ("The answerer
/// cannot change the dependency relations") for what it accepts. Each offered DDP group is
/// answered with the mids of its sections the answer accepts, when two remain, and each such
/// section with the offer's `a=depend`, restricted to the formats the answer keeps in it and
/// in the sections it depends on; a dependency left with none of the formats it needs is
/// removed with its format's line, as the answerer "MAY remove media Operation Points".
pub(crate) fn answer_decoding_dependencies(
    offer: &SessionDescription,
    answer: &mut SessionDescription,
) {
    use sdp::attribute::{Depend, TypedAttribute};
    let offered = decoding_dependencies(offer);
    if offered.is_empty() {
        return;
    }
    let formats: HashMap<String, Vec<String>> = answer
        .media_descriptions
        .iter()
        .filter(|m| !is_rejected_media(m))
        .filter_map(|m| Some((get_mid_value(m)?.clone(), m.media_name.formats.clone())))
        .collect();
    let groups: Vec<Vec<String>> = offer
        .attributes
        .iter()
        .filter(|a| a.key == ATTR_KEY_GROUP)
        .filter_map(|a| a.value.as_deref())
        .filter_map(|value| {
            let mut tokens = value.split_whitespace();
            (tokens.next() == Some("DDP")).then(|| tokens.map(str::to_owned).collect::<Vec<_>>())
        })
        // A group `decoding_dependencies` took (its dependent sections are listed); the
        // sections without `a=depend` (a base layer) are members too.
        .filter(|group| offered.iter().any(|(mid, _)| group.contains(mid)))
        .map(|group| {
            group
                .into_iter()
                .filter(|mid| formats.contains_key(mid))
                .collect::<Vec<_>>()
        })
        .filter(|group| group.len() >= 2)
        .collect();
    for group in &groups {
        answer
            .attributes
            .push(sdp::description::common::Attribute::new(
                ATTR_KEY_GROUP.to_owned(),
                Some(format!("DDP {}", group.join(" "))),
            ));
    }
    for media in &mut answer.media_descriptions {
        let Some(mid) = get_mid_value(media).cloned() else {
            continue;
        };
        if !groups.iter().any(|g| g.contains(&mid)) {
            continue;
        }
        let Some((_, depend)) = offered.iter().find(|(m, _)| *m == mid) else {
            continue;
        };
        let own = &formats[&mid];
        let dependencies: Vec<_> = depend
            .dependencies
            .iter()
            .filter(|d| own.contains(&d.fmt))
            .filter_map(|d| {
                let mut d = d.clone();
                if let Some((on, fmts)) = &mut d.on {
                    let kept = formats.get(on.as_str())?;
                    fmts.retain(|f| kept.contains(f));
                    if fmts.is_empty() || !groups.iter().any(|g| g.contains(on)) {
                        return None;
                    }
                }
                Some(d)
            })
            .collect();
        if !dependencies.is_empty() {
            *media = media
                .clone()
                .with_value_attribute(Depend::NAME.to_owned(), Depend { dependencies }.to_string());
        }
    }
}

/// The lip synchronization groups of a description (`a=group:LS`, RFC 5888 section 7), each
/// its mids in order.
pub(crate) fn ls_groups(desc: &SessionDescription) -> Vec<Vec<String>> {
    desc.attributes
        .iter()
        .filter(|a| a.key == ATTR_KEY_GROUP)
        .filter_map(|a| a.value.as_deref())
        .filter_map(|value| {
            let mut tokens = value.split_whitespace();
            (tokens.next() == Some("LS")).then(|| tokens.map(str::to_owned).collect())
        })
        .collect()
}

/// The `a=group:LS` groups of a description being generated (RFC 9429 sections 5.2.1, 5.2.2,
/// 5.3.1). `live` are its accepted RTP sections in order, each with the streams its sender is
/// associated with (empty: none). An offer has a group for each stream more than one of them
/// is associated with, and keeps each group of the most recent answer (`previous`) with the
/// mids still live, when two remain; an answer has, for each offered group (`previous`), the
/// sections of the group that share one stream or have none, when there are two.
fn generated_ls_groups(
    live: &[(String, Vec<String>)],
    previous: &[Vec<String>],
    is_offer: bool,
) -> Vec<Vec<String>> {
    let position = |mid: &String| live.iter().position(|(m, _)| m == mid);
    let ordered = |mut group: Vec<String>| {
        group.sort_by_key(position);
        group.dedup();
        group
    };
    let mut groups: Vec<Vec<String>> = vec![];
    if is_offer {
        for group in previous {
            let kept: Vec<String> = group
                .iter()
                .filter(|mid| position(mid).is_some())
                .cloned()
                .collect();
            if kept.len() >= 2 {
                groups.push(ordered(kept));
            }
        }
        let mut streams: Vec<&String> = vec![];
        for (_, ids) in live {
            for id in ids {
                if !streams.contains(&id) {
                    streams.push(id);
                }
            }
        }
        for stream in streams {
            let members: Vec<String> = live
                .iter()
                .filter(|(_, ids)| ids.contains(stream))
                .map(|(mid, _)| mid.clone())
                .collect();
            if members.len() < 2 {
                continue;
            }
            // A stream's sections join the group of the last answer they are in, if any.
            match groups
                .iter_mut()
                .find(|group| group.iter().any(|mid| members.contains(mid)))
            {
                Some(group) => {
                    let mut joined = group.clone();
                    joined.extend(members);
                    *group = ordered(joined);
                }
                None => groups.push(members),
            }
        }
    } else {
        for group in previous {
            let members: Vec<&(String, Vec<String>)> =
                live.iter().filter(|(mid, _)| group.contains(mid)).collect();
            // The stream most of them share; the first in section order on a tie.
            let mut common: Option<(&String, usize)> = None;
            for (_, ids) in &members {
                for id in ids {
                    let count = members.iter().filter(|(_, i)| i.contains(id)).count();
                    if common.is_none_or(|(_, best)| count > best) {
                        common = Some((id, count));
                    }
                }
            }
            let kept: Vec<String> = members
                .iter()
                .filter(|(_, ids)| ids.is_empty() || common.is_some_and(|(id, _)| ids.contains(id)))
                .map(|(mid, _)| mid.clone())
                .collect();
            if kept.len() >= 2 {
                groups.push(kept);
            }
        }
    }
    groups
}

pub(crate) fn bundle_group_mids(desc: &SessionDescription) -> Vec<&str> {
    desc.attributes
        .iter()
        .filter(|a| a.key == ATTR_KEY_GROUP)
        .filter_map(|a| a.value.as_deref())
        .find_map(|value| {
            let mut tokens = value.split_whitespace();
            (tokens.next() == Some("BUNDLE")).then(|| tokens.collect())
        })
        .unwrap_or_default()
}

/// An m-section's ICE credentials: its own `a=ice-ufrag` / `a=ice-pwd`, else the session's
/// (RFC 8839 §5.4 allows both levels).
pub(crate) fn media_ice_credentials<'a>(
    desc: &'a SessionDescription,
    m: &'a MediaDescription,
) -> (Option<&'a str>, Option<&'a str>) {
    let ufrag = m
        .attribute("ice-ufrag")
        .flatten()
        .or_else(|| desc.attribute("ice-ufrag").map(String::as_str));
    let pwd = m
        .attribute("ice-pwd")
        .flatten()
        .or_else(|| desc.attribute("ice-pwd").map(String::as_str));
    (ufrag, pwd)
}

/// Checks ICE credentials against RFC 8839 §5.4: `ice-ufrag` is 4 to 256 ice-chars, `ice-pwd`
/// 22 to 256, an ice-char being ALPHA, DIGIT, "+" or "/" (RFC 8839 §5.1).
fn check_ice_credentials(ufrag: Option<&str>, pwd: Option<&str>) -> Result<()> {
    let valid = |value: &str, min: usize| {
        (min..=256).contains(&value.len())
            && value
                .bytes()
                .all(|b| b.is_ascii_alphanumeric() || b == b'+' || b == b'/')
    };
    if ufrag.is_some_and(|u| !valid(u, 4)) || pwd.is_some_and(|p| !valid(p, 22)) {
        return Err(Error::ErrSessionDescriptionInvalidIceCredentials);
    }
    Ok(())
}

/// Extracts the credentials and candidates of the ICE transport a remote description sets up.
///
/// This peer connection runs one ICE transport for every m-section, so the description has to
/// name one set of credentials:
///
/// - With a BUNDLE group, that is the offerer-tagged m-section's (the first mid of the group
///   that isn't rejected, RFC 8843 §7.2). The other m-sections of the group may carry their own
///   credentials (an offer under the `balanced` or `max-compat` policy does, JSEP RFC 8829
///   §5.2.1): their transports are discarded once BUNDLE is negotiated (RFC 8843 §7.3.3), so
///   their credentials and candidates aren't used.
/// - Every m-section outside the group must share those credentials; one that doesn't is
///   [`Error::ErrSessionDescriptionConflictingIceUfrag`] /
///   [`Error::ErrSessionDescriptionConflictingIcePwd`]. An inactive one is let through (its
///   credentials are the fallback when every m-section is inactive).
/// - Rejected m-sections set up no transport and are skipped.
///
/// Returns `Ok(None)` when there is no transport to set up: no m-section other than rejected
/// ones, and no session-level credentials (the description of a connection that has nothing to
/// negotiate yet, such as an offer created before any transceiver or data channel was added).
/// Why a remote `candidate` line that follows the grammar is to be ignored, rather than
/// refuse its description (RFC 8839 section 5.1): its address is a fully qualified domain
/// name ("An agent processing remote candidates MUST ignore "candidate" lines that include
/// candidates with FQDNs"; a host candidate's `<name>.local` is resolved by mDNS,
/// draft-ietf-mmusic-mdns-ice-candidates section 3.2.1, and a `.local` name of more than one
/// "." or on another candidate type is an FQDN like any other), or its transport or candidate type is one this agent does not know (both are
/// extensible tokens in the grammar). `None`: the line is parsed as usual, and a line that does
/// not follow the grammar still refuses the description.
pub(crate) fn ignored_candidate_line(value: &str) -> Option<&'static str> {
    let fields: Vec<&str> = value.split_ascii_whitespace().collect();
    if fields.len() < 8 {
        return None;
    }
    let (transport, address, typ) = (fields[2], fields[4], fields[7]);
    if !transport.eq_ignore_ascii_case("udp") && !transport.eq_ignore_ascii_case("tcp") {
        return Some("an unknown transport");
    }
    if !matches!(typ, "host" | "srflx" | "prflx" | "relay") {
        return Some("an unknown candidate type");
    }
    let is_ip = address.parse::<std::net::IpAddr>().is_ok();
    // draft-ietf-mmusic-mdns-ice-candidates section 3.2.1: only an address that ends with
    // ".local" and has no other "." is resolved by mDNS (step 1 sends the rest to RFC 8445
    // processing, where an FQDN is ignored), and only a host candidate carries one (section
    // 3.1.2.2 hides host addresses alone).
    let mdns_name = typ == "host"
        && address.to_ascii_lowercase().ends_with(".local")
        && address.matches('.').count() == 1;
    if !is_ip && !mdns_name {
        let fqdn = address.split('.').all(|label| {
            !label.is_empty()
                && label
                    .bytes()
                    .all(|b| b.is_ascii_alphanumeric() || b == b'-')
        });
        if fqdn {
            return Some("its address is a domain name (FQDN)");
        }
    }
    None
}

pub(crate) fn extract_ice_details(desc: &SessionDescription) -> Result<Option<RemoteIceDetails>> {
    let bundle = bundle_group_mids(desc);
    let bundle_set: HashSet<&str> = bundle.iter().copied().collect();
    let in_bundle = |m: &MediaDescription| {
        get_mid_value(m).is_some_and(|mid| bundle_set.contains(mid.as_str()))
    };
    // The first m-section that isn't rejected, for each mid: a lookup per bundle mid instead of
    // a scan of every m-section.
    let mut usable_by_mid: HashMap<&str, &MediaDescription> = HashMap::new();
    for m in &desc.media_descriptions {
        if let Some(mid) = get_mid_value(m)
            && !is_rejected_media(m)
        {
            usable_by_mid.entry(mid.as_str()).or_insert(m);
        }
    }
    let tagged = bundle
        .iter()
        .find_map(|mid| usable_by_mid.get(mid).copied());

    // Backup ufrag/pwd is the first inactive credentials found, for the corner case where all
    // media lines/transceivers are set to inactive.
    let mut backup_ufrag = None;
    let mut backup_pwd = None;

    let (mut remote_ufrag, mut remote_pwd) = match tagged {
        Some(m) => media_ice_credentials(desc, m),
        None => (
            desc.attribute("ice-ufrag").map(String::as_str),
            desc.attribute("ice-pwd").map(String::as_str),
        ),
    };

    let mut has_transport = remote_ufrag.is_some() || remote_pwd.is_some() || tagged.is_some();
    let mut transport_media = vec![];
    for m in &desc.media_descriptions {
        if is_rejected_media(m) {
            continue;
        }
        has_transport = true;
        let (ufrag, pwd) = media_ice_credentials(desc, m);
        check_ice_credentials(ufrag, pwd)?;

        if tagged.is_some() && in_bundle(m) {
            // Part of the tagged m-section's transport only when it says so with the same
            // credentials; otherwise its own transport, which BUNDLE replaces.
            if (ufrag.is_none() || ufrag == remote_ufrag) && (pwd.is_none() || pwd == remote_pwd) {
                transport_media.push(m);
            }
            continue;
        }

        if m.attribute(ATTR_KEY_INACTIVE).is_some() {
            if backup_ufrag.is_none() {
                backup_ufrag = ufrag;
            }
            if backup_pwd.is_none() {
                backup_pwd = pwd;
            }
            continue;
        }

        if remote_ufrag.is_none() {
            remote_ufrag = ufrag;
        }
        if remote_pwd.is_none() {
            remote_pwd = pwd;
        }

        if ufrag.is_some() && ufrag != remote_ufrag {
            return Err(Error::ErrSessionDescriptionConflictingIceUfrag);
        }
        if pwd.is_some() && pwd != remote_pwd {
            return Err(Error::ErrSessionDescriptionConflictingIcePwd);
        }
        transport_media.push(m);
    }

    if !has_transport {
        return Ok(None);
    }
    check_ice_credentials(remote_ufrag, remote_pwd)?;

    let remote_ufrag = remote_ufrag
        .or(backup_ufrag)
        .ok_or(Error::ErrSessionDescriptionMissingIceUfrag)?;
    let remote_pwd = remote_pwd
        .or(backup_pwd)
        .ok_or(Error::ErrSessionDescriptionMissingIcePwd)?;

    let mut candidates = vec![];
    for m in transport_media {
        for a in &m.attributes {
            if a.is_ice_candidate()
                && let Some(value) = &a.value
            {
                if let Some(reason) = ignored_candidate_line(value) {
                    log::warn!("ignoring remote candidate line {value:?}: {reason}");
                    continue;
                }
                candidates.push(unmarshal_candidate(value)?);
            }
        }
    }

    Ok(Some(RemoteIceDetails {
        ufrag: remote_ufrag.to_owned(),
        pwd: remote_pwd.to_owned(),
        candidates,
    }))
}

/// RFC 8839 section 4.4.2.1: "If any of the SDP attributes [`ice-options`, `ice-pacing`,
/// `ice-lite`] have been modified in a subsequent offer that is not used to request an ICE
/// restart, the answerer MUST reject the offer." `previous` is the current remote
/// description; `offer` keeps its ICE credentials (no restart). The attributes are read at
/// session level and in the first live section, where this engine and browsers write them.
pub(crate) fn check_ice_attributes_unchanged(
    previous: &SessionDescription,
    offer: &SessionDescription,
) -> Result<()> {
    fn of(desc: &SessionDescription) -> (bool, Vec<String>, Option<String>) {
        let first = desc
            .media_descriptions
            .iter()
            .find(|m| !is_rejected_media(m));
        let value = |key: &str| {
            desc.attribute(key)
                .map(String::as_str)
                .or_else(|| first.and_then(|m| m.attribute(key).flatten()))
                .map(str::to_owned)
        };
        let mut options: Vec<String> = value(ATTR_KEY_ICE_OPTIONS)
            .unwrap_or_default()
            .split_ascii_whitespace()
            .map(str::to_owned)
            .collect();
        options.sort();
        (is_lite_set(desc), options, value(ATTR_KEY_ICE_PACING))
    }
    let (before, after) = (of(previous), of(offer));
    if before != after {
        return Err(Error::SdpInvalidValue(format!(
            "an offer without an ICE restart changed ice-lite / ice-options / ice-pacing \
             ({before:?} to {after:?}; RFC 8839 section 4.4.2.1)"
        )));
    }
    Ok(())
}

pub(crate) fn is_lite_set(desc: &SessionDescription) -> bool {
    for a in &desc.attributes {
        if a.key.trim() == ATTR_KEY_ICELITE {
            return true;
        }
    }
    false
}

pub(crate) trait MediaDescriptionExt {
    /// Reports whether `self` is the WebRTC SCTP data channel m-line, as opposed to some
    /// other RTP-carried media that also uses the SDP media name `"application"`.
    fn is_webrtc_datachannel(&self) -> bool;
}

impl MediaDescriptionExt for MediaDescription {
    /// RFC 8841 section 4.4.2: media `application`, proto `UDP/DTLS/SCTP` or `TCP/DTLS/SCTP`,
    /// and the one fmt `webrtc-datachannel`; or the `DTLS/SCTP <sctp-port>` line with
    /// `a=sctpmap:<sctp-port> webrtc-datachannel` of the drafts before the RFC, which RFC 9429
    /// section 5.1.2 has a JSEP endpoint receive "for backwards compatibility"
    /// ([`is_legacy_data_section`]). Any other `m=application` line is not a data channel
    /// section.
    fn is_webrtc_datachannel(&self) -> bool {
        self.media_name.media == MEDIA_SECTION_APPLICATION
            && (self.media_name.formats == ["webrtc-datachannel"]
                && (self.media_name.protos == ["UDP", "DTLS", "SCTP"]
                    || self.media_name.protos == ["TCP", "DTLS", "SCTP"])
                || legacy_sctp_port(self).is_some())
    }
}

/// The SCTP port of a data section in the form of the drafts before RFC 8841: `m=application
/// <port> DTLS/SCTP <sctp-port>` with `a=sctpmap:<sctp-port> webrtc-datachannel <streams>`
/// (draft-ietf-mmusic-sctp-sdp-05). `None` for any other line.
pub(crate) fn legacy_sctp_port(media: &MediaDescription) -> Option<u16> {
    if media.media_name.media != MEDIA_SECTION_APPLICATION
        || media.media_name.protos != ["DTLS", "SCTP"]
    {
        return None;
    }
    let [format] = media.media_name.formats.as_slice() else {
        return None;
    };
    let port = format.parse::<u16>().ok()?;
    media
        .attributes
        .iter()
        .filter(|a| a.key == "sctpmap")
        .filter_map(|a| a.value.as_deref())
        .any(|value| {
            let mut fields = value.split_ascii_whitespace();
            fields.next() == Some(format.as_str()) && fields.next() == Some("webrtc-datachannel")
        })
        .then_some(port)
}

/// Turns this endpoint's data section `media` into the form of the drafts before RFC 8841,
/// the profile of an offer that used it (RFC 9429 section 5.3.1: the answer's profile "MUST
/// exactly match the profile provided in the offer"): `DTLS/SCTP <sctp-port>` with
/// `a=sctpmap:<sctp-port> webrtc-datachannel 65535` in place of `a=sctp-port`.
pub(crate) fn into_legacy_data_section(media: &mut MediaDescription) {
    let Some(port) = media
        .attributes
        .iter()
        .find(|a| a.key == "sctp-port")
        .and_then(|a| a.value.clone())
    else {
        return;
    };
    media.media_name.protos = vec!["DTLS".to_owned(), "SCTP".to_owned()];
    media.media_name.formats = vec![port.clone()];
    for attribute in &mut media.attributes {
        if attribute.key == "sctp-port" {
            attribute.key = "sctpmap".to_owned();
            attribute.value = Some(format!("{port} webrtc-datachannel 65535"));
        }
    }
}

/// Whether `media` is an `m=application` line that is neither a data channel section
/// (RFC 8841, or the drafts before it) nor application media over RTP, or an `m=audio` /
/// `m=video` line whose protocol is not RTP (RFC 8866 section 5.14: "the interpretation of
/// the media format depends on the value of the <proto> sub-field", so the formats of
/// `m=audio 9 udptl t38` are no payload types): a protocol this endpoint does not know. It is
/// answered like a media type this endpoint does not know, rejected with its own m= line, and
/// gets no transceiver. An audio or video section built in code without a protocol (every
/// parsed m= line has one) is read as RTP.
pub(crate) fn is_unknown_media_protocol(media_desc: &MediaDescription) -> bool {
    let rtp = media_desc
        .media_name
        .protos
        .iter()
        .any(|proto| proto == "RTP");
    match media_desc.media_name.media.as_str() {
        MEDIA_SECTION_APPLICATION => !media_desc.is_webrtc_datachannel() && !rtp,
        "audio" | "video" => !rtp && !media_desc.media_name.protos.is_empty(),
        _ => false,
    }
}

/// The `a=sctp-port` of a data channel section (RFC 8841 section 5): `Ok(None)` when the
/// attribute is absent, an error when its value is not `1*5(DIGIT)` in 0..=65535.
///
/// Leading zeroes are taken: section 5.2 forbids writing them, not reading them.
pub(crate) fn get_application_media_section_sctp_port(
    media_desc: &MediaDescription,
) -> Result<Option<u16>> {
    let Some(attribute) = media_desc
        .attributes
        .iter()
        .find(|attr| attr.key == "sctp-port")
    else {
        // The drafts before RFC 8841 name the port in the fmt and `a=sctpmap`.
        return Ok(legacy_sctp_port(media_desc));
    };
    let value = attribute.value.as_deref().unwrap_or_default();
    if value.is_empty() || value.len() > 5 || !value.bytes().all(|b| b.is_ascii_digit()) {
        return Err(Error::ErrSDPSctpPortInvalid);
    }
    value
        .parse::<u16>()
        .map(Some)
        .map_err(|_| Error::ErrSDPSctpPortInvalid)
}

/// RFC 9429 sections 5.2.3.2 and 5.3.3.1, `VoiceActivityDetection`: in each live audio
/// section of `d`, the comfort noise formats (`CN`, RFC 3389) are kept when `vad` is true and
/// removed with their lines otherwise, and Opus states `usedtx=1` or `usedtx=0` (RFC 7587
/// section 7: whether this endpoint wants DTX in what it receives). An answer (`offer` is the
/// remote offer) keeps silence suppression only where the offer's section of the same mid
/// indicated it: "if support for silence suppression was not indicated in the offer, ... the
/// answer MUST be generated as if VoiceActivityDetection was set to "false"", per codec.
pub(crate) fn apply_voice_activity_detection(
    d: &mut SessionDescription,
    vad: bool,
    offer: Option<&SessionDescription>,
) {
    fn payload_types(media: &MediaDescription, codec: &str) -> Vec<String> {
        media
            .attributes
            .iter()
            .filter(|a| a.key == "rtpmap")
            .filter_map(|a| a.value.as_deref())
            .filter_map(|value| {
                let (pt, encoding) = value.split_once(' ')?;
                let name = encoding.split('/').next()?;
                name.eq_ignore_ascii_case(codec).then(|| pt.to_owned())
            })
            .collect()
    }
    fn format_of(value: &str) -> &str {
        value.split_once(' ').map_or(value, |(format, _)| format)
    }
    fn fmtp_params(media: &MediaDescription, pt: &str) -> Option<String> {
        media
            .attributes
            .iter()
            .filter(|a| a.key == "fmtp")
            .filter_map(|a| a.value.as_deref())
            .find_map(|value| {
                let (format, params) = value.split_once(' ')?;
                (format == pt).then(|| params.to_owned())
            })
    }
    fn is_usedtx(parameter: &str) -> bool {
        parameter
            .split_once('=')
            .is_some_and(|(k, _)| k.trim().eq_ignore_ascii_case("usedtx"))
    }
    fn wants_dtx(params: &str) -> bool {
        params
            .split(';')
            .any(|p| is_usedtx(p.trim()) && p.split_once('=').is_some_and(|(_, v)| v.trim() == "1"))
    }
    for media in &mut d.media_descriptions {
        // A bundle-only section of an offer (port zero, RFC 9143 section 7.2) is an audio
        // section like the others; a rejected one is left as it is.
        if media.media_name.media != "audio" || is_rejected_media(media) {
            continue;
        }
        let offered = offer.and_then(|offer| {
            let mid = get_mid_value(media)?;
            offer
                .media_descriptions
                .iter()
                .find(|m| get_mid_value(m).is_some_and(|m| m == mid))
        });
        let offered_cn = offered.is_none_or(|o| !payload_types(o, "CN").is_empty());
        let offered_dtx = offered.is_none_or(|o| {
            payload_types(o, "opus")
                .iter()
                .any(|pt| fmtp_params(o, pt).is_some_and(|p| wants_dtx(&p)))
        });
        if !(vad && offered_cn) {
            let cn = payload_types(media, "CN");
            media.media_name.formats.retain(|f| !cn.contains(f));
            media.attributes.retain(|a| {
                !(matches!(a.key.as_str(), "rtpmap" | "fmtp" | "rtcp-fb")
                    && a.value
                        .as_deref()
                        .is_some_and(|v| cn.iter().any(|pt| format_of(v) == pt.as_str())))
            });
        }
        let usedtx = if vad && offered_dtx { "1" } else { "0" };
        for pt in payload_types(media, "opus") {
            let mut parameters: Vec<String> = fmtp_params(media, &pt)
                .unwrap_or_default()
                .split(';')
                .map(str::trim)
                .filter(|p| !p.is_empty() && !is_usedtx(p))
                .map(str::to_owned)
                .collect();
            parameters.push(format!("usedtx={usedtx}"));
            let value = format!("{pt} {}", parameters.join(";"));
            match media
                .attributes
                .iter_mut()
                .find(|a| a.key == "fmtp" && a.value.as_deref().is_some_and(|v| format_of(v) == pt))
            {
                Some(attribute) => attribute.value = Some(value),
                None => media
                    .attributes
                    .push(sdp::description::common::Attribute::new(
                        "fmtp".to_owned(),
                        Some(value),
                    )),
            }
        }
    }
}

/// RFC 9429 section 5.10: "If any RTX or FEC format ... is present, but the primary format it
/// is associated with is not present, an error MUST be returned": an `a=fmtp:<pt> apt=<x>` of a
/// live RTP section whose `x` is not one of the section's formats (RFC 4588 section 8.6).
/// A primary that is present but not supported is not an error: the RTX format is then
/// ignored (`MediaEngine::match_remote_codec`).
pub(crate) fn check_repair_primaries(desc: &SessionDescription) -> Result<()> {
    for media in &desc.media_descriptions {
        if is_rejected_media(media) || media.is_webrtc_datachannel() {
            continue;
        }
        let formats = &media.media_name.formats;
        for attribute in media.attributes.iter().filter(|a| a.key == "fmtp") {
            let Some(value) = attribute.value.as_deref() else {
                continue;
            };
            let Some((pt, parameters)) = value.split_once(' ') else {
                continue;
            };
            if !formats.iter().any(|f| f == pt) {
                continue;
            }
            for parameter in parameters.split(';') {
                if let Some((key, apt)) = parameter.trim().split_once('=')
                    && key.trim().eq_ignore_ascii_case("apt")
                    && !formats.iter().any(|f| f == apt.trim())
                {
                    return Err(Error::SdpInvalidValue(format!(
                        "a=fmtp:{value}: the associated payload type is not on the m= line \
                         (RFC 9429 section 5.10)"
                    )));
                }
            }
        }
    }
    Ok(())
}

/// Checks the data channel section of a remote description, if it has one that is not
/// rejected, and returns its `a=sctp-port`.
///
/// RFC 8841 section 5.1: "No default value is defined for the SDP 'sctp-port' attribute.
/// Therefore, if the attribute is not present, the associated 'm=' line MUST be considered
/// invalid." A description with such a line, or with a port that is not one, is refused; it
/// used to be taken with port 5000 assumed. A port of 0 is valid: it asks for no association
/// (section 9.3).
pub(crate) fn validate_application_media_section(desc: &SessionDescription) -> Result<()> {
    match get_application_media(desc) {
        Some(media) if !is_rejected_application_media(media) => {
            match get_application_media_section_sctp_port(media)? {
                Some(_) => Ok(()),
                None => Err(Error::ErrSDPSctpPortInvalid),
            }
        }
        _ => Ok(()),
    }
}

/// A data channel section with port zero and no `a=bundle-only`: rejected (RFC 3264 section
/// 6) or, in an offer, closed (RFC 8841 section 10.5). A zero port with `a=bundle-only` is a
/// bundled section of an offer, not a rejected one (RFC 9143 sections 7.2 and 13): every
/// section but the first of a `max-bundle` initial offer (RFC 9429 sections 5.2.1 and 7.2),
/// so the data section beside media. An answer never carries `a=bundle-only` (RFC 9429
/// section 5.3.1; a remote answer's is discarded, `discard_stray_bundle_only`), so a zero port
/// there is a rejection. 0.2.0 read the zero port alone and took the data section of such an
/// offer for a rejected one: no association, the channels failed.
fn is_rejected_application_media(media_desc: &MediaDescription) -> bool {
    is_rejected_media(media_desc)
}

/// What an offer/answer pair negotiated for the SCTP association (RFC 8841 section 10).
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub(crate) enum SctpNegotiation {
    /// One of the descriptions has no data channel section: nothing was negotiated about
    /// SCTP, and what exists stays as it is.
    NoSection,
    /// The data section is rejected, m= port zero in the offer or in the answer (sections
    /// 10.3, 10.4 and 10.5): no association is established, and one that exists is closed.
    Rejected,
    /// One side's `a=sctp-port` is zero (section 9.3): no association is established, and
    /// one that exists is closed; DTLS is not affected.
    PortZero,
    /// An association between these two SCTP ports, with the largest message the peer
    /// takes (0: any size).
    Association {
        local_port: u16,
        remote_port: u16,
        remote_max_message_size: u32,
    },
}

/// Reads [`SctpNegotiation`] off the two descriptions of a completed exchange.
pub(crate) fn negotiated_sctp(
    local: &SessionDescription,
    remote: &SessionDescription,
) -> SctpNegotiation {
    let (Some(local), Some(remote)) = (get_application_media(local), get_application_media(remote))
    else {
        return SctpNegotiation::NoSection;
    };
    if is_rejected_application_media(local) || is_rejected_application_media(remote) {
        return SctpNegotiation::Rejected;
    }
    // A local section always has the attribute, and a remote one was checked when the
    // description was applied; one without is no association either.
    let port = |media| {
        get_application_media_section_sctp_port(media)
            .ok()
            .flatten()
            .unwrap_or(0)
    };
    match (port(local), port(remote)) {
        (0, _) | (_, 0) => SctpNegotiation::PortZero,
        (local_port, remote_port) => SctpNegotiation::Association {
            local_port,
            remote_port,
            // RFC 8841 section 6.1: "If the SDP 'max-message-size' attribute is not present,
            // the default value is 64K."
            remote_max_message_size: get_application_media_section_max_message_size(remote)
                .unwrap_or(crate::peer_connection::configuration::setting_engine::SctpMaxMessageSize::DEFAULT_MESSAGE_SIZE),
        },
    }
}

/// The `a=max-message-size` of a data channel section (RFC 8841 section 6): the largest
/// message its sender takes, 0 for any size, `None` when absent (the default is then 64K).
/// A value above what 32 bits hold is as good as no limit; one that is not a number is taken
/// as absent, the smaller and so the safe reading.
pub(crate) fn get_application_media_section_max_message_size(
    media_desc: &MediaDescription,
) -> Option<u32> {
    if !media_desc.is_webrtc_datachannel() {
        return None;
    }
    let value = media_desc.attribute(ATTR_KEY_MAX_MESSAGE_SIZE)??;
    if value.is_empty() || !value.bytes().all(|b| b.is_ascii_digit()) {
        return None;
    }
    Some(value.parse::<u32>().unwrap_or(0))
}

pub(crate) fn get_by_mid<'a>(
    search_mid: &str,
    desc: &'a session_description::RTCSessionDescription,
) -> Option<&'a MediaDescription> {
    if let Some(parsed) = &desc.parsed {
        for m in &parsed.media_descriptions {
            if let Some(mid) = m.attribute(ATTR_KEY_MID).flatten()
                && mid == search_mid
            {
                return Some(m);
            }
        }
    }
    None
}

/// The data channel section of a description: the one in use if it has several (an offer
/// made after a data section was rejected carries the rejected one and a new one).
pub(crate) fn get_application_media(desc: &SessionDescription) -> Option<&MediaDescription> {
    let mut sections = desc
        .media_descriptions
        .iter()
        .filter(|media_description| media_description.is_webrtc_datachannel());
    let first = sections.next()?;
    if !is_rejected_application_media(first) {
        return Some(first);
    }
    sections
        .find(|media_description| !is_rejected_application_media(media_description))
        .or(Some(first))
}

/// have_data_channel return MediaDescription with MediaName equal application
pub(crate) fn have_data_channel(
    desc: &session_description::RTCSessionDescription,
) -> Option<&MediaDescription> {
    get_application_media(desc.parsed.as_ref()?)
}

const ATTR_KEY_RTCP_FB: &str = "rtcp-fb";

/// One feedback value of an `a=rtcp-fb` line, the payload type removed: the type (`nack`,
/// `ccm`, `ack`, `goog-remb`, ...) and everything after it as the parameter (`pli`, `fir`,
/// `ccfb`, `100` of `trr-int 100`). `None` for an empty value.
fn parse_rtcp_feedback(value: &str) -> Option<RTCPFeedback> {
    let mut tokens = value.split_whitespace();
    let typ = tokens.next()?.to_owned();
    Some(RTCPFeedback {
        typ,
        parameter: tokens.collect::<Vec<_>>().join(" "),
    })
}

/// The payload types the formats an answer adds after the offered ones take (RFC 9429
/// section 5.3.1), by (SFrame numbering, kind, the format's own payload type), worked out once
/// for the whole answer so that every section numbers a format alike. A format keeps its own
/// number unless the offer uses that number for another format anywhere (in a BUNDLE group one
/// payload type has one configuration, RFC 9143 section 9.1.1), or an earlier description of
/// the session gave it another format (RFC 3264 section 8.3.2: the mapping "MUST NOT change
/// for the duration of a session"); then it takes the next dynamic payload type no offered,
/// registered or SFrame format uses, no earlier description used and no format before it
/// took. A format with nothing left is not added.
fn answer_payload_types(
    media_engine: &MediaEngine,
    media_sections: &[MediaSection],
) -> HashMap<(bool, RtpCodecKind, u8), u8> {
    let mut offered: HashMap<u8, RTCRtpCodec> = HashMap::new();
    for codec in media_sections
        .iter()
        .filter_map(|m| m.offered_codecs.as_ref())
        .flatten()
    {
        offered
            .entry(codec.payload_type)
            .or_insert_with(|| codec.rtp_codec.clone());
    }
    let kinds = [RtpCodecKind::Audio, RtpCodecKind::Video];
    let candidates: Vec<(bool, RtpCodecKind, RTCRtpCodecParameters)> = kinds
        .iter()
        .flat_map(|&kind| {
            media_engine
                .registered_codecs_by_kind(kind)
                .iter()
                .cloned()
                .map(move |codec| (false, kind, codec))
        })
        .chain(kinds.iter().flat_map(|&kind| {
            media_engine
                .codecs_for_section(kind, true)
                .into_iter()
                .map(move |codec| (true, kind, codec))
        }))
        .collect();
    let mut taken: HashSet<u8> = offered.keys().copied().collect();
    taken.extend(candidates.iter().map(|(_, _, codec)| codec.payload_type));
    taken.extend(media_engine.sframe_payload_types.iter().copied());
    taken.extend(media_engine.payload_type_history.keys().copied());
    let mut free = (96..=127u8).filter(|pt| !taken.contains(pt));
    let mut numbers = HashMap::new();
    for (sframe, kind, codec) in candidates {
        let conflicting = offered.get(&codec.payload_type).is_some_and(|offered| {
            codec_parameters_fuzzy_search(offered, std::slice::from_ref(&codec)).1
                != CodecMatch::Exact
        }) || media_engine
            .payload_type_means_another_format(codec.payload_type, &codec);
        let number = if conflicting {
            // A number an earlier description already gave this very format, when the offer
            // does not use it for another one; else a new one.
            media_engine
                .payload_type_history
                .iter()
                .filter(|(pt, earlier)| {
                    !offered.contains_key(pt)
                        && crate::peer_connection::configuration::media_engine::is_same_codec(
                            earlier,
                            &codec.rtp_codec,
                        )
                })
                .map(|(pt, _)| *pt)
                .min()
                .or_else(|| free.next())
        } else {
            Some(codec.payload_type)
        };
        if let Some(number) = number {
            numbers.insert((sframe, kind, codec.payload_type), number);
        }
    }
    numbers
}

/// The formats of `codecs` (an answer's, in its order) that `offered` has
/// (`SettingEngineBuilder::with_answer_offered_formats_only`), matched as a remote description
/// is (`RTCRtpTransceiverInternal::match_remote_codecs`): an exact match, or a match by name
/// for a format whose parameters are not its configuration. A repair format stays only with
/// what it repairs: an RTX format when the offer has RTX and its `apt` names a kept format, a
/// RED format when the formats its fmtp line names are kept (or it names none), a FEC format
/// when a media format is kept.
fn offered_formats_only(
    codecs: Vec<RTCRtpCodecParameters>,
    offered: &[RTCRtpCodecParameters],
) -> Vec<RTCRtpCodecParameters> {
    use crate::peer_connection::configuration::media_engine::{
        has_symmetric_configuration, red_block_payload_types,
    };
    use crate::rtp_transceiver::rtp_sender::rtp_codec::parse_rtx_apt;
    let is_offered = |codec: &RTCRtpCodecParameters| match codec_parameters_search(
        &codec.rtp_codec,
        Some(codec.payload_type),
        offered,
    ) {
        (_, CodecMatch::Exact) => true,
        (found, CodecMatch::Partial) => {
            !has_symmetric_configuration(&codec.rtp_codec)
                || found.rtp_codec.sdp_fmtp_line.trim().is_empty()
        }
        (_, CodecMatch::None) => false,
    };
    let offer_has_rtx = offered
        .iter()
        .any(|codec| repair_family(&codec.rtp_codec) == "rtx");
    let mut kept: Vec<RTCRtpCodecParameters> = codecs
        .into_iter()
        .filter(|codec| repair_family(&codec.rtp_codec) == "rtx" || is_offered(codec))
        .collect();
    let media: HashSet<PayloadType> = kept
        .iter()
        .filter(|codec| repair_family(&codec.rtp_codec).is_empty())
        .map(|codec| codec.payload_type)
        .collect();
    kept.retain(|codec| match repair_family(&codec.rtp_codec) {
        "" => true,
        "red" => red_block_payload_types(&codec.rtp_codec.sdp_fmtp_line)
            .is_none_or(|blocks| blocks.iter().all(|block| media.contains(block))),
        "ulpfec" | "flexfec" => !media.is_empty(),
        _ => true,
    });
    // RTX: its `apt` names a kept primary (a media format, or a kept RED format).
    let primaries: HashSet<PayloadType> = kept
        .iter()
        .filter(|codec| repair_family(&codec.rtp_codec) != "rtx")
        .map(|codec| codec.payload_type)
        .collect();
    kept.retain(|codec| {
        repair_family(&codec.rtp_codec) != "rtx"
            || (offer_has_rtx
                && parse_rtx_apt(&codec.rtp_codec.sdp_fmtp_line)
                    .is_some_and(|apt| primaries.contains(&apt)))
    });
    kept
}

pub(crate) fn codecs_from_media_description(
    m: &MediaDescription,
) -> Result<Vec<RTCRtpCodecParameters>> {
    let codecs = m.codecs();
    // Feedback for the wildcard payload type applies to every format of the section (RFC 4585
    // section 4.2: "'*' ... indicates that the RTCP feedback attribute applies to all payload
    // types"); RFC 8888 section 6 has `ack ccfb` signalled only that way.
    let wildcard_feedback: Vec<RTCPFeedback> = m
        .attributes
        .iter()
        .filter(|a| a.key == ATTR_KEY_RTCP_FB)
        .filter_map(|a| a.value.as_deref())
        .filter_map(|value| value.strip_prefix("* "))
        .filter_map(parse_rtcp_feedback)
        .collect();
    // RFC 3611 section 5.1: `a=rtcp-xr:rcvr-rtt=<mode>` asks for receiver reference times,
    // what libwebrtc's `a=rtcp-fb:<pt> rrtr` asks for: taken as that feedback for each
    // format, marked as coming from here. A section whose `a=rtcp-xr` does not list it wants
    // no such blocks (section 5.1: "it SHOULD NOT send XR blocks other than those listed"),
    // whatever its `a=rtcp-fb` lines say.
    let rtcp_xr = media_rtcp_xr(m);
    // The `rcvr-rtt` format in full (`rcvr-rtt=<mode>[:<max size>]`): the mode and the
    // maximum block size reach the interceptor as the parameter of the `rrtr` entry (RFC 3611
    // section 5.1: DLRR blocks within the signalled maximum).
    let xr_rrtr = rtcp_xr
        .as_ref()
        .map(|formats| formats.iter().find(|f| is_rcvr_rtt(f)).cloned());

    let mut out = vec![];
    // A payload type listed more than once on the m= line describes one codec: keep its first
    // position and skip the repeats, so the output is at most one entry per payload type.
    let mut seen = [false; 256];
    for payload_str in &m.media_name.formats {
        let payload_type: PayloadType = payload_str.parse::<u8>()?;
        if std::mem::replace(&mut seen[payload_type as usize], true) {
            continue;
        }
        // RFC 5761 section 4: "RTP payload types in the range 64-95 MUST NOT be used" where
        // RTP and RTCP share a port, as they always do here. A format numbered so is one this
        // endpoint cannot receive or send: left out, like a format it does not know.
        if is_rtcp_conflicting_payload_type(payload_type) {
            continue;
        }
        // A payload type with no `a=rtpmap` (only `a=fmtp` / `a=rtcp-fb`
        // lines, or none) is RFC 3551's static assignment for audio, else a
        // format this description doesn't define: RFC 9429 section 5.3.1 and
        // 5.8 ignore a format the endpoint doesn't know, rather than
        // rejecting the whole description.
        let static_codec;
        let codec = match codecs.get(&payload_type).filter(|c| !c.name.is_empty()) {
            Some(codec) => codec,
            None => {
                let Some((name, clock_rate, channels)) =
                    static_payload_type(&m.media_name.media, payload_type)
                else {
                    continue;
                };
                let defined = codecs.get(&payload_type);
                static_codec = sdp::util::Codec {
                    payload_type,
                    name: name.to_owned(),
                    clock_rate,
                    encoding_parameters: channels.map(|n| n.to_string()).unwrap_or_default(),
                    fmtp: defined.map(|c| c.fmtp.clone()).unwrap_or_default(),
                    rtcp_feedback: defined.map(|c| c.rtcp_feedback.clone()).unwrap_or_default(),
                };
                &static_codec
            }
        };

        let channels = codec.encoding_parameters.parse::<u16>().unwrap_or(0);

        let mut feedback: Vec<RTCPFeedback> = codec
            .rtcp_feedback
            .iter()
            .filter_map(|raw| parse_rtcp_feedback(raw))
            .collect();
        // RFC 7728 section 9: a `*` line with `pause` applies "to all listed payload types
        // that do not have an explicit "pause" specification".
        let is_pause = |f: &RTCPFeedback| {
            f.typ == crate::rtp_transceiver::rtp_sender::TYPE_RTCP_FB_CCM
                && interceptor::PauseCapability::parse(&f.parameter).is_some()
        };
        let explicit_pause = feedback.iter().any(is_pause);
        for entry in &wildcard_feedback {
            if !feedback.contains(entry) && !(explicit_pause && is_pause(entry)) {
                feedback.push(entry.clone());
            }
        }
        match &xr_rrtr {
            Some(Some(format)) => feedback.push(RTCPFeedback {
                typ: interceptor::RTCP_FB_RRTR.to_owned(),
                parameter: format.clone(),
            }),
            Some(None) => feedback.retain(|f| f.typ != interceptor::RTCP_FB_RRTR),
            None => {}
        }
        // The other `xr-format`s of `a=rtcp-xr` (RFC 3611 section 5.1: `pkt-loss-rle`,
        // `stat-summary`, `voip-metrics`, ...): an `xr` entry each, the format in full as the
        // parameter, which the XR generator of the interceptor chain is driven by.
        for format in rtcp_xr.iter().flatten().filter(|f| !is_rcvr_rtt(f)) {
            let entry = RTCPFeedback {
                typ: RTCP_FB_XR.to_owned(),
                parameter: format.clone(),
            };
            if !feedback.contains(&entry) {
                feedback.push(entry);
            }
        }

        out.push(RTCRtpCodecParameters {
            rtp_codec: RTCRtpCodec {
                mime_type: m.media_name.media.clone() + "/" + codec.name.as_str(),
                clock_rate: codec.clock_rate,
                channels,
                sdp_fmtp_line: codec.fmtp.clone(),
                rtcp_feedback: feedback,
            },
            payload_type,
        })
    }

    Ok(out)
}

/// The m= line of a section whose media type this endpoint doesn't know (not audio or
/// video, or audio or video over a protocol that is not RTP), for a rejection that
/// reproduces it. An `m=application` line is reproduced too:
/// a data channel section keeps its proto (`TCP/DTLS/SCTP` stays that), and one that is not
/// a data channel section (the pre-RFC `DTLS/SCTP 5000` form, application media over RTP)
/// is not answered as if it had been one.
pub(crate) fn unknown_media_name(media: &MediaDescription) -> Option<MediaName> {
    let kind = media.media_name.media.as_str();
    if matches!(kind, "audio" | "video") && !is_unknown_media_protocol(media) {
        return None;
    }
    let mut name = media.media_name.clone();
    if name.formats.is_empty() {
        name.formats.push("0".to_owned());
    }
    Some(name)
}

/// RFC 3551 section 6's static payload types of a section of `media` (`audio`: Table 4,
/// `video`: Table 5): encoding name, clock rate and, where the table gives it, the number of
/// channels. RFC 3551 section 3: a static payload type means its encoding without an
/// `a=rtpmap` line. A type of the other media kind's table is not one of this section's.
fn static_payload_type(
    media: &str,
    payload_type: PayloadType,
) -> Option<(&'static str, u32, Option<u16>)> {
    let audio = match payload_type {
        0 => Some(("PCMU", 8000, None)),
        3 => Some(("GSM", 8000, None)),
        4 => Some(("G723", 8000, None)),
        5 => Some(("DVI4", 8000, None)),
        6 => Some(("DVI4", 16000, None)),
        7 => Some(("LPC", 8000, None)),
        8 => Some(("PCMA", 8000, None)),
        9 => Some(("G722", 8000, None)),
        10 => Some(("L16", 44100, Some(2))),
        11 => Some(("L16", 44100, None)),
        12 => Some(("QCELP", 8000, None)),
        13 => Some(("CN", 8000, None)),
        14 => Some(("MPA", 90000, None)),
        15 => Some(("G728", 8000, None)),
        16 => Some(("DVI4", 11025, None)),
        17 => Some(("DVI4", 22050, None)),
        18 => Some(("G729", 8000, None)),
        _ => None,
    };
    let video = match payload_type {
        25 => Some(("CelB", 90000, None)),
        26 => Some(("JPEG", 90000, None)),
        28 => Some(("nv", 90000, None)),
        31 => Some(("H261", 90000, None)),
        32 => Some(("MPV", 90000, None)),
        33 => Some(("MP2T", 90000, None)),
        34 => Some(("H263", 90000, None)),
        _ => None,
    };
    match media {
        "audio" => audio,
        "video" => video,
        _ => None,
    }
}

/// RFC 3551 section 3 with Tables 4 and 5: every static payload type is read without an
/// `a=rtpmap` line as its table's encoding, in a section of its media kind only.
#[test]
fn every_static_payload_type_of_rfc_3551_is_read_without_an_rtpmap() {
    let read = |media: &str, formats: &[&str]| {
        let mut m = MediaDescription::default();
        m.media_name.media = media.to_owned();
        m.media_name.formats = formats.iter().map(|f| (*f).to_owned()).collect();
        codecs_from_media_description(&m).unwrap()
    };
    let audio = read("audio", &["10", "14", "16", "34"]);
    let names: Vec<(&str, u32, u16)> = audio
        .iter()
        .map(|c| {
            (
                c.rtp_codec.mime_type.as_str(),
                c.rtp_codec.clock_rate,
                c.rtp_codec.channels,
            )
        })
        .collect();
    assert_eq!(
        names,
        [
            ("audio/L16", 44100, 2),
            ("audio/MPA", 90000, 0),
            ("audio/DVI4", 11025, 0)
        ],
        "34 is a video type"
    );
    let video = read("video", &["26", "31", "34", "0"]);
    let names: Vec<&str> = video
        .iter()
        .map(|c| c.rtp_codec.mime_type.as_str())
        .collect();
    assert_eq!(
        names,
        ["video/JPEG", "video/H261", "video/H263"],
        "0 is an audio type"
    );
}

/// RFC 3551 section 3: "the payload type codes below 96 MAY be ... bound dynamically", and
/// a static binding may be redefined: an `a=rtpmap` for a static number (0, PCMU) or an
/// unassigned one below 96 (35) gives the format it names, not the table's.
#[test]
fn an_rtpmap_rebinds_a_static_or_unassigned_payload_type_below_96() {
    let mut m = MediaDescription::default()
        .with_value_attribute("rtpmap".to_owned(), "0 opus/48000/2".to_owned())
        .with_value_attribute("rtpmap".to_owned(), "35 telephone-event/8000".to_owned());
    m.media_name.media = "audio".to_owned();
    m.media_name.formats = ["0", "35", "8"].map(str::to_owned).to_vec();
    let codecs = codecs_from_media_description(&m).unwrap();
    let read: Vec<(u8, &str, u32)> = codecs
        .iter()
        .map(|c| {
            (
                c.payload_type,
                c.rtp_codec.mime_type.as_str(),
                c.rtp_codec.clock_rate,
            )
        })
        .collect();
    assert_eq!(
        read,
        [
            (0, "audio/opus", 48000),
            (35, "audio/telephone-event", 8000),
            (8, "audio/PCMA", 8000)
        ]
    );
}

#[test]
fn codecs_from_media_description_reads_static_and_skips_undefined_payload_types() {
    let mut m = MediaDescription::default()
        .with_value_attribute("rtpmap".to_owned(), "111 opus/48000/2".to_owned());
    m.media_name.media = "audio".to_owned();
    m.media_name.formats = ["111", "103", "9", "0", "8"].map(str::to_owned).to_vec();

    let codecs = codecs_from_media_description(&m).unwrap();

    let payload_types: Vec<_> = codecs.iter().map(|c| c.payload_type).collect();
    assert_eq!(payload_types, [111, 9, 0, 8]);
    assert_eq!(codecs[1].rtp_codec.mime_type, "audio/G722");
    assert_eq!(codecs[2].rtp_codec.mime_type, "audio/PCMU");
    assert_eq!(codecs[2].rtp_codec.clock_rate, 8000);
}

/// RFC 3611 section 5.1: `rcvr-rtt=<mode>[:<max size>]` reaches the stream's feedback in
/// full, as the parameter of its `rrtr` entry, so that the XR generator can keep its DLRR
/// blocks within the maximum size.
#[test]
fn the_rcvr_rtt_format_is_passed_on_in_full() {
    for format in ["rcvr-rtt=all:1024", "rcvr-rtt=sender", "rcvr-rtt=all"] {
        let mut m = MediaDescription::default()
            .with_value_attribute("rtpmap".to_owned(), "96 VP8/90000".to_owned())
            .with_value_attribute(ATTR_KEY_RTCP_XR.to_owned(), format.to_owned());
        m.media_name.media = "video".to_owned();
        m.media_name.formats = vec!["96".to_owned()];
        let codecs = codecs_from_media_description(&m).unwrap();
        let rrtr: Vec<&str> = codecs[0]
            .rtp_codec
            .rtcp_feedback
            .iter()
            .filter(|f| f.typ == interceptor::RTCP_FB_RRTR)
            .map(|f| f.parameter.as_str())
            .collect();
        assert_eq!(rrtr, [format]);
    }
}

/// RFC 3611 section 5.1: the unilateral `xr-format`s of `a=rtcp-xr` become `xr` entries of
/// the stream's feedback, each with its format in full, beside `rrtr` for `rcvr-rtt`.
#[test]
fn unilateral_xr_formats_become_xr_feedback_entries() {
    let mut m = MediaDescription::default()
        .with_value_attribute("rtpmap".to_owned(), "96 VP8/90000".to_owned())
        .with_value_attribute(
            ATTR_KEY_RTCP_XR.to_owned(),
            "pkt-loss-rle=1024 rcvr-rtt=all stat-summary=loss,jitt".to_owned(),
        );
    m.media_name.media = "video".to_owned();
    m.media_name.formats = vec!["96".to_owned()];
    let codecs = codecs_from_media_description(&m).unwrap();
    let entries: Vec<(&str, &str)> = codecs[0]
        .rtp_codec
        .rtcp_feedback
        .iter()
        .map(|f| (f.typ.as_str(), f.parameter.as_str()))
        .collect();
    assert_eq!(
        entries,
        [
            (interceptor::RTCP_FB_RRTR, "rcvr-rtt=all"),
            (RTCP_FB_XR, "pkt-loss-rle=1024"),
            (RTCP_FB_XR, "stat-summary=loss,jitt"),
        ]
    );
}

#[test]
fn codecs_from_media_description_keeps_format_order_and_attributes() {
    let mut m = MediaDescription::default()
        .with_value_attribute("rtpmap".to_owned(), "97 rtx/90000".to_owned())
        .with_value_attribute("fmtp".to_owned(), "97 apt=96".to_owned())
        .with_value_attribute("rtpmap".to_owned(), "96 VP8/90000".to_owned())
        .with_value_attribute("rtcp-fb".to_owned(), "96 nack pli".to_owned())
        .with_value_attribute("rtcp-fb".to_owned(), "96 goog-remb".to_owned());
    m.media_name.media = "video".to_owned();
    // Payload type 0 is PCMU's static assignment and may come without an a=rtpmap line.
    m.media_name.formats = ["96", "0", "97"].map(str::to_owned).to_vec();

    let codecs = codecs_from_media_description(&m).unwrap();

    let payload_types: Vec<_> = codecs.iter().map(|c| c.payload_type).collect();
    assert_eq!(payload_types, [96, 97]);

    let vp8 = &codecs[0].rtp_codec;
    assert_eq!(vp8.mime_type, "video/VP8");
    assert_eq!(vp8.clock_rate, 90000);
    assert_eq!(vp8.rtcp_feedback.len(), 2);
    assert_eq!(vp8.rtcp_feedback[0].typ, "nack");
    assert_eq!(vp8.rtcp_feedback[0].parameter, "pli");
    assert_eq!(vp8.rtcp_feedback[1].typ, "goog-remb");
    assert_eq!(codecs[1].rtp_codec.sdp_fmtp_line, "apt=96");

    // A dynamic payload type with no a=rtpmap is left out, not an error.
    m.media_name.formats.push("98".to_owned());
    assert_eq!(codecs_from_media_description(&m).unwrap().len(), 2);
}

#[test]
fn get_rids_uses_each_layers_first_alternative_once() {
    let mut m = MediaDescription::default();
    for rid in ["foo", "bar", "1", "2"] {
        m = m.with_value_attribute(SDP_ATTRIBUTE_RID.to_owned(), format!("{rid} recv"));
    }
    let simulcast = m.clone().with_value_attribute(
        SDP_ATTRIBUTE_SIMULCAST.to_owned(),
        "recv foo,bar;1,2".to_owned(),
    );
    let ids: Vec<(String, bool)> = get_rids(&simulcast, RidIdGrammar::Corrected)
        .into_iter()
        .map(|r| (r.id, r.simulcast))
        .collect();
    // The first alternative of each stream is the stream; the others are dropped.
    assert_eq!(ids, [("foo".to_owned(), true), ("1".to_owned(), true)]);

    // A rid-id listed twice makes the line malformed (RFC 8853 section 5.2): it is not used.
    let repeated = m.with_value_attribute(
        SDP_ATTRIBUTE_SIMULCAST.to_owned(),
        "recv foo,bar;1,2;foo".to_owned(),
    );
    assert!(
        get_rids(&repeated, RidIdGrammar::Corrected)
            .iter()
            .all(|r| !r.simulcast)
    );
}

/// The extensions an offer adds back for a transceiver with an explicit list of header
/// extensions to negotiate (webrtc-extensions: a subsequent offer carries every extension of
/// `[[HeaderExtensionsToNegotiate]]` that isn't "stopped", not only the ones the last answer
/// kept): each listed URI the media engine registered for `kind` and `direction` that
/// `written` doesn't have yet, with the id it was negotiated with, or else the lowest one-byte
/// id (RFC 8285 section 4.2) that neither the negotiated set nor `written` uses.
pub(crate) fn reoffered_header_extensions(
    media_engine: &MediaEngine,
    kind: RtpCodecKind,
    direction: RTCRtpTransceiverDirection,
    uris: &[String],
    written: &[(u16, String)],
) -> Vec<(u16, String, bool)> {
    let mut out: Vec<(u16, String, bool)> = vec![];
    for uri in uris {
        if written.iter().any(|(_, u)| u == uri) || out.iter().any(|(_, u, _)| u == uri) {
            continue;
        }
        let registered = media_engine.header_extensions.iter().any(|e| {
            e.uri == *uri
                && e.is_matching_direction(direction)
                && (e.is_audio && kind == RtpCodecKind::Audio
                    || e.is_video && kind == RtpCodecKind::Video)
        });
        if !registered {
            continue;
        }
        let taken =
            |id: u16| written.iter().any(|(i, _)| *i == id) || out.iter().any(|(i, _, _)| *i == id);
        let negotiated = media_engine
            .negotiated_header_extensions
            .iter()
            .find(|(_, e)| e.uri == *uri)
            .map(|(id, e)| (*id, e.encrypted))
            .filter(|(id, _)| !taken(*id));
        let id = negotiated.or_else(|| {
            local_extension_ids()
                .find(|id| {
                    !taken(*id) && !media_engine.negotiated_header_extensions.contains_key(id)
                })
                .map(|id| (id, false))
        });
        if let Some((id, encrypted)) = id {
            out.push((id, uri.clone(), encrypted));
        }
    }
    out
}

/// The direction an `a=extmap` line states (RFC 8285 section 7), or `None` when the
/// extension is left out of the description.
///
/// - `registered`: the transceiver directions the extension was registered for
///   ([`MediaEngine::register_header_extension`]), `None` for all.
/// - `answered`: answering, the reverse of the direction the offer gave the extension
///   ([`answered_extension_directions`]), `None` when the offer gave none (it then has the
///   section's direction).
/// - `section`: the section's direction (an answer's, or the transceiver's in an offer).
///
/// An extension registered to send only or receive only says so, and is left out of a
/// section that does not go that way.
/// An answer to a restricted extension keeps the reversed direction when the registration
/// allows it, and otherwise drops the extension (RFC 8285 section 7: an answerer that does
/// not want to receive an extension offered sendonly, or cannot send one offered recvonly,
/// "SHOULD remove it from the SDP answer").
pub(crate) fn extension_direction(
    registered: Option<RTCRtpTransceiverDirection>,
    answered: Option<sdp::direction::Direction>,
    section: RTCRtpTransceiverDirection,
) -> Option<sdp::direction::Direction> {
    use sdp::direction::Direction;
    let registered = registered.filter(|r| {
        matches!(
            r,
            RTCRtpTransceiverDirection::Sendonly | RTCRtpTransceiverDirection::Recvonly
        )
    });
    match (answered, registered) {
        (Some(Direction::SendOnly), Some(RTCRtpTransceiverDirection::Recvonly))
        | (Some(Direction::RecvOnly), Some(RTCRtpTransceiverDirection::Sendonly)) => None,
        (Some(answered), _) => Some(answered),
        // RFC 6465 section 5: a client that does not mix "would hence have to always include
        // the direction parameter"; RFC 8285 section 7: "It is an error to use an extension
        // direction incompatible with the stream direction".
        (None, Some(RTCRtpTransceiverDirection::Sendonly)) => {
            section.has_send().then_some(Direction::SendOnly)
        }
        (None, Some(_)) => section.has_recv().then_some(Direction::RecvOnly),
        (None, None) => Some(Direction::Unspecified),
    }
}

#[test]
fn codecs_from_media_description_bounds_repeated_formats_and_feedback() {
    let mut m = MediaDescription::default()
        .with_value_attribute("rtpmap".to_owned(), "96 VP8/90000".to_owned());
    for _ in 0..20_000 {
        m = m.with_value_attribute("rtcp-fb".to_owned(), "96 nack".to_owned());
    }
    m.media_name.media = "video".to_owned();
    m.media_name.formats = vec!["96".to_owned(); 20_000];

    let codecs = codecs_from_media_description(&m).unwrap();

    assert_eq!(codecs.len(), 1);
    assert_eq!(codecs[0].payload_type, 96);
    assert_eq!(codecs[0].rtp_codec.rtcp_feedback.len(), 1);
    assert_eq!(codecs[0].rtp_codec.rtcp_feedback[0].typ, "nack");
}

/// The RFC 6904 URI that marks an `a=extmap` line as the encrypted form of the extension it
/// names next (`a=extmap:<id> urn:ietf:params:rtp-hdrext:encrypt <uri> [attributes]`).
pub(crate) const ENCRYPT_URI: &str = "urn:ietf:params:rtp-hdrext:encrypt";

/// One header extension mapping of a media section, as negotiation uses it.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct SectionExtension {
    /// The id (1 to 255, never 15).
    pub(crate) id: u16,
    /// The mapping is the encrypted form (RFC 6904 section 4).
    pub(crate) encrypted: bool,
    /// The extension attributes after the URI, if any (`vad=off`, RFC 6464 section 4).
    pub(crate) attributes: Option<String>,
    /// The direction the line gives the extension (RFC 8285 section 7), `Unspecified` for
    /// none.
    pub(crate) direction: sdp::direction::Direction,
}

/// Whether a section's transport protocol is an RTP/AVPF profile or one that inherits its
/// signalling (`RTP/AVPF`, `RTP/SAVPF`, `UDP/TLS/RTP/SAVPF`, `TCP/DTLS/RTP/SAVPF`): RFC 4585
/// section 4.1, feedback is used only under such a profile, and RFC 5506 section 4, reduced-size
/// RTCP only with AVPF's early or immediate feedback.
pub(crate) fn is_avpf_section(m: &MediaDescription) -> bool {
    m.media_name
        .protos
        .iter()
        .any(|p| p.eq_ignore_ascii_case("AVPF") || p.eq_ignore_ascii_case("SAVPF"))
}

/// Whether a section's transport protocol is an SRTP-based RTP profile (`RTP/SAVP`,
/// `RTP/SAVPF`, `UDP/TLS/RTP/SAVPF`, ...).
fn is_srtp_section(m: &MediaDescription) -> bool {
    m.media_name
        .protos
        .iter()
        .any(|p| p.eq_ignore_ascii_case("SAVP") || p.eq_ignore_ascii_case("SAVPF"))
}

/// The usable `a=extmap` lines of a section, in order, as (extension URI, mapping); several
/// lines may name one URI. Left out: what RFC 8285 does not let a packet carry (256, the
/// 4096 to 4351 range, and 15, which is reserved: "A usable mapping MUST use IDs in the valid
/// range", section 5), a URI that is not a URI (an extension the answerer does not
/// understand, RFC 8285 section 7, RFC 9429 section 5.10), and RFC 6904 lines that cannot
/// apply: on a section without an SRTP profile (RFC 6904 section 4: "it MUST be specified
/// only for media that use SRTP-based RTP profiles"), or encrypting the `encrypt` URI itself
/// ("MUST NOT be recursively applied to itself").
pub(crate) fn section_extmap_lines(
    m: &MediaDescription,
) -> Result<Vec<(String, SectionExtension)>> {
    let srtp = is_srtp_section(m);
    let mut out = vec![];
    for a in &m.attributes {
        if a.key != ATTR_KEY_EXT_MAP {
            continue;
        }
        let value = a.value.as_deref().unwrap_or("");
        let mut tokens = value.split_whitespace();
        let entry = tokens.next().unwrap_or("");
        let uri = tokens.next();
        if uri.is_some_and(|uri| Url::parse(uri).is_err()) {
            continue;
        }
        if entry
            .split('/')
            .next()
            .and_then(|id| id.parse::<u32>().ok())
            .is_some_and(|id| id == 15 || id == 256 || (4096..=4351).contains(&id))
        {
            continue;
        }
        let a_str = a.to_string();
        let e = ExtMap::unmarshal(&mut a_str.as_bytes())?;
        let Some(uri) = e.uri else {
            continue;
        };
        let (uri, encrypted, attributes) = if uri.as_str() == ENCRYPT_URI {
            let mut inner = e.ext_attr.as_deref().unwrap_or("").splitn(2, ' ');
            let Some(inner_uri) = inner.next().filter(|u| Url::parse(u).is_ok()) else {
                continue;
            };
            if !srtp || inner_uri == ENCRYPT_URI {
                continue;
            }
            (inner_uri.to_owned(), true, inner.next().map(str::to_owned))
        } else {
            (uri.to_string(), false, e.ext_attr.clone())
        };
        out.push((
            uri,
            SectionExtension {
                id: e.value,
                encrypted,
                attributes,
                direction: e.direction,
            },
        ));
    }
    Ok(out)
}

/// The header extensions a section maps, one mapping per URI: the encrypted form when the
/// section has both (RFC 6904 section 4.1: an answerer that understands header extension
/// encryption "SHOULD choose the encrypted form of the offered header extension element and
/// mark the unencrypted form 'inactive'"; [`superseded_clear_extensions`] gives the latter),
/// otherwise the first line for the URI.
pub(crate) fn rtp_extensions_from_media_description(
    m: &MediaDescription,
) -> Result<HashMap<String, SectionExtension>> {
    let mut out: HashMap<String, SectionExtension> = HashMap::new();
    for (uri, mapping) in section_extmap_lines(m)? {
        match out.get(&uri) {
            Some(current) if current.encrypted || !mapping.encrypted => {}
            _ => {
                out.insert(uri, mapping);
            }
        }
    }
    Ok(out)
}

/// The clear mappings of a section that [`rtp_extensions_from_media_description`] passed
/// over for the encrypted form of the same extension, as (id, URI): an answer marks them
/// `inactive` (RFC 6904 section 4.1).
pub(crate) fn superseded_clear_extensions(m: &MediaDescription) -> Result<Vec<(u16, String)>> {
    let chosen = rtp_extensions_from_media_description(m)?;
    Ok(section_extmap_lines(m)?
        .into_iter()
        .filter(|(uri, mapping)| !mapping.encrypted && chosen.get(uri).is_some_and(|c| c.encrypted))
        .map(|(uri, mapping)| (mapping.id, uri))
        .collect())
}

#[test]
fn rtp_extensions_from_media_description_reads_each_extmap_line() {
    let m = MediaDescription::default()
        .with_value_attribute("mid".to_owned(), "0".to_owned())
        .with_value_attribute(
            ATTR_KEY_EXT_MAP.to_owned(),
            "1 urn:ietf:params:rtp-hdrext:sdes:mid".to_owned(),
        )
        .with_value_attribute(
            ATTR_KEY_EXT_MAP.to_owned(),
            "3/recvonly urn:ietf:params:rtp-hdrext:ssrc-audio-level".to_owned(),
        );

    let extensions = rtp_extensions_from_media_description(&m).unwrap();

    assert_eq!(extensions.len(), 2);
    assert_eq!(extensions["urn:ietf:params:rtp-hdrext:sdes:mid"].id, 1);
    assert_eq!(
        extensions["urn:ietf:params:rtp-hdrext:ssrc-audio-level"].id,
        3
    );

    let malformed = MediaDescription::default()
        .with_value_attribute(ATTR_KEY_EXT_MAP.to_owned(), "not-a-number urn:x".to_owned());
    assert!(rtp_extensions_from_media_description(&malformed).is_err());

    // An unknown extension whose name isn't a URI is skipped, not an error.
    let bogus = MediaDescription::default()
        .with_value_attribute(ATTR_KEY_EXT_MAP.to_owned(), "2 bogus".to_owned())
        .with_value_attribute(
            ATTR_KEY_EXT_MAP.to_owned(),
            "16 urn:ietf:params:rtp-hdrext:sdes:mid".to_owned(),
        );
    let extensions = rtp_extensions_from_media_description(&bogus).unwrap();
    assert_eq!(extensions.len(), 1);
    assert_eq!(extensions["urn:ietf:params:rtp-hdrext:sdes:mid"].id, 16);
}

/// RFC 6904 section 4: an encrypted mapping applies only to media with an SRTP-based profile
/// ("it MUST be specified only for media that use SRTP-based RTP profiles"; a session-level
/// one "MUST be ignored for all other (non-SRTP or non-RTP) media"), never to the `encrypt`
/// URI itself ("MUST NOT be recursively applied to itself"), and is preferred to the clear
/// form of the same extension (section 4.1), which an answer marks inactive.
#[test]
fn encrypted_mappings_apply_to_srtp_media_only_and_are_preferred() {
    let section = |protos: &[&str], lines: &[&str]| {
        let mut m = MediaDescription::default();
        m.media_name.media = "audio".to_owned();
        m.media_name.protos = protos.iter().map(|p| (*p).to_owned()).collect();
        for line in lines {
            m = m.with_value_attribute(ATTR_KEY_EXT_MAP.to_owned(), (*line).to_owned());
        }
        m
    };
    let level = "urn:ietf:params:rtp-hdrext:ssrc-audio-level";
    let both = [
        "3 urn:ietf:params:rtp-hdrext:ssrc-audio-level",
        "4 urn:ietf:params:rtp-hdrext:encrypt urn:ietf:params:rtp-hdrext:ssrc-audio-level vad=off",
        "5 urn:ietf:params:rtp-hdrext:encrypt urn:ietf:params:rtp-hdrext:encrypt",
    ];

    let srtp = section(&["UDP", "TLS", "RTP", "SAVPF"], &both);
    let chosen = rtp_extensions_from_media_description(&srtp).unwrap();
    assert_eq!(
        chosen[level],
        SectionExtension {
            id: 4,
            encrypted: true,
            attributes: Some("vad=off".to_owned()),
            direction: sdp::direction::Direction::Unspecified,
        }
    );
    assert!(!chosen.contains_key(ENCRYPT_URI), "{chosen:?}");
    assert_eq!(
        superseded_clear_extensions(&srtp).unwrap(),
        vec![(3, level.to_owned())]
    );

    let plain = section(&["RTP", "AVPF"], &both);
    let chosen = rtp_extensions_from_media_description(&plain).unwrap();
    assert_eq!((chosen[level].id, chosen[level].encrypted), (3, false));
    assert!(superseded_clear_extensions(&plain).unwrap().is_empty());
}

#[test]
fn reoffered_header_extensions_adds_listed_extensions_back() {
    use crate::rtp_transceiver::rtp_sender::RTCRtpHeaderExtensionCapability;

    let mut media_engine = MediaEngine::default();
    for uri in [
        "urn:ietf:params:rtp-hdrext:sdes:mid",
        "urn:3gpp:video-orientation",
        "urn:ietf:params:rtp-hdrext:ssrc-audio-level",
    ] {
        let kind = if uri.ends_with("audio-level") {
            RtpCodecKind::Audio
        } else {
            RtpCodecKind::Video
        };
        media_engine
            .register_header_extension(
                RTCRtpHeaderExtensionCapability {
                    uri: uri.to_owned(),
                },
                kind,
                None,
            )
            .unwrap();
    }
    let listed = vec![
        "urn:ietf:params:rtp-hdrext:sdes:mid".to_owned(),
        "urn:3gpp:video-orientation".to_owned(),
        "urn:ietf:params:rtp-hdrext:ssrc-audio-level".to_owned(),
        "urn:example:unregistered".to_owned(),
    ];
    let written = vec![(1u16, "urn:ietf:params:rtp-hdrext:sdes:mid".to_owned())];
    let added = reoffered_header_extensions(
        &media_engine,
        RtpCodecKind::Video,
        RTCRtpTransceiverDirection::Sendrecv,
        &listed,
        &written,
    );
    // Only the registered video extension that isn't written yet, on a free id.
    assert_eq!(
        added,
        vec![(2u16, "urn:3gpp:video-orientation".to_owned(), false)]
    );
}

/// The `o=` line of a peer connection's descriptions (RFC 9429 section 5.2.1), drawn once
/// when the peer connection is built: `<sess-id>` from `random` (the crypto provider's, so a
/// seeded provider makes it the same in every run), 63 bits and "less than (2^63)-1";
/// `<sess-version>` the wall-clock time `since_unix_epoch` in seconds since 1900 (RFC 8866
/// section 5.2: "it is RECOMMENDED that a timestamp be used"), from which each later
/// description that differs counts up by one ([`update_sdp_origin`]).
pub(crate) fn jsep_origin(
    random: &dyn crypto::RTCRandom,
    since_unix_epoch: std::time::Duration,
) -> Origin {
    let mut bytes = [0u8; 8];
    let drawn = match random.fill(&mut bytes) {
        Ok(()) => u64::from_be_bytes(bytes),
        // The id needs uniqueness, not a particular source.
        Err(_) => rand::random(),
    };
    Origin::jsep(
        drawn % (u64::MAX >> 1),
        since_unix_epoch.as_secs() + NTP_UNIX_EPOCH_OFFSET_SECS,
    )
}

/// Gives a generated description the session's `o=` line (RFC 9429 sections 5.2.2 and 5.3.2:
/// "The 'o=' line MUST stay the same except for the <session-version> field, which MUST
/// increment by one on each call ... if the offer might differ from the output of the
/// previous call"; RFC 3264 section 8: "the version in the origin field MUST increment by one
/// from the previous SDP").
///
/// `origin` is the session's, drawn when the peer connection was built ([`jsep_origin`]). The
/// first description generated gets it as it is; each later one gets it with the version one
/// higher than the previous description's when it differs from it (`last_generated`, the
/// text of the previous one) and the same version when it is the same text. Offers and
/// answers are one sequence: they describe one session.
pub(crate) fn update_sdp_origin(
    origin: &mut Origin,
    last_generated: &mut String,
    d: &mut SessionDescription,
) {
    d.origin = origin.clone();
    let text = d.marshal();
    if last_generated.is_empty() || text == *last_generated {
        *last_generated = text;
        return;
    }
    origin.session_version = origin.session_version.incremented();
    d.origin.session_version = origin.session_version.clone();
    *last_generated = d.marshal();
}

/// Whether a received description has `a=extmap-allow-mixed`, at session level or in any
/// media section (RFC 8285 section 6: "This attribute can be used at the session level or the
/// media level"). An answer to it says so at session level.
pub(crate) fn is_ext_map_allow_mixed_set(
    remote_description: Option<&RTCSessionDescription>,
) -> bool {
    remote_description.is_some_and(|r| {
        r.parsed.as_ref().is_some_and(|parsed| {
            parsed.has_attribute(ATTR_KEY_EXTMAP_ALLOW_MIXED)
                || parsed
                    .media_descriptions
                    .iter()
                    .any(|m| m.has_attribute(ATTR_KEY_EXTMAP_ALLOW_MIXED))
        })
    })
}

/// Whether a description allows mixed one- and two-byte header extensions for one of its
/// sections: at session level, in the section, or, for a bundled section, in its BUNDLE
/// group's tagged section (RFC 8285 section 6: the attribute is of the IDENTICAL multiplexing
/// category, RFC 8859).
pub(crate) fn extmap_allow_mixed_in(desc: &SessionDescription, media: &MediaDescription) -> bool {
    desc.has_attribute(ATTR_KEY_EXTMAP_ALLOW_MIXED)
        || has_bundle_attribute(desc, media, ATTR_KEY_EXTMAP_ALLOW_MIXED)
}

/// Checks if the SDP indicates trickle ICE support.
///
/// Per RFC 8838 and RFC 9429 section 4.1.17, trickle ICE support is indicated by
/// the presence of "trickle" in space-separated "ice-options" attribute values
/// at either session level or media level.
///
/// # Parameters
///
/// * `desc` - The parsed SDP session description
///
/// # Returns
///
/// `true` if trickle ICE is supported, `false` otherwise
pub(crate) fn has_ice_trickle_option(desc: &SessionDescription) -> bool {
    // Check session-level ice-options attribute
    if let Some(value) = desc.attribute("ice-options")
        && value.split_whitespace().any(|opt| opt == "trickle")
    {
        return true;
    }

    // Check media-level ice-options attribute
    for media in &desc.media_descriptions {
        if let Some(Some(value)) = media.attribute("ice-options")
            && value.split_whitespace().any(|opt| opt == "trickle")
        {
            return true;
        }
    }

    false
}

#[cfg(test)]
mod fingerprint_tests {
    use super::*;
    use sdp::description::common::Attribute;
    use sdp::description::media::MediaDescription;

    /// With several `a=fingerprint` lines, the sha-256 one is used even when it is not the first.
    #[test]
    fn test_extract_fingerprints_puts_sha256_first() -> Result<()> {
        let s = SessionDescription {
            media_descriptions: vec![MediaDescription {
                attributes: vec![
                    Attribute {
                        key: "fingerprint".to_owned(),
                        value: Some(format!("sha-384 {}", ["AB"; 48].join(":"))),
                    },
                    Attribute {
                        key: "fingerprint".to_owned(),
                        value: Some(format!("sha-256 {}", ["CD"; 32].join(":"))),
                    },
                ],
                ..Default::default()
            }],
            ..Default::default()
        };
        let fingerprints = extract_fingerprints(&s)?;
        assert_eq!(fingerprints[0].algorithm, "sha-256");
        assert_eq!(fingerprints[0].value, ["CD"; 32].join(":"));
        assert_eq!(fingerprints.len(), 2);
        Ok(())
    }

    fn parse(sdp: &str) -> SessionDescription {
        let mut reader = std::io::Cursor::new(sdp.as_bytes());
        SessionDescription::unmarshal(&mut reader).expect("test SDP parses")
    }

    const HEAD: &str = "v=0\r\no=- 1 1 IN IP4 0.0.0.0\r\ns=-\r\nt=0 0\r\n";

    fn section(media: &str, mid: &str, port: u16, extra: &str) -> String {
        format!(
            "m={media} {port} UDP/TLS/RTP/SAVPF 96\r\nc=IN IP4 0.0.0.0\r\na=mid:{mid}\r\n{extra}"
        )
    }

    #[test]
    fn extract_ice_details_takes_the_bundle_tagged_sections_credentials() -> Result<()> {
        let a = "a=ice-ufrag:aaaa\r\na=ice-pwd:aaaaaaaaaaaaaaaaaaaaaaaa\r\n\
a=candidate:1 1 udp 1 10.0.0.1 1000 typ host\r\n";
        let b = "a=ice-ufrag:bbbb\r\na=ice-pwd:bbbbbbbbbbbbbbbbbbbbbbbb\r\n\
a=candidate:1 1 udp 1 10.0.0.2 2000 typ host\r\n";
        let s = parse(&format!(
            "{HEAD}a=group:BUNDLE 1 0\r\n{}{}",
            section("audio", "0", 9, a),
            section("video", "1", 9, b)
        ));
        let details = extract_ice_details(&s)?.expect("a transport");
        // The group's first mid tags the transport (RFC 8843 §7.2), whatever the m-line order.
        assert_eq!(details.ufrag, "bbbb");
        assert_eq!(details.candidates.len(), 1);
        assert_eq!(details.candidates[0].port(), 2000);

        // A tagged m-section that is rejected tags nothing; the next mid of the group does.
        let s = parse(&format!(
            "{HEAD}a=group:BUNDLE 1 0\r\n{}{}",
            section("audio", "0", 9, a),
            section("video", "1", 0, b)
        ));
        assert_eq!(extract_ice_details(&s)?.expect("a transport").ufrag, "aaaa");

        // Outside a BUNDLE group, one transport means one set of credentials.
        let s = parse(&format!(
            "{HEAD}{}{}",
            section("audio", "0", 9, a),
            section("video", "1", 9, b)
        ));
        assert_eq!(
            extract_ice_details(&s).unwrap_err(),
            Error::ErrSessionDescriptionConflictingIceUfrag
        );
        Ok(())
    }

    #[test]
    fn extract_ice_details_checks_the_credentials_syntax() {
        let with = |ufrag: &str, pwd: &str| {
            let extra = format!("a=ice-ufrag:{ufrag}\r\na=ice-pwd:{pwd}\r\n");
            extract_ice_details(&parse(&format!(
                "{HEAD}{}",
                section("audio", "0", 9, &extra)
            )))
        };
        assert!(with("ETEn", "OtSK0WpNtpUjkY4+86js7Z/l").is_ok());
        for (ufrag, pwd) in [
            ("E$En", "OtSK0WpNtpUjkY4+86js7Z/l"),
            ("ETEn", "OtSK$WpNtpUjkY4+86js7Z/l"),
            ("ETE", "OtSK0WpNtpUjkY4+86js7Z/l"),
            ("ETEn", "OtSK0WpNtpUjkY4+86js7"),
        ] {
            assert_eq!(
                with(ufrag, pwd).unwrap_err(),
                Error::ErrSessionDescriptionInvalidIceCredentials,
                "{ufrag} {pwd}"
            );
        }
    }

    #[test]
    fn extract_ice_details_is_none_without_a_transport() -> Result<()> {
        assert!(extract_ice_details(&parse(HEAD))?.is_none());
        let rejected = parse(&format!("{HEAD}{}", section("audio", "0", 0, "")));
        assert!(extract_ice_details(&rejected)?.is_none());
        // A section that is used still needs credentials.
        let bare = parse(&format!("{HEAD}{}", section("audio", "0", 9, "")));
        assert_eq!(
            extract_ice_details(&bare).unwrap_err(),
            Error::ErrSessionDescriptionMissingIceUfrag
        );
        // bundle-only m-sections have port 0 but aren't rejected (RFC 8843 §6).
        let bundle_only = parse(&format!(
            "{HEAD}a=group:BUNDLE 0\r\n{}",
            section("audio", "0", 0, "a=bundle-only\r\n")
        ));
        assert!(extract_ice_details(&bundle_only).is_err());
        Ok(())
    }

    #[test]
    fn extract_fingerprints_keeps_one_per_certificate_and_checks_levels() -> Result<()> {
        let a = ["AA"; 32].join(":");
        let b = ["BB"; 32].join(":");
        let two = format!("a=fingerprint:sha-256 {a}\r\na=fingerprint:sha-256 {b}\r\n");
        let s = parse(&format!(
            "{HEAD}{}{}",
            section("audio", "0", 9, &two),
            section("video", "1", 9, &two)
        ));
        let fingerprints = extract_fingerprints(&s)?;
        assert_eq!(
            fingerprints
                .iter()
                .map(|f| f.value.as_str())
                .collect::<Vec<_>>(),
            [a.as_str(), b.as_str()]
        );

        let s = parse(&format!(
            "{HEAD}{}{}",
            section("audio", "0", 9, &two),
            section("video", "1", 9, &format!("a=fingerprint:sha-256 {a}\r\n"))
        ));
        assert_eq!(
            extract_fingerprints(&s).unwrap_err(),
            Error::ErrSessionDescriptionConflictingFingerprints
        );
        Ok(())
    }

    /// RFC 8122 section 5: a session-level fingerprint "applies to all TLS sessions for which
    /// no media-level fingerprint attribute is defined": a media-level one overrides it, and a
    /// section without one takes the session's. The sections share one transport, so what is
    /// in force for each must be the same.
    #[test]
    fn a_media_level_fingerprint_overrides_the_session_level_one() -> Result<()> {
        let a = format!("a=fingerprint:sha-256 {}\r\n", ["AA"; 32].join(":"));
        let b = format!("a=fingerprint:sha-256 {}\r\n", ["BB"; 32].join(":"));
        let values = |sdp: String| -> Result<Vec<String>> {
            Ok(extract_fingerprints(&parse(&sdp))?
                .into_iter()
                .map(|f| f.value)
                .collect())
        };
        let aa = vec![["AA"; 32].join(":")];
        let bb = vec![["BB"; 32].join(":")];

        // Session level only: both sections take it.
        assert_eq!(
            values(format!(
                "{HEAD}{a}{}{}",
                section("audio", "0", 9, ""),
                section("video", "1", 9, "")
            ))?,
            aa
        );
        // Every section overrides the session-level value: that one applies to nothing.
        assert_eq!(
            values(format!(
                "{HEAD}{a}{}{}",
                section("audio", "0", 9, &b),
                section("video", "1", 9, &b)
            ))?,
            bb
        );
        // One section overrides it and the other takes it: two fingerprints for one transport.
        assert_eq!(
            extract_fingerprints(&parse(&format!(
                "{HEAD}{a}{}{}",
                section("audio", "0", 9, &b),
                section("video", "1", 9, "")
            )))
            .unwrap_err(),
            Error::ErrSessionDescriptionConflictingFingerprints
        );
        // A rejected section has no transport: what it carries is not compared.
        assert_eq!(
            values(format!(
                "{HEAD}{}{}",
                section("audio", "0", 0, &b),
                section("video", "1", 9, &a)
            ))?,
            aa
        );
        // With no fingerprint in force anywhere, the description has none.
        assert_eq!(
            extract_fingerprints(&parse(&format!("{HEAD}{}", section("audio", "0", 9, ""))))
                .unwrap_err(),
            Error::ErrSessionDescriptionNoFingerprint
        );
        Ok(())
    }

    const TLS_ID: &str = "abc3de65cddef001be82";

    /// RFC 8842 section 4: `tls-id-value = 20*255(ALPHA / DIGIT / "+" / "/" / "-" / "_")`.
    #[test]
    fn tls_id_syntax() {
        assert!(is_valid_tls_id(TLS_ID));
        assert!(is_valid_tls_id(&"a".repeat(255)));
        assert!(is_valid_tls_id("ABCxyz0123456789+/-_ABCxyz"));
        assert!(!is_valid_tls_id(&TLS_ID[1..]));
        assert!(!is_valid_tls_id(&"a".repeat(256)));
        assert!(!is_valid_tls_id(""));
        for other in ["=", " ", ".", ":", "\u{e9}"] {
            assert!(!is_valid_tls_id(&format!("{TLS_ID}{other}")), "{other:?}");
        }
    }

    /// The remote `tls-id` is the one of the transport's sections: media-level only, the same
    /// on every section that has it, not that of a rejected section.
    #[test]
    fn extract_tls_id_reads_the_transports_value() -> Result<()> {
        let line = |value: &str| format!("a=tls-id:{value}\r\n");
        let sdp = |audio: &str, video: &str| {
            parse(&format!(
                "{HEAD}{}{}",
                section("audio", "0", 9, audio),
                section("video", "1", 9, video)
            ))
        };
        assert_eq!(extract_tls_id(&sdp("", ""))?, None);
        assert_eq!(
            extract_tls_id(&sdp(&line(TLS_ID), ""))?.as_deref(),
            Some(TLS_ID)
        );
        assert_eq!(
            extract_tls_id(&sdp("", &line(TLS_ID)))?.as_deref(),
            Some(TLS_ID)
        );
        assert_eq!(
            extract_tls_id(&sdp(&line(TLS_ID), &line(TLS_ID)))?.as_deref(),
            Some(TLS_ID)
        );
        assert_eq!(
            extract_tls_id(&sdp(&line(TLS_ID), &line("abc3de65cddef001be83"))),
            Err(Error::ErrSessionDescriptionInvalidTlsId)
        );
        assert_eq!(
            extract_tls_id(&sdp(&line("tooshort"), "")),
            Err(Error::ErrSessionDescriptionInvalidTlsId)
        );
        assert_eq!(
            extract_tls_id(&sdp("a=tls-id\r\n", "")),
            Err(Error::ErrSessionDescriptionInvalidTlsId)
        );
        // A session-level attribute is not the media-level `tls-id`.
        assert_eq!(
            extract_tls_id(&parse(&format!(
                "{HEAD}{}{}",
                line(TLS_ID),
                section("audio", "0", 9, "")
            )))?,
            None
        );
        // A rejected section's value is not the transport's.
        let rejected = parse(&format!(
            "{HEAD}{}{}",
            section("audio", "0", 0, &line("abc3de65cddef001be83")),
            section("video", "1", 9, &line(TLS_ID))
        ));
        assert_eq!(extract_tls_id(&rejected)?.as_deref(), Some(TLS_ID));
        Ok(())
    }

    /// The DTLS attributes of a description are checked wherever they sit.
    #[test]
    fn validate_dtls_attributes_checks_every_level() {
        let good = format!("a=fingerprint:sha-256 {}\r\n", ["AA"; 32].join(":"));
        let sdp = |session: &str, audio: &str, video: &str| {
            parse(&format!(
                "{HEAD}{session}{}{}",
                section("audio", "0", 9, audio),
                section("video", "1", 0, video)
            ))
        };
        assert_eq!(validate_dtls_attributes(&sdp("", "", ""), false), Ok(()));
        assert_eq!(
            validate_dtls_attributes(&sdp(&good, &good, &good), false),
            Ok(())
        );
        let bad = "a=fingerprint:sha-256 AA:BB\r\n";
        for (session, audio, video) in [(bad, "", ""), ("", bad, ""), ("", "", bad)] {
            assert_eq!(
                validate_dtls_attributes(&sdp(session, audio, video), false),
                Err(Error::ErrSessionDescriptionInvalidFingerprint)
            );
        }
        assert_eq!(
            validate_dtls_attributes(&sdp("a=fingerprint\r\n", "", ""), false),
            Err(Error::ErrSessionDescriptionInvalidFingerprint)
        );
        let holdconn = "a=setup:holdconn\r\n";
        for (session, audio, video) in [(holdconn, "", ""), ("", holdconn, ""), ("", "", holdconn)]
        {
            assert_eq!(
                validate_dtls_attributes(&sdp(session, audio, video), false),
                Err(Error::ErrSessionDescriptionInvalidSetup)
            );
        }
        // Two transports (no BUNDLE group), each with its own association's `tls-id`: valid;
        // two sections of one BUNDLE group with different ones are not.
        let two = |group: &str| {
            parse(&format!(
                "{HEAD}{group}{}{}",
                section("audio", "0", 9, "a=tls-id:abc3de65cddef001be82\r\n"),
                section("video", "1", 9, "a=tls-id:abc3de65cddef001be83\r\n")
            ))
        };
        assert_eq!(validate_dtls_attributes(&two(""), false), Ok(()));
        assert_eq!(
            validate_dtls_attributes(&two("a=group:BUNDLE 0 1\r\n"), false),
            Err(Error::ErrSessionDescriptionInvalidTlsId)
        );
        for (audio, video) in [("a=tls-id:short\r\n", ""), ("", "a=tls-id:short\r\n")] {
            assert_eq!(
                validate_dtls_attributes(&sdp("", audio, video), false),
                Err(Error::ErrSessionDescriptionInvalidTlsId)
            );
        }
    }

    #[test]
    fn has_rtp_media_is_about_live_audio_and_video_sections() {
        let application = "m=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\n\
c=IN IP4 0.0.0.0\r\na=mid:2\r\n";
        assert!(!has_rtp_media(&parse(HEAD)));
        assert!(!has_rtp_media(&parse(&format!("{HEAD}{application}"))));
        assert!(!has_rtp_media(&parse(&format!(
            "{HEAD}{}{application}",
            section("audio", "0", 0, "")
        ))));
        assert!(has_rtp_media(&parse(&format!(
            "{HEAD}{application}{}",
            section("video", "1", 9, "")
        ))));
        assert!(has_rtp_media(&parse(&format!(
            "{HEAD}{}",
            section("audio", "0", 0, "a=bundle-only\r\n")
        ))));
    }

    #[test]
    fn insert_media_line_appends_to_the_section() {
        let sdp = "v=0\r\nm=audio 9 X 0\r\na=mid:0\r\nm=video 9 X 0\r\na=mid:1\r\n";
        assert_eq!(
            insert_media_line(sdp, 0, "end-of-candidates", None),
            "v=0\r\nm=audio 9 X 0\r\na=mid:0\r\na=end-of-candidates\r\nm=video 9 X 0\r\na=mid:1\r\n"
        );
        assert_eq!(
            insert_media_line(
                "v=0\nm=audio 9 X 0\na=mid:0",
                0,
                "candidate",
                Some("1 1 udp")
            ),
            "v=0\nm=audio 9 X 0\na=mid:0\na=candidate:1 1 udp\n"
        );
        assert_eq!(insert_media_line(sdp, 2, "x", None), sdp);
    }
}