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
#![allow(clippy::single_match)]
use combine::EasyParser;
use std::collections::HashMap;
use std::collections::HashSet;
use std::fmt::{self};
use std::ops::Deref;
use crate::crypto::Fingerprint;
use crate::format::Codec;
use crate::format::CodecSpec;
use crate::format::FormatParams;
use crate::format::PayloadParams;
use crate::packet::H265ProfileTierLevel;
use crate::rtp_::{Direction, Extension, Frequency, Mid, Pt, Rid, SessionId, Ssrc};
use crate::{Candidate, IceCreds, VERSION};
use str0m_proto::Id;
use super::SdpError;
use super::parser::sdp_parser;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Sdp {
pub session: Session,
pub media_lines: Vec<MediaLine>,
}
impl Sdp {
pub(crate) fn parse(input: &str) -> Result<Sdp, SdpError> {
sdp_parser()
.easy_parse(input)
.map(|(sdp, _)| sdp)
.map_err(|e| SdpError::ParseError(e.to_string()))
}
/// Get the MIDs listed in the BUNDLE group, if any.
pub(crate) fn bundle_mids(&self) -> Option<&[Mid]> {
self.session.attrs.iter().find_map(|a| {
if let SessionAttribute::Group { typ, mids } = a {
if typ == "BUNDLE" {
return Some(mids.as_slice());
}
}
None
})
}
pub(crate) fn assert_consistency(&self) -> Result<(), SdpError> {
match self.do_assert_consistency() {
None => Ok(()),
Some(error) => Err(SdpError::Inconsistent(error)),
}
}
pub(crate) fn fingerprint(&self) -> Option<Fingerprint> {
self.session
.fingerprint()
.or_else(|| self.media_lines.iter().find_map(|m| m.fingerprint()))
}
pub(crate) fn ice_creds(&self) -> Option<IceCreds> {
self.session
.ice_creds()
.or_else(|| self.media_lines.iter().find_map(|m| m.ice_creds()))
}
pub(crate) fn ice_candidates(&self) -> impl Iterator<Item = &Candidate> {
let mut candidates: HashSet<&Candidate> = HashSet::new();
// Session level ice candidates.
candidates.extend(self.session.ice_candidates());
// Ice candidates.
for m in &self.media_lines {
candidates.extend(m.ice_candidates());
}
candidates.into_iter()
}
/// Get the `a=sctp-init` value from the application m-line, if present.
///
/// Returns the base64-encoded SCTP INIT value.
pub(crate) fn sctp_init(&self) -> Option<&str> {
self.media_lines
.iter()
.find(|m| m.typ.is_channel())
.and_then(|m| m.sctp_init())
}
pub(crate) fn setup(&self) -> Option<Setup> {
self.session
.setup()
.or_else(|| self.media_lines.iter().find_map(|m| m.setup()))
}
fn do_assert_consistency(&self) -> Option<String> {
// TODO: SDP assertions we need to make:
// 1. Ensure that every m-line has the same PT configuration for a codec. I.e. if FIR is enabled
// for PT 96 in one m-line it must be in all m-lines.
// 2. Compare with previous m-lines that remote isn't narrowing/expanding PT and/or extmaps.
let group = self
.session
.attrs
.iter()
.find(|a| matches!(a, SessionAttribute::Group { .. }));
if let Some(SessionAttribute::Group { mids, .. }) = group {
if !mids.len() == self.media_lines.len() {
return Some(format!(
"a=group mid count doesn't match m-line count {} != {}",
mids.len(),
self.media_lines.len()
));
}
for (media, mid) in self.media_lines.iter().zip(mids.iter()) {
media.check_consistent()?;
let m = media.mid();
if m != *mid {
return Some(format!("Mid order not matching a=group {m} != {mid}"));
}
}
} else {
return Some("Session attribute a=group missing".into());
}
None
}
}
/// Session info, before the first m= line
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Session {
pub id: SessionId,
pub bw: Option<Bandwidth>,
pub attrs: Vec<SessionAttribute>,
}
/// Bandwidth from b= line
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Bandwidth {
pub typ: String,
pub val: String,
}
impl Session {
pub fn setup(&self) -> Option<Setup> {
let setup = self.attrs.iter().find_map(|m| {
if let SessionAttribute::Setup(v) = m {
Some(v)
} else {
None
}
})?;
Some(*setup)
}
pub fn ice_creds(&self) -> Option<IceCreds> {
let ufrag = self.attrs.iter().find_map(|m| {
if let SessionAttribute::IceUfrag(v) = m {
Some(v)
} else {
None
}
})?;
let pass = self.attrs.iter().find_map(|m| {
if let SessionAttribute::IcePwd(v) = m {
Some(v)
} else {
None
}
})?;
Some(IceCreds {
ufrag: ufrag.to_string(),
pass: pass.to_string(),
})
}
pub fn fingerprint(&self) -> Option<Fingerprint> {
for a in &self.attrs {
if let SessionAttribute::Fingerprint(v) = a {
return Some(v.clone());
}
}
None
}
pub fn ice_lite(&self) -> bool {
self.attrs
.iter()
.any(|a| matches!(a, SessionAttribute::IceLite))
}
pub fn ice_candidates(&self) -> impl Iterator<Item = &Candidate> {
self.attrs.iter().filter_map(|a| {
if let SessionAttribute::Candidate(v) = a {
Some(v)
} else {
None
}
})
}
pub fn end_of_candidates(&self) -> bool {
self.attrs
.iter()
.any(|a| matches!(a, SessionAttribute::EndOfCandidates))
}
}
/// Attributes before the first m= line.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SessionAttribute {
Group {
typ: String, // BUNDLE, LS etc
mids: Vec<Mid>, // 0 1 2 3
},
MsidSemantic {
semantic: String, // WMS
stream_ids: Vec<String>,
},
AllowMixedExts,
IceLite,
IceUfrag(String),
IcePwd(String),
IceOptions(String),
Fingerprint(Fingerprint),
Setup(Setup), // active, passive, actpass, holdconn
Candidate(Candidate),
EndOfCandidates,
Unused(String),
}
fn is_dir(a: &MediaAttribute) -> bool {
use MediaAttribute::*;
matches!(a, SendRecv | SendOnly | RecvOnly | Inactive)
}
/// An m-line
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct MediaLine {
pub typ: MediaType,
pub disabled: bool,
pub proto: Proto,
pub pts: Vec<Pt>, // payload types 96 97 125 107 from the m= line
pub bw: Option<Bandwidth>,
pub attrs: Vec<MediaAttribute>,
}
impl MediaLine {
pub fn mid(&self) -> Mid {
self.attrs
.iter()
.find_map(|a| {
if let MediaAttribute::Mid(m) = a {
Some(*m)
} else {
None
}
})
// We should only use `mid()` once we're certain there is
// a mid line. This is checked by `check_consistent`.
.expect("missing a=mid")
}
/// Get the sctp-init attribute value (base64-encoded string).
///
/// Returns `None` if no `a=sctp-init` attribute is present.
pub fn sctp_init(&self) -> Option<&str> {
self.attrs.iter().find_map(|a| {
if let MediaAttribute::SctpInit(v) = a {
Some(v.as_str())
} else {
None
}
})
}
pub fn msid(&self) -> Option<Msid> {
self.attrs.iter().find_map(|a| {
if let MediaAttribute::Msid(m) = a {
Some(m.clone())
} else {
None
}
})
}
pub fn direction(&self) -> Direction {
for a in &self.attrs {
match a {
MediaAttribute::SendRecv => return Direction::SendRecv,
MediaAttribute::SendOnly => return Direction::SendOnly,
MediaAttribute::RecvOnly => return Direction::RecvOnly,
MediaAttribute::Inactive => return Direction::Inactive,
_ => {}
}
}
// Should we error here?
Direction::Inactive
}
pub fn set_direction(&mut self, dir: Direction) {
let idx = self
.attrs
.iter()
.position(is_dir)
.expect("m-line must have direction");
self.attrs[idx] = dir.into();
}
pub fn rtp_params(&self) -> Vec<PayloadParams> {
let rtp_maps: Vec<_> = self
.attrs
.iter()
.filter_map(|a| {
if let MediaAttribute::RtpMap { pt, value: c } = a {
Some((*pt, *c))
} else {
None
}
})
.collect();
let fmtps: Vec<_> = self
.attrs
.iter()
.filter_map(|a| {
if let MediaAttribute::Fmtp { pt, values } = a {
Some((pt, values))
} else {
None
}
})
.collect();
let fbs: Vec<_> = self
.attrs
.iter()
.filter_map(|a| {
if let MediaAttribute::RtcpFb { pt, value } = a {
Some((pt, value))
} else {
None
}
})
.collect();
let mut params: Vec<_> = rtp_maps
.iter()
.filter(|(_, c)| c.codec.is_audio() | c.codec.is_video())
.map(|(pt, c)| PayloadParams::new(*pt, None, (*c).into()))
.collect();
for p in &mut params {
for (pt, values) in fmtps.iter() {
// find matching a=fmtp line, if it exists.
if **pt == p.pt {
for param in values.iter() {
p.spec.format.set_param(param);
}
}
// find resend pt, if there is one.
for fp in values.iter() {
if let FormatParam::Apt(v) = fp {
if *v == p.pt {
// ensure this is a rtx
let is_rtx = rtp_maps
.iter()
.any(|(cpt, c)| cpt == *pt && c.codec == Codec::Rtx);
if is_rtx {
p.resend = Some(**pt);
}
}
}
}
}
// rtcp feedback mechanisms
for (pt, value) in fbs.iter() {
if **pt == p.pt {
match &value[..] {
"goog-remb" => {
p.fb_remb = true;
}
"transport-cc" => {
p.fb_transport_cc = true;
}
"ccm fir" => {
p.fb_fir = true;
}
"nack" => {
p.fb_nack = true;
}
"nack pli" => {
p.fb_pli = true;
}
_ => {
//
}
}
}
}
}
params
}
pub fn check_consistent(&self) -> Option<String> {
use MediaAttribute::*;
let mid_count = self.attrs.iter().filter(|a| matches!(a, Mid(_))).count();
if mid_count == 0 {
return Some(format!(
"Media is missing a=mid: {} {}",
self.typ, self.proto
));
}
if mid_count > 1 {
return Some(format!(
"Media has more than one a=mid: {} {}",
self.typ, self.proto
));
}
let setup = self.attrs.iter().filter(|a| matches!(a, Setup(_))).count();
if setup > 1 {
return Some(format!(
"Expected 0 or 1 a=setup: line for mid: {}",
self.mid()
));
}
let dir_count = self.attrs.iter().filter(|a| is_dir(a)).count();
if self.proto == Proto::Srtp && dir_count != 1 {
return Some(format!(
"Expected exactly one of a=sendrecv, a=sendonly, a=recvonly, a=inactive for mid: {}",
self.mid()
));
}
if self.proto == Proto::Srtp && self.pts.is_empty() {
return Some(format!("Expected at least one PT for mid: {}", self.mid()));
}
for m in &self.pts {
let rtp_count = self
.attrs
.iter()
.filter(|a| {
if let MediaAttribute::RtpMap { pt, value: _ } = a {
pt == m
} else {
false
}
})
.count();
if rtp_count == 0 {
return Some(format!("Missing a=rtp_map:{} for mid: {}", m, self.mid()));
}
if rtp_count > 1 {
return Some(format!(
"More than one a=rtp_map:{} for mid: {}",
m,
self.mid()
));
}
}
None
}
pub fn setup(&self) -> Option<Setup> {
let setup = self.attrs.iter().find_map(|m| {
if let MediaAttribute::Setup(v) = m {
Some(v)
} else {
None
}
})?;
Some(*setup)
}
pub fn ice_creds(&self) -> Option<IceCreds> {
let ufrag = self.attrs.iter().find_map(|m| {
if let MediaAttribute::IceUfrag(v) = m {
Some(v)
} else {
None
}
})?;
let pass = self.attrs.iter().find_map(|m| {
if let MediaAttribute::IcePwd(v) = m {
Some(v)
} else {
None
}
})?;
Some(IceCreds {
ufrag: ufrag.to_string(),
pass: pass.to_string(),
})
}
pub fn fingerprint(&self) -> Option<Fingerprint> {
for a in &self.attrs {
if let MediaAttribute::Fingerprint(v) = a {
return Some(v.clone());
}
}
None
}
/// This hoovers the ice candidates from all m-lines, lots of dupes.
/// For WebRTC we don't expect different ice states per media line.
pub fn ice_candidates(&self) -> impl Iterator<Item = &Candidate> {
self.attrs.iter().filter_map(|a| {
if let MediaAttribute::Candidate(v) = a {
Some(v)
} else {
None
}
})
}
/// Any end-of-candidate in any m-line.
/// For WebRTC we don't expect different ice states per media line.
pub fn end_of_candidates(&self) -> bool {
self.attrs
.iter()
.any(|a| matches!(a, MediaAttribute::EndOfCandidates))
}
pub fn extmaps(&self) -> Vec<(u8, &Extension)> {
let mut ret = vec![];
for a in &self.attrs {
if let MediaAttribute::ExtMap { id, ext } = a {
ret.push((*id, ext));
}
}
ret
}
pub fn rids(&self) -> Vec<Rid> {
let mut ret = vec![];
for a in &self.attrs {
if let MediaAttribute::Rid { id, .. } = a {
ret.push(id.0.as_str().into())
}
}
ret
}
pub fn simulcast(&self) -> Option<Simulcast> {
let mut found = None;
for a in &self.attrs {
if let MediaAttribute::Simulcast(s) = a {
found = Some(s.clone());
}
if let MediaAttribute::Rid {
pt, restriction, ..
} = a
{
if !pt.is_empty() {
warn!("Not currently supporting PT via a=rid");
}
if !restriction.is_empty() {
warn!("Not currently supporting restrictions via a=rid");
}
}
}
if found.is_some() {
return found;
}
// Here we could handle munged SDPs and we used to, but we have dropped support for this.
None
}
pub fn ssrc_info(&self) -> Vec<SsrcInfo> {
let mut v = vec![];
fn by_ssrc(v: &mut Vec<SsrcInfo>, ssrc: Ssrc) -> &mut SsrcInfo {
if let Some(pos) = v.iter().position(|i| i.ssrc == ssrc) {
&mut v[pos]
} else {
v.push(SsrcInfo {
ssrc,
..Default::default()
});
v.last_mut().unwrap()
}
}
for a in &self.attrs {
match a {
MediaAttribute::Ssrc { ssrc, attr, value } => {
let info = by_ssrc(&mut v, *ssrc);
// a=ssrc:2147603131 cname:TbS1Ajv9obq6/63I
// a=ssrc:2147603131 msid:- 7a08dda6-518f-4027-b707-410a6d414176
match attr.to_lowercase().as_str() {
"cname" => info.cname = Some(value.clone()),
"msid" => {
let mut iter = value.split(' ');
fn trim_and_no_minus(s: &str) -> Option<String> {
let s = s.trim();
if s == "-" { None } else { Some(s.into()) }
}
if let Some(stream_id) = iter.next() {
info.stream_id = trim_and_no_minus(stream_id);
}
if let Some(track_id) = iter.next() {
info.track_id = trim_and_no_minus(track_id);
}
}
_ => {}
}
}
_ => {}
}
}
// Match this second to ensure we preserve order of a=ssrc.
for a in &self.attrs {
match a {
MediaAttribute::SsrcGroup { semantics, ssrcs } => {
if semantics.to_lowercase() != "fid" {
continue;
}
// a=ssrc-group:FID 659652645 98148385
// Should be two SSRC after FID.
if ssrcs.len() != 2 {
continue;
}
let info = by_ssrc(&mut v, ssrcs[1]);
info.repairs = Some(ssrcs[0]);
}
_ => {}
}
}
v
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SsrcInfo {
pub ssrc: Ssrc,
/// the other ssrc this ssrc is repairing
pub repairs: Option<Ssrc>,
pub cname: Option<String>,
pub stream_id: Option<String>,
pub track_id: Option<String>,
}
impl Default for SsrcInfo {
fn default() -> Self {
Self {
ssrc: 0.into(),
repairs: None,
cname: None,
stream_id: None,
track_id: None,
}
}
}
impl From<Direction> for MediaAttribute {
fn from(v: Direction) -> Self {
match v {
Direction::SendOnly => MediaAttribute::SendOnly,
Direction::RecvOnly => MediaAttribute::RecvOnly,
Direction::SendRecv => MediaAttribute::SendRecv,
Direction::Inactive => MediaAttribute::Inactive,
}
}
}
/// Identifier of an `a=rid` restriction.
///
/// Defined in https://tools.ietf.org/html/draft-ietf-avtext-rid-09
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RestrictionId(pub String, pub bool);
impl RestrictionId {
pub fn new(rid: String, active: bool) -> Self {
RestrictionId(rid, active)
}
pub fn new_active(rid: String) -> Self {
RestrictionId(rid, true)
}
pub fn to_sdp(&self) -> String {
format!("{}{}", if self.1 { "" } else { "~" }, self.0)
}
}
impl Default for RestrictionId {
fn default() -> Self {
RestrictionId("".to_string(), true)
}
}
/// "audio", "video", "application"
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub enum MediaType {
#[default]
Audio,
Video,
Application,
// If a parsed SDP has a value we don't recognize, we stick it
// in here. We could consider making that a parse exception instead.
#[doc(hidden)]
Unknown(String),
}
impl MediaType {
pub fn is_media(&self) -> bool {
matches!(self, MediaType::Audio | MediaType::Video)
}
pub fn is_channel(&self) -> bool {
matches!(self, MediaType::Application)
}
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum Proto {
#[default]
Srtp,
Sctp,
}
impl Proto {
pub fn proto_line(&self) -> &str {
match self {
Proto::Srtp => "UDP/TLS/RTP/SAVPF",
Proto::Sctp => "UDP/DTLS/SCTP",
}
}
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum Setup {
#[default]
ActPass,
Active,
Passive,
}
impl fmt::Display for Setup {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}",
match self {
Setup::ActPass => "actpass",
Setup::Active => "active",
Setup::Passive => "passive",
}
)
}
}
impl Setup {
pub fn setup_line(&self) -> &str {
match self {
Setup::ActPass => "actpass",
Setup::Active => "active",
Setup::Passive => "passive",
}
}
pub fn compare_to_remote(&self, remote: Setup) -> Option<Setup> {
use Setup::*;
match (self, remote) {
(ActPass, ActPass) => None,
(ActPass, Active) => Some(Passive),
(ActPass, Passive) => Some(Active),
(Active, ActPass) => Some(Active),
(Active, Active) => None,
(Active, Passive) => Some(Active),
(Passive, ActPass) => Some(Passive),
(Passive, Active) => Some(Passive),
(Passive, Passive) => None,
}
}
pub fn invert(&self) -> Setup {
match self {
Setup::ActPass => Setup::ActPass,
Setup::Active => Setup::Passive,
Setup::Passive => Setup::Active,
}
}
}
/// Attributes before the first m= line.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MediaAttribute {
// The "a=rtcp" line MUST NOT be added if the most recent answer included an "a=rtcp-mux" line.
Rtcp(String),
IceUfrag(String),
IcePwd(String),
IceOptions(String),
Fingerprint(Fingerprint),
Setup(Setup), // active, passive, actpass, holdconn
Mid(Mid), // 0, 1, 2
SctpPort(u16),
MaxMessageSize(usize),
/// a=sctp-init:<base64-encoded SCTP INIT chunk>
/// See draft-hancke-tsvwg-snap
SctpInit(String),
// a=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level
// a=extmap:2 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time
ExtMap {
id: u8, // 1-14 inclusive,
ext: Extension,
},
RecvOnly, // a=recvonly
SendRecv, // a=sendrecv
SendOnly, // a=sendonly
Inactive, // a=inactive
// a=msid:5UUdwiuY7OML2EkQtF38pJtNP5v7In1LhjEK f78dde68-7055-4e20-bb37-433803dd1ed1
// a=msid:- 78dde68-7055-4e20-bb37-433803dd1ed1
Msid(Msid),
RtcpMux, //
RtcpMuxOnly, // only in offer, answer with a=rtcp-mux
// reduced size rtcp. remove this if not supported.
RtcpRsize,
Candidate(Candidate),
EndOfCandidates,
RtpMap {
pt: Pt,
value: RtpMap,
},
// rtcp-fb RTCP feedback parameters, repeated
RtcpFb {
pt: Pt, // 111
value: String, // nack, nack pli, ccm fir...
},
// format parameters, seems to be one of these
Fmtp {
pt: Pt, // 111
values: Vec<FormatParam>, // minptime=10;useinbandfec=1
},
// a=rid:<rid-id> <direction> [pt=<fmt-list>;]<restriction>=<value>
// a=rid:hi send pt=111,112;max-br=64000;max-height=360
// https://tools.ietf.org/html/draft-ietf-mmusic-rid-15
Rid {
id: RestrictionId, //
direction: &'static str, // send or recv
// No pt means the rid applies to all
pt: Vec<Pt>, // 111, 112 (rtpmap no)
restriction: Vec<(String, String)>,
},
// a=rid:hi send
// a=rid:lo send
// a=simulcast:send hi;lo
// https://tools.ietf.org/html/draft-ietf-mmusic-sdp-simulcast-14
// a=simulcast:<send/recv> <alt A>;<alt B>,<or C> <send/recv> [same]
Simulcast(Simulcast),
SsrcGroup {
semantics: String, // i.e. "FID"
ssrcs: Vec<Ssrc>, // <normal stream> <repair stream>
},
Ssrc {
ssrc: Ssrc, // synchronization source id
attr: String,
value: String,
},
Unused(String),
}
impl MediaAttribute {
pub fn is_direction(&self) -> bool {
use MediaAttribute::*;
matches!(self, RecvOnly | SendRecv | SendOnly | Inactive)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FormatParam {
/// The minimum duration of media represented by a packet.
///
/// Default 3. Max 120.
MinPTime(u8),
/// Specifies that the decoder can do Opus in-band FEC
UseInbandFec(bool),
/// Specifies that the decoder can do Opus DTX
UseDtx(bool),
/// Whether h264 sending media encoded at a different level in the offerer-to-answerer
/// direction than the level in the answerer-to-offerer direction, is allowed.
LevelAsymmetryAllowed(bool),
/// What h264 packetization mode is used.
///
/// * 0 - single nal.
/// * 1 - STAP-A, FU-A is allowed. Non-interleaved.
PacketizationMode(u8),
/// H264 profile level.
///
/// * 42 00 1f - 4200=baseline (B) 1f=level 3.1
/// * 42 e0 1f - 42e0=constrained baseline (CB) 1f=level 3.1
/// * 4d 00 1f - 4d00=main (M) 1f=level 3.1
/// * 64 00 1f - 6400=high (H) 1f=level 3.1
ProfileLevelId(u32),
/// VP9 profile id
ProfileId(u32),
/// AV1 profile
Profile(u8),
/// AV1 level-idx
LevelIdx(u8),
/// AV1 tier
Tier(u8),
/// H.265/HEVC profile, tier, and level.
H265ProfileTierLevel(crate::packet::H265ProfileTierLevel),
/// H.265 sprop-max-don-diff parameter (RFC 7798 §7.1).
/// When > 0, DONL fields are included in RTP packets to support
/// out-of-order NAL unit decoding. Valid range: 0–32767.
SpropMaxDonDiff(u16),
/// RTX (resend) codecs, which PT it concerns.
Apt(Pt),
/// Unrecognized fmtp.
Unknown,
}
impl FormatParam {
pub fn parse(k: &str, v: &str) -> Self {
use FormatParam::*;
match k {
"minptime" => v.parse().map(MinPTime).ok(),
"useinbandfec" => Some(UseInbandFec(v == "1")),
"usedtx" => Some(UseDtx(v == "1")),
"level-asymmetry-allowed" => Some(LevelAsymmetryAllowed(v == "1")),
"packetization-mode" => v.parse().map(PacketizationMode).ok(),
"profile-level-id" => u32::from_str_radix(v, 16)
.or_else(|_| v.parse())
.map(ProfileLevelId)
.ok(),
"profile-id" => v.parse().map(ProfileId).ok(),
"profile" => v.parse().map(Profile).ok(),
"level-idx" => v.parse().map(LevelIdx).ok(),
"tier" => v.parse().map(Tier).ok(),
"sprop-max-don-diff" => v
.parse::<u16>()
.ok()
.filter(|&v| v <= 32767)
.map(SpropMaxDonDiff),
"apt" => v.parse::<u8>().map(|v| Apt(Pt::from(v))).ok(),
_ => None,
}
.unwrap_or_else(|| {
trace!("Failed to parse FormatParam: {k}={v}");
Unknown
})
}
/// Parse multiple format parameters from key-value pairs.
/// Handles H.265 special case where three params combine into one composite.
pub fn parse_pairs(pairs: Vec<(String, String)>) -> Vec<FormatParam> {
// Check if this looks like H.265 by presence of tier-flag or level-id.
let is_h265 = pairs
.iter()
.any(|(k, _)| k == "tier-flag" || k == "level-id");
if is_h265 {
// For H.265, build composite ProfileTierLevel.
let map: HashMap<String, String> = pairs.into_iter().collect();
let mut result = vec![];
if let Some(ptl) = H265ProfileTierLevel::from_fmtp(&map) {
result.push(FormatParam::H265ProfileTierLevel(ptl));
}
// Include non-H.265-PTL parameters.
for (k, v) in map.iter() {
if k != "profile-id" && k != "tier-flag" && k != "level-id" {
result.push(FormatParam::parse(k, v));
}
}
result
} else {
// Standard parsing for non-H.265 codecs.
pairs
.into_iter()
.map(|(k, v)| FormatParam::parse(&k, &v))
.collect()
}
}
}
impl fmt::Display for FormatParam {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use FormatParam::*;
match self {
MinPTime(v) => write!(f, "minptime={v}"),
UseInbandFec(v) => write!(f, "useinbandfec={}", i32::from(*v)),
UseDtx(v) => write!(f, "usedtx={}", i32::from(*v)),
LevelAsymmetryAllowed(v) => {
write!(f, "level-asymmetry-allowed={}", i32::from(*v))
}
PacketizationMode(v) => write!(f, "packetization-mode={}", *v),
ProfileLevelId(v) => write!(f, "profile-level-id={:06x}", *v),
ProfileId(v) => write!(f, "profile-id={}", *v),
Profile(v) => write!(f, "profile={}", v),
LevelIdx(v) => write!(f, "level-idx={}", *v),
Tier(v) => write!(f, "tier={}", v),
H265ProfileTierLevel(ptl) => {
write!(
f,
"profile-id={};tier-flag={};level-id={}",
ptl.profile_id(),
ptl.tier_flag(),
ptl.level_id()
)
}
SpropMaxDonDiff(v) => write!(f, "sprop-max-don-diff={}", *v),
Apt(v) => write!(f, "apt={v}"),
Unknown => Ok(()),
}
}
}
impl PayloadParams {
pub(crate) fn as_media_attrs(&self, attrs: &mut Vec<MediaAttribute>) {
attrs.push(MediaAttribute::RtpMap {
pt: self.pt,
value: self.spec.into(),
});
if self.fb_transport_cc {
attrs.push(MediaAttribute::RtcpFb {
pt: self.pt,
value: "transport-cc".into(),
});
}
if self.fb_remb {
attrs.push(MediaAttribute::RtcpFb {
pt: self.pt,
value: "goog-remb".into(),
});
}
if self.fb_fir {
attrs.push(MediaAttribute::RtcpFb {
pt: self.pt,
value: "ccm fir".into(),
});
}
if self.fb_nack {
attrs.push(MediaAttribute::RtcpFb {
pt: self.pt,
value: "nack".into(),
});
}
if self.fb_pli {
attrs.push(MediaAttribute::RtcpFb {
pt: self.pt,
value: "nack pli".into(),
});
}
let fmtps = self.spec.format.to_format_param();
if !fmtps.is_empty() {
attrs.push(MediaAttribute::Fmtp {
pt: self.pt,
values: fmtps,
});
}
if let Some(pt) = self.resend {
attrs.push(MediaAttribute::RtpMap {
pt,
value: RtpMap {
codec: Codec::Rtx,
clock_rate: self.spec.clock_rate,
channels: None,
},
});
attrs.push(MediaAttribute::Fmtp {
pt,
values: vec![FormatParam::Apt(self.pt)],
});
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RtpMap {
pub codec: Codec,
pub clock_rate: Frequency,
pub channels: Option<u8>,
}
impl From<RtpMap> for CodecSpec {
fn from(v: RtpMap) -> Self {
CodecSpec {
codec: v.codec,
clock_rate: v.clock_rate,
channels: v.channels,
format: FormatParams::default(),
}
}
}
impl From<CodecSpec> for RtpMap {
fn from(v: CodecSpec) -> Self {
RtpMap {
codec: v.codec,
clock_rate: v.clock_rate,
channels: v.channels,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Simulcast {
pub send: SimulcastGroups,
pub recv: SimulcastGroups,
/// If this is created synthetically for a munged SDP.
pub is_munged: bool,
}
impl Simulcast {
pub fn invert(self) -> Self {
Simulcast {
send: self.recv,
recv: self.send,
is_munged: self.is_munged,
}
}
}
/// RID organization inside a=simulcast line.
///
/// `a=simulcast send 2;3,4` would result in
/// `SimulcastGroups(vec![SimulcastLayer("2"), SimulcastLayer("3")])`
///
/// The choice between 3 and 4 for the rid is currently ignored and the first option is always
/// selected.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SimulcastGroups(pub Vec<SimulcastLayer>);
/// Represents a simulcast layer in a group
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SimulcastLayer {
/// The layer's rid
pub restriction_id: RestrictionId,
/// Optional attributes per RFC 8851
pub attributes: Option<Vec<(String, String)>>,
}
impl Deref for SimulcastGroups {
type Target = [SimulcastLayer];
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Msid {
pub stream_id: String,
pub track_id: String,
}
impl Msid {
pub fn random() -> Self {
Msid {
stream_id: Id::<30>::random().to_string(),
track_id: Id::<30>::random().to_string(),
}
}
}
impl fmt::Display for SimulcastGroups {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for (idx, layer) in self.0.iter().enumerate() {
if idx + 1 == self.0.len() {
write!(f, "{}", layer.restriction_id.to_sdp())?;
} else {
write!(f, "{};", layer.restriction_id.to_sdp())?;
}
}
Ok(())
}
}
impl fmt::Display for Sdp {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.session)?;
for m in &self.media_lines {
write!(f, "{m}")?;
}
Ok(())
}
}
impl fmt::Display for Session {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "v=0\r\n")?;
write!(f, "o=str0m-{} {} 2 IN IP4 0.0.0.0\r\n", VERSION, self.id)?;
write!(f, "s=-\r\n")?;
if let Some(bw) = &self.bw {
write!(f, "b={}:{}\r\n", bw.typ, bw.val)?;
}
write!(f, "t=0 0\r\n")?;
for a in &self.attrs {
write!(f, "{a}")?;
}
Ok(())
}
}
impl fmt::Display for SessionAttribute {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use SessionAttribute::*;
match self {
Group { typ, mids } => {
let mids: Vec<_> = mids.iter().map(|m| m.to_string()).collect();
write!(f, "a=group:{} {}\r\n", typ, mids.join(" "))?;
}
AllowMixedExts => write!(f, "a=extmap-allow-mixed\r\n")?,
MsidSemantic {
semantic,
stream_ids,
} => {
write!(
f,
"a=msid-semantic: {} {}\r\n",
semantic,
stream_ids.join(" ")
)?;
}
IceLite => write!(f, "a=ice-lite\r\n")?,
IceUfrag(v) => write!(f, "a=ice-ufrag:{v}\r\n")?,
IcePwd(v) => write!(f, "a=ice-pwd:{v}\r\n")?,
IceOptions(v) => write!(f, "a=ice-options:{v}\r\n")?,
Fingerprint(v) => {
write!(
f,
"a=fingerprint:{} {}\r\n",
v.hash_func,
FingerprintFmt(&v.bytes)
)?;
}
Setup(v) => write!(f, "a=setup:{}\r\n", v.setup_line())?,
Candidate(c) => write!(f, "a={}\r\n", c.to_sdp_string())?,
EndOfCandidates => write!(f, "a=end-of-candidates\r\n")?,
Unused(v) => write!(f, "a={v}\r\n")?,
}
Ok(())
}
}
impl fmt::Display for MediaLine {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let port = if self.disabled { 0 } else { 9 };
write!(f, "m={} {} {} ", self.typ, port, self.proto)?;
let len = self.pts.len();
if self.typ.is_channel() {
write!(f, "webrtc-datachannel\r\n")?;
} else {
for (idx, m) in self.pts.iter().enumerate() {
if idx + 1 < len {
write!(f, "{m} ")?;
} else {
write!(f, "{m}")?;
}
}
write!(f, "\r\n")?;
}
write!(f, "c=IN IP4 0.0.0.0\r\n")?;
if let Some(bw) = &self.bw {
write!(f, "b={}:{}\r\n", bw.typ, bw.val)?;
}
for a in &self.attrs {
write!(f, "{a}")?;
}
Ok(())
}
}
impl fmt::Display for MediaType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
MediaType::Audio => write!(f, "audio"),
MediaType::Video => write!(f, "video"),
MediaType::Application => write!(f, "application"),
MediaType::Unknown(v) => write!(f, "{v}"),
}
}
}
impl fmt::Display for Proto {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.proto_line())
}
}
impl fmt::Display for MediaAttribute {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use MediaAttribute::*;
match self {
Rtcp(v) => write!(f, "a=rtcp:{v}\r\n")?,
IceUfrag(v) => write!(f, "a=ice-ufrag:{v}\r\n")?,
IcePwd(v) => write!(f, "a=ice-pwd:{v}\r\n")?,
IceOptions(v) => write!(f, "a=ice-options:{v}\r\n")?,
Fingerprint(v) => {
write!(
f,
"a=fingerprint:{} {}\r\n",
v.hash_func,
FingerprintFmt(&v.bytes)
)?;
}
Setup(v) => write!(f, "a=setup:{}\r\n", v.setup_line())?,
Mid(v) => write!(f, "a=mid:{v}\r\n")?,
SctpPort(v) => write!(f, "a=sctp-port:{v}\r\n")?,
MaxMessageSize(v) => write!(f, "a=max-message-size:{v}\r\n")?,
SctpInit(v) => write!(f, "a=sctp-init:{v}\r\n")?,
ExtMap { id, ext } => {
if !ext.is_serialized() {
return Ok(());
}
write!(f, "a=extmap:{}", id)?;
// if let Some(d) = &e.direction {
// write!(f, "/{d}")?;
// }
write!(f, " {}", ext.as_uri())?;
// if let Some(e) = &e.ext {
// write!(f, " {}", e)?;
// }
write!(f, "\r\n")?;
}
RecvOnly => write!(f, "a=recvonly\r\n")?,
SendRecv => write!(f, "a=sendrecv\r\n")?,
SendOnly => write!(f, "a=sendonly\r\n")?,
Inactive => write!(f, "a=inactive\r\n")?,
// a=msid:5UUdwiuY7OML2EkQtF38pJtNP5v7In1LhjEK f78dde68-7055-4e20-bb37-433803dd1ed1
// a=msid:- 78dde68-7055-4e20-bb37-433803dd1ed1
Msid(v) => write!(f, "a=msid:{} {}\r\n", v.stream_id, v.track_id)?,
RtcpMux => write!(f, "a=rtcp-mux\r\n")?,
RtcpMuxOnly => write!(f, "a=rtcp-mux-only\r\n")?,
RtcpRsize => write!(f, "a=rtcp-rsize\r\n")?,
Candidate(c) => write!(f, "a={}\r\n", c.to_sdp_string())?,
EndOfCandidates => write!(f, "a=end-of-candidates\r\n")?,
RtpMap { pt, value: c } => {
write!(f, "a=rtpmap:{} {}/{}", pt, c.codec, c.clock_rate)?;
if let Some(e) = c.channels {
write!(f, "/{e}")?;
}
write!(f, "\r\n")?;
}
RtcpFb { pt, value } => write!(f, "a=rtcp-fb:{pt} {value}\r\n")?,
Fmtp { pt, values } => {
if values.is_empty() {
// Skip empty fmtp lines - they're invalid SDP
return Ok(());
}
write!(f, "a=fmtp:{pt} ")?;
for (idx, v) in values.iter().enumerate() {
if idx + 1 < values.len() {
write!(f, "{v};")?;
} else {
write!(f, "{v}\r\n")?;
}
}
}
// a=rid:hi send pt=111,112;max-br=64000;max-height=360
Rid {
id,
direction,
pt,
restriction,
} => {
write!(f, "a=rid:{} {}", id.0, direction)?;
for (idx, p) in pt.iter().enumerate() {
if idx == 0 {
write!(f, " pt=")?;
}
if idx + 1 == pt.len() {
write!(f, "{p}")?;
} else {
write!(f, "{p},")?;
}
}
for (idx, (k, v)) in restriction.iter().enumerate() {
if idx == 0 {
if pt.is_empty() {
write!(f, " ")?;
} else {
write!(f, ";")?;
}
}
if idx + 1 == restriction.len() {
write!(f, "{k}={v}")?;
} else {
write!(f, "{k}={v};")?;
}
}
write!(f, "\r\n")?;
}
// a=simulcast:<send/recv> <alt A>;<alt B>,<or C> <send/recv> [same]
Simulcast(x) => {
let self::Simulcast {
send,
recv,
is_munged,
} = x;
assert!(
!(send.0.is_empty() && recv.0.is_empty()),
"Empty a=simulcast"
);
if *is_munged {
// don't write
return Ok(());
}
write!(f, "a=simulcast:")?;
if !send.0.is_empty() {
write!(f, "send {send}")?;
}
if !recv.0.is_empty() {
if !send.0.is_empty() {
write!(f, " ")?;
}
write!(f, "recv {recv}")?;
}
write!(f, "\r\n")?;
}
SsrcGroup { semantics, ssrcs } => {
write!(f, "a=ssrc-group:{semantics} ")?;
for (idx, ssrc) in ssrcs.iter().enumerate() {
if idx + 1 < ssrcs.len() {
write!(f, "{} ", **ssrc)?;
} else {
write!(f, "{}\r\n", **ssrc)?;
}
}
}
Ssrc { ssrc, attr, value } => {
write!(f, "a=ssrc:{} {}:{}\r\n", **ssrc, attr, value)?;
}
Unused(v) => write!(f, "a={v}\r\n")?,
}
Ok(())
}
}
pub struct FingerprintFmt<'a>(pub &'a [u8]);
impl<'a> std::fmt::Display for FingerprintFmt<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let last = self.0.len() - 1;
for (idx, b) in self.0.iter().enumerate() {
if idx < last {
write!(f, "{b:02X}:")?;
} else {
write!(f, "{b:02X}")?;
}
}
Ok(())
}
}
#[cfg(test)]
mod test {
use crate::VERSION;
use crate::packet::H265ProfileTierLevel;
use crate::rtp_::{Extension, Frequency};
use super::*;
/// Tests for general format parameter serialization and parsing.
/// These tests verify that format parameters can be correctly converted to/from strings.
mod format_params {
use super::*;
#[test]
fn fmtp_param_to_string() {
let f = FormatParams {
min_p_time: Some(10),
use_inband_fec: Some(true),
..Default::default()
};
assert_eq!(f.to_string(), "minptime=10;useinbandfec=1");
}
}
/// Tests for SDP parsing, structure validation, and serialization.
/// Covers error handling, SDP generation, BUNDLE groups, and media line configuration.
mod sdp_parsing {
use super::*;
#[test]
fn parse_error() {
let input = "v=0\r\n\
o=mozilla...THIS_IS_SDPARTA-99.0 7710052215259647220 2 IN IP4 0.0.0.0\r\n\
s=-\r\n\
t=0 0\r\n\
a=fingerprint:sha-256 A6:64:23:37:94:7E:4B:40:F6:62:86:8C:DD:09:D5:08:\
7E:D4:0E:68:58:93:45:EC:99:F2:91:F7:19:72:E7:BB\r\n\
a=group:BUNDLE 0 hxI i1X mxk B3D kNI nbB xIZ bKm Hkn\r\n\
a=ice-options:trickle\r\n\
a=msid-semantic:WMS *\r\n\
m=audio 0 UDP/TLS/RTP/SAVPF 0\r\n\
c=IN IP4 0.0.0.0\r\n\
a=setup:actpass\r\n\
a=mid:1\r\n\
a=rtpmap:0 PCMU/8000\r\n\
";
let sdp = Sdp::parse(input);
match sdp {
Err(SdpError::ParseError(out)) => {
assert!(out.starts_with(&"Parse error at ".to_string()));
assert!(out.contains(
&"Expected exactly one of a=sendrecv, a=sendonly, a=recvonly, a=inactive for mid: 1"
.to_string()
));
}
_ => panic!(),
}
}
#[test]
fn write_sdp() {
let sdp = Sdp {
session: Session {
id: 5_058_682_828_002_148_772.into(),
bw: None,
attrs: vec![
SessionAttribute::Group {
typ: "BUNDLE".into(),
mids: vec!["0".into()],
},
SessionAttribute::Unused(
"msid-semantic: WMS 5UUdwiuY7OML2EkQtF38pJtNP5v7In1LhjEK".into(),
),
],
},
media_lines: vec![
MediaLine {
typ: MediaType::Audio,
disabled: false,
proto: Proto::Srtp,
pts: vec![111, 103, 104, 9, 0, 8, 106, 105, 13, 110, 112, 113, 126]
.into_iter()
.map(Pt::from)
.collect(),
bw: None,
attrs: vec![
MediaAttribute::Rtcp("9 IN IP4 0.0.0.0".into()),
MediaAttribute::IceUfrag("S5hk".into()),
MediaAttribute::IcePwd("0zV/Yu3y8aDzbHgqWhnVQhqP".into()),
MediaAttribute::IceOptions("trickle".into()),
MediaAttribute::Fingerprint(Fingerprint {
hash_func: "sha-256".into(),
bytes: vec![
140, 100, 237, 3, 118, 208, 61, 180, 136, 8, 145, 100, 8, 128,
168, 198, 90, 191, 139, 78, 56, 39, 150, 202, 8, 73, 37, 115,
70, 96, 32, 220,
],
}),
MediaAttribute::Setup(Setup::ActPass),
MediaAttribute::Mid("0".into()),
MediaAttribute::ExtMap{ id: 1, ext: Extension::AudioLevel },
MediaAttribute::ExtMap{ id: 2, ext: Extension::AbsoluteSendTime },
MediaAttribute::ExtMap{ id: 3, ext: Extension::TransportSequenceNumber },
MediaAttribute::ExtMap{ id: 4, ext: Extension::RtpMid },
MediaAttribute::ExtMap{ id: 5, ext: Extension::RtpStreamId },
MediaAttribute::ExtMap{ id: 6, ext: Extension::RepairedRtpStreamId },
MediaAttribute::SendRecv,
MediaAttribute::Msid(Msid {
stream_id: "5UUdwiuY7OML2EkQtF38pJtNP5v7In1LhjEK".into(),
track_id: "f78dde68-7055-4e20-bb37-433803dd1ed1".into(),
}),
MediaAttribute::RtcpMux,
MediaAttribute::RtpMap {
pt: 111.into(),
value: RtpMap {
codec: "opus".into(),
clock_rate: Frequency::FORTY_EIGHT_KHZ,
channels: Some(2),
},
},
MediaAttribute::RtcpFb { pt: 111.into(), value: "transport-cc".into() },
MediaAttribute::Fmtp {
pt: 111.into(),
values: vec![FormatParam::MinPTime(10), FormatParam::UseInbandFec(true)],
},
MediaAttribute::Ssrc {
ssrc: 3_948_621_874.into(),
attr: "cname".into(),
value: "xeXs3aE9AOBn00yJ".into(),
},
MediaAttribute::Ssrc {
ssrc: 3_948_621_874.into(),
attr: "msid".into(),
value: "5UUdwiuY7OML2EkQtF38pJtNP5v7In1LhjEK f78dde68-7055-4e20-bb37-433803dd1ed1"
.into(),
},
MediaAttribute::Ssrc {
ssrc: 3_948_621_874.into(),
attr: "mslabel".into(),
value: "5UUdwiuY7OML2EkQtF38pJtNP5v7In1LhjEK".into(),
},
MediaAttribute::Ssrc {
ssrc: 3_948_621_874.into(),
attr: "label".into(),
value: "f78dde68-7055-4e20-bb37-433803dd1ed1".into(),
},
],
},
MediaLine {
typ: MediaType::Video,
disabled: false,
proto: Proto::Srtp,
pts: vec![45.into(), 46.into()],
bw: None,
attrs: vec![
MediaAttribute::Rtcp("9 IN IP4 0.0.0.0".into()),
MediaAttribute::IceUfrag("S5hk".into()),
MediaAttribute::IcePwd("0zV/Yu3y8aDzbHgqWhnVQhqP".into()),
MediaAttribute::IceOptions("trickle".into()),
MediaAttribute::Fingerprint(Fingerprint {
hash_func: "sha-256".into(),
bytes: vec![
140, 100, 237, 3, 118, 208, 61, 180, 136, 8, 145, 100, 8, 128,
168, 198, 90, 191, 139, 78, 56, 39, 150, 202, 8, 73, 37, 115,
70, 96, 32, 220,
],
}),
MediaAttribute::Setup(Setup::ActPass),
MediaAttribute::Mid("1".into()),
MediaAttribute::ExtMap{ id: 14, ext: Extension::TransmissionTimeOffset },
MediaAttribute::ExtMap{ id: 2, ext: Extension::AbsoluteSendTime },
MediaAttribute::ExtMap{ id: 13, ext: Extension::VideoOrientation },
MediaAttribute::ExtMap{ id: 3, ext: Extension::TransportSequenceNumber },
MediaAttribute::ExtMap{ id: 5, ext: Extension::PlayoutDelay },
MediaAttribute::ExtMap{ id: 6, ext: Extension::VideoContentType },
MediaAttribute::ExtMap{ id: 7, ext: Extension::VideoTiming },
MediaAttribute::ExtMap{ id: 8, ext: Extension::ColorSpace },
MediaAttribute::ExtMap{ id: 4, ext: Extension::RtpMid },
MediaAttribute::ExtMap{ id: 10, ext: Extension::RtpStreamId },
MediaAttribute::ExtMap{ id: 11, ext: Extension::RepairedRtpStreamId },
MediaAttribute::SendRecv,
MediaAttribute::Msid(Msid {
stream_id: "-".into(),
track_id: "4018fd65-ac50-4861-89a4-1f2cc35bbb5e".into(),
}),
MediaAttribute::RtcpMux,
MediaAttribute::RtcpRsize,
MediaAttribute::RtpMap {
pt: 45.into(),
value: RtpMap {
codec: Codec::Av1,
clock_rate: Frequency::NINETY_KHZ,
channels: None,
},
},
MediaAttribute::RtcpFb { pt: 45.into(), value: "goog-remb".into() },
MediaAttribute::RtcpFb { pt: 45.into(), value: "transport-cc".into() },
MediaAttribute::RtcpFb { pt: 45.into(), value: "ccm fir".into() },
MediaAttribute::RtcpFb { pt: 45.into(), value: "nack".into() },
MediaAttribute::RtcpFb { pt: 45.into(), value: "nack pli".into() },
MediaAttribute::Fmtp {
pt: 45.into(),
values: vec![
FormatParam::LevelIdx(5),
FormatParam::Profile(0),
FormatParam::Tier(0),
],
},
MediaAttribute::RtpMap {
pt: 46.into(),
value: RtpMap {
codec: Codec::Rtx,
clock_rate: Frequency::NINETY_KHZ,
channels: None,
},
},
MediaAttribute::Fmtp { pt: 46.into(), values: vec![FormatParam::Apt(45.into())] }
],
}
],
};
assert_eq!(
&format!("{sdp}"),
&format!(
"v=0\r\n\
o=str0m-{VERSION} 5058682828002148772 2 IN IP4 0.0.0.0\r\n\
s=-\r\n\
t=0 0\r\n\
a=group:BUNDLE 0\r\n\
a=msid-semantic: WMS 5UUdwiuY7OML2EkQtF38pJtNP5v7In1LhjEK\r\n\
m=audio 9 UDP/TLS/RTP/SAVPF 111 103 104 9 0 8 106 105 13 110 112 113 126\r\n\
c=IN IP4 0.0.0.0\r\n\
a=rtcp:9 IN IP4 0.0.0.0\r\n\
a=ice-ufrag:S5hk\r\n\
a=ice-pwd:0zV/Yu3y8aDzbHgqWhnVQhqP\r\n\
a=ice-options:trickle\r\n\
a=fingerprint:sha-256 8C:64:ED:03:76:D0:3D:B4:88:08:91:64:08:80:A8:C6:\
5A:BF:8B:4E:38:27:96:CA:08:49:25:73:46:60:20:DC\r\n\
a=setup:actpass\r\n\
a=mid:0\r\n\
a=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level\r\n\
a=extmap:2 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\r\n\
a=extmap:3 http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01\r\n\
a=extmap:4 urn:ietf:params:rtp-hdrext:sdes:mid\r\n\
a=extmap:5 urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id\r\n\
a=extmap:6 urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id\r\n\
a=sendrecv\r\n\
a=msid:5UUdwiuY7OML2EkQtF38pJtNP5v7In1LhjEK f78dde68-7055-4e20-bb37-433803dd1ed1\r\n\
a=rtcp-mux\r\n\
a=rtpmap:111 opus/48000/2\r\n\
a=rtcp-fb:111 transport-cc\r\n\
a=fmtp:111 minptime=10;useinbandfec=1\r\n\
a=ssrc:3948621874 cname:xeXs3aE9AOBn00yJ\r\n\
a=ssrc:3948621874 msid:5UUdwiuY7OML2EkQtF38pJtNP5v7In1LhjEK \
f78dde68-7055-4e20-bb37-433803dd1ed1\r\n\
a=ssrc:3948621874 mslabel:5UUdwiuY7OML2EkQtF38pJtNP5v7In1LhjEK\r\n\
a=ssrc:3948621874 label:f78dde68-7055-4e20-bb37-433803dd1ed1\r\n\
m=video 9 UDP/TLS/RTP/SAVPF 45 46\r\n\
c=IN IP4 0.0.0.0\r\n\
a=rtcp:9 IN IP4 0.0.0.0\r\n\
a=ice-ufrag:S5hk\r\n\
a=ice-pwd:0zV/Yu3y8aDzbHgqWhnVQhqP\r\n\
a=ice-options:trickle\r\n\
a=fingerprint:sha-256 8C:64:ED:03:76:D0:3D:B4:88:08:91:64:08:80:A8:C6:\
5A:BF:8B:4E:38:27:96:CA:08:49:25:73:46:60:20:DC\r\n\
a=setup:actpass\r\n\
a=mid:1\r\n\
a=extmap:14 urn:ietf:params:rtp-hdrext:toffset\r\n\
a=extmap:2 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\r\n\
a=extmap:13 urn:3gpp:video-orientation\r\n\
a=extmap:3 http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01\r\n\
a=extmap:5 http://www.webrtc.org/experiments/rtp-hdrext/playout-delay\r\n\
a=extmap:6 http://www.webrtc.org/experiments/rtp-hdrext/video-content-type\r\n\
a=extmap:7 http://www.webrtc.org/experiments/rtp-hdrext/video-timing\r\n\
a=extmap:8 http://www.webrtc.org/experiments/rtp-hdrext/color-space\r\n\
a=extmap:4 urn:ietf:params:rtp-hdrext:sdes:mid\r\n\
a=extmap:10 urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id\r\n\
a=extmap:11 urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id\r\n\
a=sendrecv\r\n\
a=msid:- 4018fd65-ac50-4861-89a4-1f2cc35bbb5e\r\n\
a=rtcp-mux\r\n\
a=rtcp-rsize\r\n\
a=rtpmap:45 AV1/90000\r\n\
a=rtcp-fb:45 goog-remb\r\n\
a=rtcp-fb:45 transport-cc\r\n\
a=rtcp-fb:45 ccm fir\r\n\
a=rtcp-fb:45 nack\r\n\
a=rtcp-fb:45 nack pli\r\n\
a=fmtp:45 level-idx=5;profile=0;tier=0\r\n\
a=rtpmap:46 rtx/90000\r\n\
a=fmtp:46 apt=45\r\n\
"
)
);
}
#[test]
fn bundle_mids_returns_correct_mids() {
let input = "v=0\r\n\
o=- 123456 2 IN IP4 127.0.0.1\r\n\
s=-\r\n\
t=0 0\r\n\
a=group:BUNDLE 0 1 2\r\n\
a=msid-semantic:WMS *\r\n\
m=audio 9 UDP/TLS/RTP/SAVPF 111\r\n\
c=IN IP4 0.0.0.0\r\n\
a=mid:0\r\n\
a=sendrecv\r\n\
a=rtpmap:111 opus/48000/2\r\n\
a=setup:actpass\r\n\
a=ice-ufrag:test\r\n\
a=ice-pwd:testpassword1234\r\n\
m=video 0 UDP/TLS/RTP/SAVPF 96\r\n\
c=IN IP4 0.0.0.0\r\n\
a=mid:1\r\n\
a=sendrecv\r\n\
a=rtpmap:96 VP8/90000\r\n\
a=setup:actpass\r\n\
a=ice-ufrag:test\r\n\
a=ice-pwd:testpassword1234\r\n\
m=application 0 UDP/DTLS/SCTP webrtc-datachannel\r\n\
c=IN IP4 0.0.0.0\r\n\
a=mid:2\r\n\
a=setup:actpass\r\n\
a=ice-ufrag:test\r\n\
a=ice-pwd:testpassword1234\r\n\
a=sctp-port:5000\r\n\
";
let sdp = Sdp::parse(input).expect("should parse");
// bundle_mids should return all MIDs from the BUNDLE group
let mids = sdp.bundle_mids().expect("should have BUNDLE group");
assert_eq!(mids.len(), 3);
assert_eq!(mids[0], "0".into());
assert_eq!(mids[1], "1".into());
assert_eq!(mids[2], "2".into());
// The m-lines with port=0 should have disabled=true at parsing level
// (interpretation of whether this means "rejected" happens later)
assert!(!sdp.media_lines[0].disabled, "audio has port=9");
assert!(sdp.media_lines[1].disabled, "video has port=0");
assert!(sdp.media_lines[2].disabled, "application has port=0");
}
}
/// Core H.265 (HEVC) codec-specific tests.
/// Tests basic H.265 parameter handling including profile-tier-level parsing,
/// serialization, and format parameter combinations.
mod h265_codec {
use super::*;
/// Test that H.265 format parameters can be serialized to a string and parsed back
/// without loss of information. Verifies the round-trip conversion works correctly.
#[test]
fn h265_fmtp_round_trip() {
// Test that H.265 fmtp params round-trip correctly
let ptl = H265ProfileTierLevel::new(1, 0, 93).unwrap(); // Main, Main tier, Level 3.1
let f = FormatParams {
h265_profile_tier_level: Some(ptl),
..Default::default()
};
// Serialize to string
let fmtp_str = f.to_string();
assert_eq!(fmtp_str, "profile-id=1;tier-flag=0;level-id=93");
// Parse back
let parsed = FormatParams::parse_line(&fmtp_str);
assert_eq!(parsed.h265_profile_tier_level, Some(ptl));
}
/// Test different combinations of H.265 profiles, tiers, and levels to ensure
/// they are all serialized correctly. Covers Main, Main 10, different tiers, and levels.
#[test]
fn h265_different_profiles() {
// Test Main profile (1)
let main = H265ProfileTierLevel::new(1, 0, 93).unwrap();
let f = FormatParams {
h265_profile_tier_level: Some(main),
..Default::default()
};
assert_eq!(f.to_string(), "profile-id=1;tier-flag=0;level-id=93");
// Test Main 10 profile (2)
let main10 = H265ProfileTierLevel::new(2, 0, 93).unwrap();
let f = FormatParams {
h265_profile_tier_level: Some(main10),
..Default::default()
};
assert_eq!(f.to_string(), "profile-id=2;tier-flag=0;level-id=93");
// Test different tier (High tier)
let high_tier = H265ProfileTierLevel::new(1, 1, 93).unwrap();
let f = FormatParams {
h265_profile_tier_level: Some(high_tier),
..Default::default()
};
assert_eq!(f.to_string(), "profile-id=1;tier-flag=1;level-id=93");
// Test different level (Level 5.1 = 153)
let level_5_1 = H265ProfileTierLevel::new(1, 0, 153).unwrap();
let f = FormatParams {
h265_profile_tier_level: Some(level_5_1),
..Default::default()
};
assert_eq!(f.to_string(), "profile-id=1;tier-flag=0;level-id=153");
}
/// Test parsing H.265 parameters from key-value pairs as they would appear in SDP.
/// Verifies that the three separate params (profile-id, tier-flag, level-id) are
/// correctly combined into a single H265ProfileTierLevel composite.
#[test]
fn h265_parse_from_pairs() {
// Test parsing from key-value pairs (as would come from SDP)
let pairs = vec![
("profile-id".to_string(), "1".to_string()),
("tier-flag".to_string(), "0".to_string()),
("level-id".to_string(), "93".to_string()),
];
let params = FormatParam::parse_pairs(pairs);
// Should have exactly one H265ProfileTierLevel param
let h265_params: Vec<_> = params
.iter()
.filter(|p| matches!(p, FormatParam::H265ProfileTierLevel(_)))
.collect();
assert_eq!(h265_params.len(), 1);
if let FormatParam::H265ProfileTierLevel(ptl) = h265_params[0] {
assert_eq!(ptl.profile_id(), 1);
assert_eq!(ptl.tier_flag(), 0);
assert_eq!(ptl.level_id(), 93);
} else {
panic!("Expected H265ProfileTierLevel");
}
}
/// Test that H.265 profile-tier-level params can coexist with other H.265-specific
/// parameters like sprop-max-don-diff without interfering with each other.
#[test]
fn h265_mixed_with_other_params() {
// Test H.265 params mixed with other format params
let pairs = vec![
("profile-id".to_string(), "1".to_string()),
("tier-flag".to_string(), "0".to_string()),
("level-id".to_string(), "93".to_string()),
("sprop-max-don-diff".to_string(), "0".to_string()),
];
let params = FormatParam::parse_pairs(pairs);
// Should have H265ProfileTierLevel and SpropMaxDonDiff
assert!(
params
.iter()
.any(|p| matches!(p, FormatParam::H265ProfileTierLevel(_)))
);
assert!(
params
.iter()
.any(|p| matches!(p, FormatParam::SpropMaxDonDiff(0)))
);
}
/// Test sprop-max-don-diff parsing, display, and round-trip for various values.
#[test]
fn sprop_max_don_diff_parse_and_display() {
// Parse standalone sprop-max-don-diff
let param = FormatParam::parse("sprop-max-don-diff", "32");
assert!(matches!(param, FormatParam::SpropMaxDonDiff(32)));
// Display format
assert_eq!(param.to_string(), "sprop-max-don-diff=32");
// Parse value 0 (DONL disabled)
let param0 = FormatParam::parse("sprop-max-don-diff", "0");
assert!(matches!(param0, FormatParam::SpropMaxDonDiff(0)));
// Parse max valid value (RFC 7798 §7.1: 0..32767)
let param_max = FormatParam::parse("sprop-max-don-diff", "32767");
assert!(matches!(param_max, FormatParam::SpropMaxDonDiff(32767)));
// Out-of-range value (32768) rejected per RFC 7798 §7.1
let param_over = FormatParam::parse("sprop-max-don-diff", "32768");
assert!(matches!(param_over, FormatParam::Unknown));
// Invalid value falls back to Unknown
let param_bad = FormatParam::parse("sprop-max-don-diff", "notanumber");
assert!(matches!(param_bad, FormatParam::Unknown));
}
/// Test that sprop-max-don-diff > 0 round-trips through H.265 fmtp with PTL params.
#[test]
fn h265_sprop_max_don_diff_nonzero_with_ptl() {
let pairs = vec![
("profile-id".to_string(), "1".to_string()),
("tier-flag".to_string(), "0".to_string()),
("level-id".to_string(), "93".to_string()),
("sprop-max-don-diff".to_string(), "32".to_string()),
];
let params = FormatParam::parse_pairs(pairs);
// Should have both H265ProfileTierLevel and SpropMaxDonDiff(32)
assert!(
params
.iter()
.any(|p| matches!(p, FormatParam::H265ProfileTierLevel(_)))
);
assert!(
params
.iter()
.any(|p| matches!(p, FormatParam::SpropMaxDonDiff(32)))
);
// Verify PTL values are correct
if let Some(FormatParam::H265ProfileTierLevel(ptl)) = params
.iter()
.find(|p| matches!(p, FormatParam::H265ProfileTierLevel(_)))
{
assert_eq!(ptl.profile_id(), 1);
assert_eq!(ptl.tier_flag(), 0);
assert_eq!(ptl.level_id(), 93);
}
}
}
/// Tests ensuring H.265 parameters are not confused with other codecs.
/// Verifies that H.265's three-parameter format (profile-id, tier-flag, level-id)
/// is correctly distinguished from H.264's profile-level-id, VP9's profile-id,
/// and AV1's profile/tier/level-idx parameters.
mod no_confusion {
use super::*;
/// Test that H.264's profile-level-id parameter (single hex value) is not confused
/// with H.265's three separate parameters. H.264 uses a different format entirely.
#[test]
fn h265_no_confusion_with_h264() {
// H.264 uses profile-level-id (single param)
let h264_pairs = vec![
("profile-level-id".to_string(), "42e01f".to_string()),
("packetization-mode".to_string(), "1".to_string()),
];
let h264_params = FormatParam::parse_pairs(h264_pairs);
// Should NOT have H265ProfileTierLevel
assert!(
!h264_params
.iter()
.any(|p| matches!(p, FormatParam::H265ProfileTierLevel(_)))
);
// Should have ProfileLevelId (H.264)
assert!(
h264_params
.iter()
.any(|p| matches!(p, FormatParam::ProfileLevelId(_)))
);
assert!(
h264_params
.iter()
.any(|p| matches!(p, FormatParam::PacketizationMode(1)))
);
}
/// Test that VP9's profile-id parameter (standalone) is not confused with H.265's
/// profile-id which must be combined with tier-flag and level-id.
#[test]
fn h265_no_confusion_with_vp9() {
// VP9 uses profile-id (single param, not combined)
let vp9_pairs = vec![("profile-id".to_string(), "0".to_string())];
let vp9_params = FormatParam::parse_pairs(vp9_pairs);
// Should NOT have H265ProfileTierLevel (missing tier-flag and level-id)
assert!(
!vp9_params
.iter()
.any(|p| matches!(p, FormatParam::H265ProfileTierLevel(_)))
);
// Should have ProfileId (VP9)
assert!(
vp9_params
.iter()
.any(|p| matches!(p, FormatParam::ProfileId(0)))
);
}
/// Test that AV1's parameters (profile, tier, level-idx) use different naming than
/// H.265 (profile-id, tier-flag, level-id) and are not confused during parsing.
#[test]
fn h265_no_confusion_with_av1() {
// AV1 uses profile, level-idx, tier (but should not be confused with H.265)
let av1_pairs = vec![
("profile".to_string(), "0".to_string()),
("level-idx".to_string(), "5".to_string()),
("tier".to_string(), "0".to_string()),
];
let av1_params = FormatParam::parse_pairs(av1_pairs);
// Should NOT have H265ProfileTierLevel
// (AV1 uses different param names: profile vs profile-id,
// tier vs tier-flag, level-idx vs level-id)
assert!(
!av1_params
.iter()
.any(|p| matches!(p, FormatParam::H265ProfileTierLevel(_)))
);
// Should have AV1-specific params
assert!(
av1_params
.iter()
.any(|p| matches!(p, FormatParam::Profile(0)))
);
assert!(
av1_params
.iter()
.any(|p| matches!(p, FormatParam::LevelIdx(5)))
);
assert!(av1_params.iter().any(|p| matches!(p, FormatParam::Tier(0))));
}
}
/// Additional H.265 parsing and validation tests.
/// Covers incomplete parameter handling and complete SDP integration scenarios.
mod h265_additional {
use super::*;
/// Test that incomplete H.265 parameter sets do not create a composite ProfileTierLevel.
/// All three parameters (profile-id, tier-flag, level-id) must be present.
#[test]
fn h265_partial_params_no_composite() {
// If only some H.265 params are present, should not create composite
let partial_pairs = vec![
("profile-id".to_string(), "1".to_string()),
("tier-flag".to_string(), "0".to_string()),
// Missing level-id
];
let params = FormatParam::parse_pairs(partial_pairs);
// Should NOT have H265ProfileTierLevel (incomplete)
assert!(
!params
.iter()
.any(|p| matches!(p, FormatParam::H265ProfileTierLevel(_)))
);
}
/// Test H.265 parameters in a complete SDP offer/answer scenario.
/// Verifies that H.265 rtpmap and fmtp lines are correctly parsed along with RTX.
#[test]
fn h265_in_complete_sdp() {
let input = "v=0\r\n\
o=- 123456 2 IN IP4 127.0.0.1\r\n\
s=-\r\n\
t=0 0\r\n\
a=group:BUNDLE 0\r\n\
m=video 9 UDP/TLS/RTP/SAVPF 96 97\r\n\
c=IN IP4 0.0.0.0\r\n\
a=mid:0\r\n\
a=sendrecv\r\n\
a=rtpmap:96 H265/90000\r\n\
a=fmtp:96 profile-id=1;tier-flag=0;level-id=93\r\n\
a=rtpmap:97 rtx/90000\r\n\
a=fmtp:97 apt=96\r\n\
a=setup:actpass\r\n\
a=ice-ufrag:test\r\n\
a=ice-pwd:testpassword\r\n\
";
let sdp = Sdp::parse(input).expect("should parse");
// Get RTP params
let params = sdp.media_lines[0].rtp_params();
// Find H.265 payload
let h265_payload = params
.iter()
.find(|p| p.spec.codec == Codec::H265)
.expect("should have H.265");
assert_eq!(h265_payload.pt, 96.into());
assert_eq!(h265_payload.spec.clock_rate, Frequency::NINETY_KHZ);
// Check H.265 params
let ptl = h265_payload
.spec
.format
.h265_profile_tier_level
.expect("should have H.265 PTL");
assert_eq!(ptl.profile_id(), 1);
assert_eq!(ptl.tier_flag(), 0);
assert_eq!(ptl.level_id(), 93);
// Check RTX
assert_eq!(h265_payload.resend, Some(97.into()));
}
}
/// Multi-codec integration tests.
/// Verifies that multiple video codecs (H.264, H.265, VP8, VP9) can coexist
/// in the same SDP without parameter conflicts or interference.
mod multi_codec {
use super::*;
/// Test that H.264, H.265, and other video codecs can coexist in the same SDP
/// without their format parameters interfering with each other.
#[test]
fn h265_and_h264_coexist() {
let input = "v=0\r\n\
o=- 123456 2 IN IP4 127.0.0.1\r\n\
s=-\r\n\
t=0 0\r\n\
a=group:BUNDLE 0\r\n\
m=video 9 UDP/TLS/RTP/SAVPF 96 97 98\r\n\
c=IN IP4 0.0.0.0\r\n\
a=mid:0\r\n\
a=sendrecv\r\n\
a=rtpmap:96 H264/90000\r\n\
a=fmtp:96 profile-level-id=42e01f;packetization-mode=1\r\n\
a=rtpmap:97 H265/90000\r\n\
a=fmtp:97 profile-id=1;tier-flag=0;level-id=93\r\n\
a=rtpmap:98 VP8/90000\r\n\
a=setup:actpass\r\n\
a=ice-ufrag:test\r\n\
a=ice-pwd:testpassword\r\n\
";
let sdp = Sdp::parse(input).expect("should parse");
let params = sdp.media_lines[0].rtp_params();
// Check H.264
let h264 = params
.iter()
.find(|p| p.spec.codec == Codec::H264)
.expect("should have H.264");
assert_eq!(h264.pt, 96.into());
assert_eq!(h264.spec.format.profile_level_id, Some(0x42e01f));
assert_eq!(h264.spec.format.packetization_mode, Some(1));
assert!(h264.spec.format.h265_profile_tier_level.is_none());
// Check H.265
let h265 = params
.iter()
.find(|p| p.spec.codec == Codec::H265)
.expect("should have H.265");
assert_eq!(h265.pt, 97.into());
let ptl = h265
.spec
.format
.h265_profile_tier_level
.expect("should have H.265 PTL");
assert_eq!(ptl.profile_id(), 1);
assert!(h265.spec.format.profile_level_id.is_none());
// Check VP8
let vp8 = params
.iter()
.find(|p| p.spec.codec == Codec::Vp8)
.expect("should have VP8");
assert_eq!(vp8.pt, 98.into());
assert!(vp8.spec.format.h265_profile_tier_level.is_none());
assert!(vp8.spec.format.profile_level_id.is_none());
}
}
/// H.265 serialization and edge case tests.
/// Tests media attribute generation, empty parameter handling, extreme values,
/// parameter ordering independence, DONL parameters, and invalid value handling.
mod h265_serialization {
use super::*;
/// Test that H.265 parameters are correctly serialized as media attributes,
/// including rtpmap, fmtp with ProfileTierLevel, rtcp-fb, and RTX payload.
#[test]
fn h265_serialization_in_media_attrs() {
let ptl = H265ProfileTierLevel::new(2, 1, 153).unwrap(); // Main 10, High tier, Level 5.1
let mut payload = PayloadParams::new(
100.into(),
Some(101.into()),
CodecSpec {
codec: Codec::H265,
clock_rate: Frequency::NINETY_KHZ,
channels: None,
format: FormatParams {
h265_profile_tier_level: Some(ptl),
..Default::default()
},
},
);
payload.fb_transport_cc = true;
payload.fb_nack = true;
payload.fb_pli = true;
let mut attrs = vec![];
payload.as_media_attrs(&mut attrs);
// Should have rtpmap for H.265
assert!(attrs.iter().any(|a| matches!(a,
MediaAttribute::RtpMap { pt, value }
if *pt == 100.into() && value.codec == Codec::H265
)));
// Should have fmtp with H.265 params
let fmtp = attrs.iter().find(|a| {
matches!(a,
MediaAttribute::Fmtp { pt, .. } if *pt == 100.into()
)
});
assert!(fmtp.is_some());
if let Some(MediaAttribute::Fmtp { values, .. }) = fmtp {
assert!(
values
.iter()
.any(|v| matches!(v, FormatParam::H265ProfileTierLevel(p)
if p.profile_id() == 2 && p.tier_flag() == 1 && p.level_id() == 153
))
);
}
// Should have rtx mapping
assert!(attrs.iter().any(|a| matches!(a,
MediaAttribute::RtpMap { pt, value }
if *pt == 101.into() && value.codec == Codec::Rtx
)));
}
/// Test that empty format parameters do not generate an a=fmtp line in SDP,
/// avoiding invalid SDP syntax with empty fmtp attributes.
#[test]
fn h265_empty_fmtp_not_serialized() {
// Empty fmtp should not be written
let payload = PayloadParams::new(
100.into(),
None,
CodecSpec {
codec: Codec::H265,
clock_rate: Frequency::NINETY_KHZ,
channels: None,
format: FormatParams::default(),
},
);
let mut attrs = vec![];
payload.as_media_attrs(&mut attrs);
// Should NOT have fmtp line (it would be empty)
assert!(
!attrs
.iter()
.any(|a| matches!(a, MediaAttribute::Fmtp { .. }))
);
}
/// Test H.265 with extreme profile/tier/level values at boundaries.
/// Verifies parsing and serialization of edge case values.
#[test]
fn h265_extreme_values() {
// Test minimum level (Level 1.0 = 30)
let min_level = H265ProfileTierLevel::new(1, 0, 30).unwrap();
let f = FormatParams {
h265_profile_tier_level: Some(min_level),
..Default::default()
};
assert_eq!(f.to_string(), "profile-id=1;tier-flag=0;level-id=30");
// Test maximum level (Level 6.2 = 186)
let max_level = H265ProfileTierLevel::new(1, 0, 186).unwrap();
let f = FormatParams {
h265_profile_tier_level: Some(max_level),
..Default::default()
};
assert_eq!(f.to_string(), "profile-id=1;tier-flag=0;level-id=186");
// Test Main10 with High tier
let main10_high = H265ProfileTierLevel::new(2, 1, 93).unwrap();
let f = FormatParams {
h265_profile_tier_level: Some(main10_high),
..Default::default()
};
assert_eq!(f.to_string(), "profile-id=2;tier-flag=1;level-id=93");
}
/// Test H.265 parameter ordering doesn't affect parsing.
/// SDP parameters can appear in any order.
#[test]
fn h265_parameter_order_independence() {
// Normal order
let normal_order = vec![
("profile-id".to_string(), "1".to_string()),
("tier-flag".to_string(), "0".to_string()),
("level-id".to_string(), "93".to_string()),
];
// Reversed order
let reversed_order = vec![
("level-id".to_string(), "93".to_string()),
("tier-flag".to_string(), "0".to_string()),
("profile-id".to_string(), "1".to_string()),
];
// Mixed order
let mixed_order = vec![
("tier-flag".to_string(), "0".to_string()),
("profile-id".to_string(), "1".to_string()),
("level-id".to_string(), "93".to_string()),
];
let normal_params = FormatParam::parse_pairs(normal_order);
let reversed_params = FormatParam::parse_pairs(reversed_order);
let mixed_params = FormatParam::parse_pairs(mixed_order);
// All should create H265ProfileTierLevel
assert!(
normal_params
.iter()
.any(|p| matches!(p, FormatParam::H265ProfileTierLevel(_)))
);
assert!(
reversed_params
.iter()
.any(|p| matches!(p, FormatParam::H265ProfileTierLevel(_)))
);
assert!(
mixed_params
.iter()
.any(|p| matches!(p, FormatParam::H265ProfileTierLevel(_)))
);
// All should have the same values
for params in [&normal_params, &reversed_params, &mixed_params] {
if let Some(FormatParam::H265ProfileTierLevel(ptl)) = params
.iter()
.find(|p| matches!(p, FormatParam::H265ProfileTierLevel(_)))
{
assert_eq!(ptl.profile_id(), 1);
assert_eq!(ptl.tier_flag(), 0);
assert_eq!(ptl.level_id(), 93);
}
}
}
#[test]
fn h265_invalid_parameter_values() {
// Invalid profile-id
let invalid_profile = vec![
("profile-id".to_string(), "999".to_string()),
("tier-flag".to_string(), "0".to_string()),
("level-id".to_string(), "93".to_string()),
];
let params = FormatParam::parse_pairs(invalid_profile);
assert!(
!params
.iter()
.any(|p| matches!(p, FormatParam::H265ProfileTierLevel(_)))
);
// Invalid tier-flag
let invalid_tier = vec![
("profile-id".to_string(), "1".to_string()),
("tier-flag".to_string(), "5".to_string()),
("level-id".to_string(), "93".to_string()),
];
let params = FormatParam::parse_pairs(invalid_tier);
assert!(
!params
.iter()
.any(|p| matches!(p, FormatParam::H265ProfileTierLevel(_)))
);
// Invalid level-id
let invalid_level = vec![
("profile-id".to_string(), "1".to_string()),
("tier-flag".to_string(), "0".to_string()),
("level-id".to_string(), "999".to_string()),
];
let params = FormatParam::parse_pairs(invalid_level);
assert!(
!params
.iter()
.any(|p| matches!(p, FormatParam::H265ProfileTierLevel(_)))
);
}
}
/// H.265 integration with RTCP feedback mechanisms.
/// Tests H.265 behavior with multiple codecs and various RTCP feedback types
/// including NACK, PLI, FIR, and transport-cc.
mod h265_integration {
use super::*;
/// Test H.265 in SDP with multiple video codecs and feedback mechanisms.
/// Verifies proper parsing of complex multi-codec scenarios.
#[test]
fn h265_multi_codec_with_feedback() {
let input = "v=0\r\n\
o=- 123456 2 IN IP4 127.0.0.1\r\n\
s=-\r\n\
t=0 0\r\n\
a=group:BUNDLE 0\r\n\
m=video 9 UDP/TLS/RTP/SAVPF 96 97 98 99\r\n\
c=IN IP4 0.0.0.0\r\n\
a=mid:0\r\n\
a=sendrecv\r\n\
a=rtpmap:96 H265/90000\r\n\
a=fmtp:96 profile-id=1;tier-flag=0;level-id=93\r\n\
a=rtcp-fb:96 nack\r\n\
a=rtcp-fb:96 nack pli\r\n\
a=rtcp-fb:96 ccm fir\r\n\
a=rtcp-fb:96 transport-cc\r\n\
a=rtpmap:97 rtx/90000\r\n\
a=fmtp:97 apt=96\r\n\
a=rtpmap:98 VP9/90000\r\n\
a=fmtp:98 profile-id=0\r\n\
a=rtpmap:99 rtx/90000\r\n\
a=fmtp:99 apt=98\r\n\
a=setup:actpass\r\n\
a=ice-ufrag:test\r\n\
a=ice-pwd:testpassword\r\n\
";
let sdp = Sdp::parse(input).expect("should parse");
let params = sdp.media_lines[0].rtp_params();
// Check H.265 with all feedback mechanisms
let h265 = params
.iter()
.find(|p| p.spec.codec == Codec::H265)
.expect("should have H.265");
assert_eq!(h265.pt, 96.into());
assert!(h265.fb_nack);
assert!(h265.fb_pli);
assert!(h265.fb_fir);
assert!(h265.fb_transport_cc);
assert_eq!(h265.resend, Some(97.into()));
// Verify H.265 PTL is correct
let ptl = h265
.spec
.format
.h265_profile_tier_level
.expect("should have PTL");
assert_eq!(ptl.profile_id(), 1);
// Check VP9 is separate and correct
let vp9 = params
.iter()
.find(|p| p.spec.codec == Codec::Vp9)
.expect("should have VP9");
assert_eq!(vp9.pt, 98.into());
assert_eq!(vp9.spec.format.profile_id, Some(0));
assert!(vp9.spec.format.h265_profile_tier_level.is_none());
}
}
/// Advanced H.265 functionality tests.
/// Covers SDP round-trip serialization, incomplete parameter permutations,
/// browser compatibility (Chrome profile-only mode), and validation of all
/// standard H.265 level values (1.0 through 6.2).
mod h265_advanced {
use super::*;
/// Test H.265 SDP serialization maintains parameter integrity.
/// Ensures that serialized SDP can be parsed back with identical values.
#[test]
fn h265_sdp_serialization_round_trip() {
let ptl = H265ProfileTierLevel::new(2, 0, 153).unwrap();
let payload = PayloadParams::new(
100.into(),
Some(101.into()),
CodecSpec {
codec: Codec::H265,
clock_rate: Frequency::NINETY_KHZ,
channels: None,
format: FormatParams {
h265_profile_tier_level: Some(ptl),
..Default::default()
},
},
);
let mut attrs = vec![];
payload.as_media_attrs(&mut attrs);
// Find the fmtp line
let fmtp = attrs
.iter()
.find_map(|a| match a {
MediaAttribute::Fmtp { pt, values } if *pt == 100.into() => Some(values),
_ => None,
})
.expect("should have fmtp");
// Should contain H265ProfileTierLevel
assert!(
fmtp.iter().any(
|v| matches!(v, FormatParam::H265ProfileTierLevel(p) if p.profile_id() == 2)
)
);
}
/// Test that only two of three H.265 params doesn't create PTL.
/// Each permutation of missing parameter should fail.
#[test]
fn h265_incomplete_params_all_permutations() {
// Missing level-id
let missing_level = vec![
("profile-id".to_string(), "1".to_string()),
("tier-flag".to_string(), "0".to_string()),
];
let params = FormatParam::parse_pairs(missing_level);
assert!(
!params
.iter()
.any(|p| matches!(p, FormatParam::H265ProfileTierLevel(_)))
);
// Missing tier-flag
let missing_tier = vec![
("profile-id".to_string(), "1".to_string()),
("level-id".to_string(), "93".to_string()),
];
let params = FormatParam::parse_pairs(missing_tier);
assert!(
!params
.iter()
.any(|p| matches!(p, FormatParam::H265ProfileTierLevel(_)))
);
// Missing profile-id
let missing_profile = vec![
("tier-flag".to_string(), "0".to_string()),
("level-id".to_string(), "93".to_string()),
];
let params = FormatParam::parse_pairs(missing_profile);
assert!(
!params
.iter()
.any(|p| matches!(p, FormatParam::H265ProfileTierLevel(_)))
);
// Only one parameter
let only_profile = vec![("profile-id".to_string(), "1".to_string())];
let params = FormatParam::parse_pairs(only_profile);
assert!(
!params
.iter()
.any(|p| matches!(p, FormatParam::H265ProfileTierLevel(_)))
);
}
/// Test H.265 with Chrome-style profile-only in complete SDP.
/// Verifies that browser compatibility mode works in real SDP.
#[test]
fn h265_chrome_profile_only_sdp() {
let input = "v=0\r\n\
o=- 123456 2 IN IP4 127.0.0.1\r\n\
s=-\r\n\
t=0 0\r\n\
a=group:BUNDLE 0\r\n\
m=video 9 UDP/TLS/RTP/SAVPF 96\r\n\
c=IN IP4 0.0.0.0\r\n\
a=mid:0\r\n\
a=sendrecv\r\n\
a=rtpmap:96 H265/90000\r\n\
a=fmtp:96 profile-id=1\r\n\
a=setup:actpass\r\n\
a=ice-ufrag:test\r\n\
a=ice-pwd:testpassword\r\n\
";
let sdp = Sdp::parse(input).expect("should parse");
let params = sdp.media_lines[0].rtp_params();
let h265 = params
.iter()
.find(|p| p.spec.codec == Codec::H265)
.expect("should have H.265");
// Should NOT have full PTL
assert!(h265.spec.format.h265_profile_tier_level.is_none());
// Should have profile_id field instead
assert_eq!(h265.spec.format.profile_id, Some(1));
}
/// Test H.265 different level values in valid range.
/// Ensures all valid level IDs are properly handled.
#[test]
fn h265_all_valid_levels() {
let valid_levels = vec![
30, // Level 1.0
60, // Level 2.0
63, // Level 2.1
90, // Level 3.0
93, // Level 3.1
120, // Level 4.0
123, // Level 4.1
150, // Level 5.0
153, // Level 5.1
156, // Level 5.2
180, // Level 6.0
183, // Level 6.1
186, // Level 6.2
];
for level_id in valid_levels {
let ptl = H265ProfileTierLevel::new(1, 0, level_id);
assert!(ptl.is_some(), "Level ID {} should be valid", level_id);
let f = FormatParams {
h265_profile_tier_level: ptl,
..Default::default()
};
let serialized = f.to_string();
assert!(serialized.contains(&format!("level-id={}", level_id)));
}
}
}
}