sdp-types 0.2.0

SDP (RFC 4566) types, parser and serializer
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
// Copyright (C) 2026 Taruntej Kanakamalla <tarun@centricular.com>
//
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>

//! Contains all the Session description Attributes defined as Structs/Enums

use std::{
    fmt::{Display, Write},
    net::IpAddr,
    str::FromStr,
};

use crate::{builders, enums::*, Attribute};

/// Trait for Typed Attribute structs
pub trait TypedAttribute: Display + FromStr<Err = AttributeError> {
    const NAME: &'static str;
}

impl<T: TypedAttribute> From<T> for Attribute {
    fn from(attr: T) -> Attribute {
        Attribute {
            attribute: T::NAME.to_string(),
            value: Some(attr.to_string()),
        }
    }
}

/// Attribute error with specific details
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum AttributeError {
    /// If an Attribute is not found in a media or the session
    #[error("Attribute {} not found", .0)]
    NotFound(String),
    /// If a parameter is missing in an attribute
    #[error("Param {} not found in {}", .param, .attr)]
    ParamNotFound { param: String, attr: String },
    /// If a parameter value is not valid type or not in range
    #[error("Invalid value {} for Param {} in {}", .val ,.param, .attr)]
    InvalidParamValue {
        param: String,
        val: String,
        attr: String,
    },
    /// If an attribute is not in expected format
    #[error("Unsupported attribute format: {} for {}", .val, .attr)]
    UnsupportedFormat { val: String, attr: String },
    /// If there are more than expected items trailing in the attribute parameters
    #[error("Unexpected trailing item {} for in {}", .val, .attr)]
    UnexpectedTrailingItem { val: String, attr: String },
    /// Unspecified error
    #[error("{}: {}", .attr, .error)]
    Other { error: String, attr: String },
}

impl AttributeError {
    pub fn is_attribute_not_found(&self) -> bool {
        matches!(self, AttributeError::NotFound(_))
    }

    /// Preprends the provided `param_context` to the parameter field of this AttributeError if applicable
    fn add_param_context(&mut self, param_context: &str) {
        use AttributeError::*;
        match self {
            NotFound(_)
            | Other { .. }
            | UnsupportedFormat { .. }
            | UnexpectedTrailingItem { .. } => (),
            ParamNotFound { param, .. } | InvalidParamValue { param, .. } => {
                param.push(')');
                param.insert_str(0, " (");
                param.insert_str(0, param_context);
            }
        }
    }

    /// Sets the attribute field of this AttributeError to new_attr
    pub(crate) fn set_attr(&mut self, new_attr: impl ToString) {
        use AttributeError::*;
        match self {
            NotFound(attr)
            | ParamNotFound { attr, .. }
            | InvalidParamValue { attr, .. }
            | UnsupportedFormat { attr, .. }
            | UnexpectedTrailingItem { attr, .. }
            | Other { attr, .. } => *attr = new_attr.to_string(),
        }
    }
}

pub(crate) trait ErrorContext {
    fn with_param_context(self, param_context: &str) -> Self;
    fn with_attr(self, new_attr: impl ToString) -> Self;
}

impl<T> ErrorContext for Result<T, AttributeError> {
    /// Returns this error with the provided `param_context` prepended to the parameter field if applicable
    fn with_param_context(self, param_context: &str) -> Self {
        self.map_err(|mut err| {
            err.add_param_context(param_context);
            err
        })
    }

    /// Returns this error with the attribute field set to new_attr
    fn with_attr(self, new_attr: impl ToString) -> Self {
        self.map_err(|mut err| {
            err.set_attr(new_attr);
            err
        })
    }
}

/// RtpMap Attribute
///
/// See [RFC 8866 Section 6.6](https://datatracker.ietf.org/doc/html/rfc8866#section-6.6) for more details
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RtpMap {
    /// Payload type, a numerical value between 0 and 127
    pub payload_type: u8,
    /// Name of the encoding
    // TODO: is it useful to have an enum for all known encoding?
    pub encoding_name: String,
    /// Clock rate
    pub clock_rate: u32,
    /// Encoding parameters.
    ///
    /// Currently used only for audio channel count
    pub encoding_params: Option<String>,
}

impl RtpMap {
    pub fn new(payload_type: u8, encoding_name: impl ToString, clock_rate: u32) -> Self {
        RtpMap {
            payload_type,
            encoding_name: encoding_name.to_string(),
            clock_rate,
            encoding_params: None,
        }
    }

    pub fn builder(
        payload_type: u8,
        encoding_name: impl ToString,
        clock_rate: u32,
    ) -> builders::RtpMap {
        builders::RtpMap::new(payload_type, encoding_name, clock_rate)
    }

    pub fn with_encoding_params(
        payload_type: u8,
        encoding_name: impl ToString,
        clock_rate: u32,
        encoding_params: impl ToString,
    ) -> Self {
        RtpMap {
            payload_type,
            encoding_name: encoding_name.to_string(),
            clock_rate,
            encoding_params: Some(encoding_params.to_string()),
        }
    }

    pub fn set_encoding_params(&mut self, encoding_params: impl ToString) {
        self.encoding_params = Some(encoding_params.to_string());
    }
}

impl FromStr for RtpMap {
    type Err = AttributeError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let Some((pt, rest)) = s.split_once(' ') else {
            return Err(AttributeError::UnsupportedFormat {
                val: s.to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        };

        let Ok(pt) = pt.parse::<u8>() else {
            return Err(AttributeError::InvalidParamValue {
                param: "Payload type".to_string(),
                val: pt.to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        };

        if pt > 127 {
            return Err(AttributeError::InvalidParamValue {
                param: "Payload type".to_string(),
                val: format!("{pt}(expected 0-127)"),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        }

        let mut i = rest.splitn(3, '/');
        let Some(encoding) = i.next() else {
            return Err(AttributeError::ParamNotFound {
                param: "Encoding name".to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        };

        let Some(clock_rate) = i.next() else {
            return Err(AttributeError::ParamNotFound {
                param: "Clock rate".to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        };

        let Ok(clock_rate) = clock_rate.parse::<u32>() else {
            return Err(AttributeError::InvalidParamValue {
                param: "Clock rate".to_string(),
                val: clock_rate.to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        };

        let params = i.next().map(String::from);

        Ok(Self {
            payload_type: pt,
            encoding_name: encoding.to_owned(),
            clock_rate,
            encoding_params: params,
        })
    }
}

impl Display for RtpMap {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{} {}/{}",
            self.payload_type, self.encoding_name, self.clock_rate
        )?;
        if let Some(params) = &self.encoding_params {
            f.write_char('/')?;
            f.write_str(params)?;
        }
        Ok(())
    }
}

impl TypedAttribute for RtpMap {
    const NAME: &'static str = "rtpmap";
}

/// Format specific parameters
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct FmtpParam {
    pub param: String,
    pub val: Option<String>,
}

impl FmtpParam {
    pub fn new(param: impl ToString) -> Self {
        FmtpParam {
            param: param.to_string(),
            val: None,
        }
    }

    pub fn builder(param: impl ToString) -> builders::FmtpParam {
        builders::FmtpParam::new(param)
    }

    pub fn with_value(param: impl ToString, value: impl ToString) -> Self {
        FmtpParam {
            param: param.to_string(),
            val: Some(value.to_string()),
        }
    }

    pub fn set_value(&mut self, value: impl ToString) {
        self.val = Some(value.to_string());
    }
}

/// Format Parameters
///
/// See [RFC 8866 Section 6.15](https://datatracker.ietf.org/doc/html/rfc8866#section-6.15) for more details
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Fmtp {
    /// Payload format
    pub fmt: u8,
    /// Format specific parameters
    // Multiple params are expected to be semicolon separated
    // Each param can be a 'key=value' pair or just single parameter
    pub format_specific_params: Vec<FmtpParam>,
}

impl Fmtp {
    pub fn new(fmt: u8) -> Self {
        Fmtp {
            fmt,
            format_specific_params: vec![],
        }
    }

    pub fn builder(fmt: u8) -> builders::Fmtp {
        builders::Fmtp::new(fmt)
    }

    pub fn add_format_specific_param(&mut self, format_specific_param: FmtpParam) {
        self.format_specific_params.push(format_specific_param)
    }

    pub fn add_format_specific_params(
        &mut self,
        format_specific_params: impl IntoIterator<Item = FmtpParam>,
    ) {
        self.format_specific_params.extend(format_specific_params)
    }
}

impl FromStr for Fmtp {
    type Err = AttributeError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let Some((fmt, rest)) = s.split_once(' ') else {
            return Err(AttributeError::UnsupportedFormat {
                val: s.to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        };

        let Ok(fmt) = fmt.parse::<u8>() else {
            return Err(AttributeError::InvalidParamValue {
                param: "fmtp".to_string(),
                val: fmt.to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        };

        let mut params: Vec<FmtpParam> = Vec::new();
        for param in rest.split(';') {
            if let Some((key, value)) = param.split_once('=') {
                params.push(FmtpParam {
                    param: key.to_string(),
                    val: Some(value.to_string()),
                });
            } else {
                params.push(FmtpParam {
                    param: param.to_string(),
                    val: None,
                });
            }
        }

        Ok(Self {
            fmt,
            format_specific_params: params,
        })
    }
}

impl Display for Fmtp {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{} ", self.fmt)?;
        let mut iter = self.format_specific_params.iter().peekable();
        while let Some(p) = iter.next() {
            write!(f, "{}", p.param)?;
            if let Some(val) = &p.val {
                f.write_char('=')?;
                f.write_str(val.as_str())?;
            }
            if iter.peek().is_some() {
                f.write_char(';')?;
            }
        }
        Ok(())
    }
}

impl TypedAttribute for Fmtp {
    const NAME: &'static str = "fmtp";
}

/// RTCP port number and address
///
/// To be used if not algorithmically derived
/// from the RTP port described in the media line
///
/// See [RFC 3605 Section 2.1](https://datatracker.ietf.org/doc/html/rfc3605#section-2.1)
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Rtcp {
    /// Port used for the RTCP stream
    pub port: u16,
    /// Network Type
    pub nettype: NetType,
    /// Address type
    pub addrtype: AddrType,
    /// Connection address: can be IP Address, unicast, multicast, ...
    /// Conformity may be checked against the `addrtype`.
    pub connection_address: String,
}

impl Rtcp {
    /// Construct an [`Rtcp`] with the specified IP `connection_address`
    pub fn with_ip_addr(port: u16, connection_address: impl Into<IpAddr>) -> Self {
        let connection_address = connection_address.into();
        Rtcp {
            port,
            nettype: NetType::In,
            addrtype: connection_address.into(),
            connection_address: connection_address.to_string(),
        }
    }

    /// Construct an [`Rtcp`]
    ///
    /// See also [`Rtcp::with_ip_addr`]
    pub fn new(
        port: u16,
        nettype: NetType,
        addrtype: AddrType,
        connection_address: impl ToString,
    ) -> Self {
        Rtcp {
            port,
            nettype,
            addrtype,
            connection_address: connection_address.to_string(),
        }
    }

    /// Tries to parse the `connection_address` `String` of `self` as `IpAddr`
    ///
    /// Returns the `Ok` with the parsed `IpAddr` or `Err` with the string address
    /// if parsing failed.
    pub fn try_parse_connection_ip_address(&self) -> Result<IpAddr, &str> {
        self.connection_address
            .parse::<IpAddr>()
            .map_err(|_| self.connection_address.as_str())
    }

    /// Sets the `connection_address` & `addrtype` of `self` from the specified `IpAddr`
    pub fn set_connection_ip_address(&mut self, connection_address: impl Into<IpAddr>) {
        let connection_address = connection_address.into();
        self.addrtype = connection_address.into();
        self.connection_address = connection_address.to_string();
    }
}

impl FromStr for Rtcp {
    type Err = AttributeError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut i = s.split(' ');
        let Some(port) = i.next() else {
            return Err(AttributeError::ParamNotFound {
                param: "Port".to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        };

        let Ok(port) = port.parse::<u16>() else {
            return Err(AttributeError::InvalidParamValue {
                param: "Port".to_string(),
                val: port.to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        };

        let Some(nettype) = i.next() else {
            return Err(AttributeError::ParamNotFound {
                param: "Network type".to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        };

        let Ok(nettype) = NetType::from_str(nettype) else {
            return Err(AttributeError::InvalidParamValue {
                param: "Network type".to_string(),
                val: nettype.to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        };

        let Some(addrtype) = i.next() else {
            return Err(AttributeError::ParamNotFound {
                param: "Address type".to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        };

        let Ok(addrtype) = AddrType::from_str(addrtype) else {
            return Err(AttributeError::InvalidParamValue {
                param: "Address type".to_string(),
                val: addrtype.to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        };

        let Some(connection_address) = i.next() else {
            return Err(AttributeError::ParamNotFound {
                param: "Connection address".to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        };

        if let Some(unexpected) = i.next() {
            return Err(AttributeError::UnexpectedTrailingItem {
                val: unexpected.to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        }

        Ok(Self {
            port,
            nettype,
            addrtype,
            connection_address: connection_address.to_string(),
        })
    }
}

impl Display for Rtcp {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{} {} {} {}",
            self.port, self.nettype, self.addrtype, self.connection_address
        )
    }
}

impl TypedAttribute for Rtcp {
    const NAME: &'static str = "rtcp";
}

/// RTCP Feedback Capability
///
/// See [RFC 4585 Section 4.2](https://datatracker.ietf.org/doc/html/rfc4585#section-4.2)
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RtcpFb {
    /// Payload format for which feedback messages may be used
    pub pt: RtcpFbPt,
    /// RTCP Feedback value
    pub val: RtcpFbVal,
}

impl RtcpFb {
    pub fn new(pt: impl Into<RtcpFbPt>, val: impl Into<RtcpFbVal>) -> Self {
        RtcpFb {
            pt: pt.into(),
            val: val.into(),
        }
    }
}

impl FromStr for RtcpFb {
    type Err = AttributeError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut i = s.split(' ');
        let Some(pt) = i.next() else {
            return Err(AttributeError::ParamNotFound {
                param: "Payload format".to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        };

        let pt = if let Ok(pt) = pt.parse::<u8>() {
            RtcpFbPt::Fmt(pt)
        } else if pt == "*" {
            RtcpFbPt::Wildcard
        } else {
            return Err(AttributeError::InvalidParamValue {
                param: "Payload format".to_string(),
                val: pt.to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        };

        let Some(val) = i.next() else {
            return Err(AttributeError::ParamNotFound {
                param: "Rtcp feedback value".to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        };

        let rtcp_fb_val = match val {
            "ack" => {
                if let Some(ack_val) = i.next() {
                    let ack_val = match ack_val {
                        "rpsi" => RtcpFbAck::Rpsi,
                        "app" => {
                            if let Some(app_param) = i.next() {
                                RtcpFbAck::App(Some(app_param.to_string()))
                            } else {
                                RtcpFbAck::App(None)
                            }
                        }
                        "ccfb" => {
                            // The payload type used with "ccfb" feedback MUST be the wildcard type
                            // See https://datatracker.ietf.org/doc/html/rfc8888#section-6
                            if let RtcpFbPt::Fmt(pt) = pt {
                                return Err(AttributeError::InvalidParamValue {
                                    param: "Payload type of Congestion control feedback (ccfb)"
                                        .to_string(),
                                    val: format!("{pt}(expected wildcard (*))"),
                                    attr: <Self as TypedAttribute>::NAME.to_string(),
                                });
                            } else {
                                RtcpFbAck::Ccfb
                            }
                        }
                        other => RtcpFbAck::Other(other.to_string()),
                    };
                    RtcpFbVal::Ack(Some(ack_val))
                } else {
                    RtcpFbVal::Ack(None)
                }
            }
            "nack" => {
                if let Some(nack_val) = i.next() {
                    let nack_val = match nack_val {
                        "pli" => RtcpFbNack::Pli,
                        "sli" => RtcpFbNack::Sli,
                        "rpsi" => RtcpFbNack::Rpsi,
                        "app" => {
                            if let Some(app_param) = i.next() {
                                RtcpFbNack::App(Some(app_param.to_string()))
                            } else {
                                RtcpFbNack::App(None)
                            }
                        }
                        "ecn" => RtcpFbNack::Ecn,
                        other => RtcpFbNack::Other(other.to_string()),
                    };
                    RtcpFbVal::Nack(Some(nack_val))
                } else {
                    RtcpFbVal::Nack(None)
                }
            }
            "trr-int" => {
                if let Some(val) = i.next() {
                    let Ok(i) = val.parse::<u64>() else {
                        return Err(AttributeError::InvalidParamValue {
                            param: "Minimum interval between RTCP packets (trr-int)".to_string(),
                            val: val.to_string(),
                            attr: <Self as TypedAttribute>::NAME.to_string(),
                        });
                    };
                    RtcpFbVal::TrrInt(i)
                } else {
                    return Err(AttributeError::Other {
                        error: "Minimum interval between RTCP packets (trr-int) not specified"
                            .to_string(),
                        attr: <Self as TypedAttribute>::NAME.to_string(),
                    });
                }
            }
            "ccm" => {
                if let Some(ccm_val) = i.next() {
                    let ccm_val = match ccm_val {
                        "fir" => RtcpFbCcm::Fir,
                        "tmmbr" => {
                            if let Some(tmmbr_val) = i.next() {
                                RtcpFbCcm::Tmmbr(Some(tmmbr_val.to_string()))
                            } else {
                                RtcpFbCcm::Tmmbr(None)
                            }
                        }
                        "tstr" => RtcpFbCcm::Tstr,
                        "vbcm" => {
                            let mut v = vec![];
                            for vbcm_val in i {
                                let Ok(p) = vbcm_val.parse::<u8>() else {
                                    return Err(AttributeError::InvalidParamValue {
                                        param: "Video backchannel messages (vbcm)".to_string(),
                                        val: vbcm_val.to_string(),
                                        attr: <Self as TypedAttribute>::NAME.to_string(),
                                    });
                                };
                                v.push(p);
                            }
                            RtcpFbCcm::Vbcm(v)
                        }
                        other => RtcpFbCcm::Other(other.to_string()),
                    };
                    RtcpFbVal::Ccm(ccm_val)
                } else {
                    return Err(AttributeError::ParamNotFound {
                        param: "Codec control messages (ccm)".to_string(),
                        attr: <Self as TypedAttribute>::NAME.to_string(),
                    });
                }
            }
            "transport-cc" => RtcpFbVal::TransportCc,
            other => RtcpFbVal::Other(other.to_string()),
        };

        Ok(Self {
            pt,
            val: rtcp_fb_val,
        })
    }
}

impl Display for RtcpFb {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.pt {
            RtcpFbPt::Wildcard => f.write_char('*')?,
            RtcpFbPt::Fmt(pt) => write!(f, "{pt}")?,
        }

        f.write_char(' ')?;
        write!(f, "{}", self.val)
    }
}

impl TypedAttribute for RtcpFb {
    const NAME: &'static str = "rtcp-fb";
}

/// Media Direction Attributes
///
/// See [RFC 8866 Section 6.7](https://datatracker.ietf.org/doc/html/rfc8866#section-6.7)
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Direction {
    #[default]
    SendRecv,
    SendOnly,
    RecvOnly,
    Inactive,
}

impl Direction {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::SendOnly => "sendonly",
            Self::RecvOnly => "recvonly",
            Self::SendRecv => "sendrecv",
            Self::Inactive => "inactive",
        }
    }

    pub fn has_send(self) -> bool {
        matches!(self, Self::SendRecv | Self::SendOnly)
    }

    pub fn has_recv(self) -> bool {
        matches!(self, Self::SendRecv | Self::RecvOnly)
    }

    pub fn reverse(self) -> Self {
        match self {
            Self::SendRecv => Self::SendRecv,
            Self::SendOnly => Self::RecvOnly,
            Self::RecvOnly => Self::SendOnly,
            Self::Inactive => Self::Inactive,
        }
    }

    pub fn intersect_with_remote(self, remote: Self) -> Self {
        match (self, remote) {
            (Self::Inactive, _)
            | (_, Self::Inactive)
            | (Self::RecvOnly, Self::RecvOnly)
            | (Self::SendOnly, Self::SendOnly) => Self::Inactive,
            (Self::SendRecv, Self::SendRecv) => Self::SendRecv,
            (Self::SendOnly, Self::RecvOnly | Self::SendRecv)
            | (Self::SendRecv, Self::RecvOnly) => Self::SendOnly,
            (Self::RecvOnly, Self::SendRecv | Self::SendOnly)
            | (Self::SendRecv, Self::SendOnly) => Self::RecvOnly,
        }
    }
}

impl FromStr for Direction {
    type Err = ParseEnumError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if "sendonly".eq_ignore_ascii_case(s) {
            Ok(Direction::SendOnly)
        } else if "recvonly".eq_ignore_ascii_case(s) {
            Ok(Direction::RecvOnly)
        } else if "sendrecv".eq_ignore_ascii_case(s) {
            Ok(Direction::SendRecv)
        } else if "inactive".eq_ignore_ascii_case(s) {
            Ok(Direction::Inactive)
        } else {
            Err(ParseEnumError::Invalid(s.to_string()))
        }
    }
}

impl Display for Direction {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

impl From<Direction> for Attribute {
    fn from(attr: Direction) -> Attribute {
        Attribute {
            attribute: attr.to_string(),
            value: None,
        }
    }
}

/// RTP header extensions map
///
/// See [RFC 8285 Section 8](https://datatracker.ietf.org/doc/html/rfc8285#section-8)
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ExtMap {
    /// The local identifier (ID) of this extension
    pub id: u8,
    /// Direction
    pub direction: Option<Direction>,
    /// The format and meaning of the extension
    pub uri: String,
    /// Extension attributes
    pub attributes: Option<String>,
}

impl ExtMap {
    pub fn new(id: u8, uri: impl ToString) -> Self {
        ExtMap {
            id,
            direction: None,
            uri: uri.to_string(),
            attributes: None,
        }
    }

    pub fn builder(id: u8, uri: impl ToString) -> builders::ExtMap {
        builders::ExtMap::new(id, uri)
    }

    pub fn with_direction(id: u8, direction: Direction, uri: impl ToString) -> Self {
        ExtMap {
            id,
            direction: Some(direction),
            uri: uri.to_string(),
            attributes: None,
        }
    }

    pub fn with_direction_and_attributes(
        id: u8,
        direction: Direction,
        uri: impl ToString,
        attributes: impl ToString,
    ) -> Self {
        ExtMap {
            id,
            direction: Some(direction),
            uri: uri.to_string(),
            attributes: Some(attributes.to_string()),
        }
    }

    pub fn set_direction(&mut self, direction: Direction) {
        self.direction = Some(direction);
    }

    pub fn set_attributes(&mut self, attributes: impl ToString) {
        self.attributes = Some(attributes.to_string());
    }
}

impl FromStr for ExtMap {
    type Err = AttributeError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut i = s.splitn(3, ' ');

        let Some(id_direction) = i.next() else {
            return Err(AttributeError::ParamNotFound {
                param: "id/direction".to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        };

        let mut d = id_direction.split('/');

        let Some(id) = d.next() else {
            return Err(AttributeError::ParamNotFound {
                param: "id".to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        };

        let direction = if let Some(d) = d.next() {
            let Ok(dir) = Direction::from_str(d) else {
                return Err(AttributeError::InvalidParamValue {
                    param: "Direction".to_string(),
                    val: d.to_string(),
                    attr: <Self as TypedAttribute>::NAME.to_string(),
                });
            };
            Some(dir)
        } else {
            None
        };

        let Ok(id) = id.parse::<u8>() else {
            return Err(AttributeError::InvalidParamValue {
                param: "Id".to_string(),
                val: id.to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        };

        if id == 0 {
            return Err(AttributeError::InvalidParamValue {
                param: "Id".to_string(),
                val: id.to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        }

        let Some(uri) = i.next() else {
            return Err(AttributeError::ParamNotFound {
                param: "URI".to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        };

        let attributes = i.next().map(|attr| attr.to_string());

        Ok(Self {
            id,
            direction,
            uri: uri.to_string(),
            attributes,
        })
    }
}

impl Display for ExtMap {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.id)?;
        if let Some(direction) = &self.direction {
            f.write_char('/')?;
            f.write_str(direction.as_str())?;
        }

        f.write_char(' ')?;
        f.write_str(&self.uri)?;

        if let Some(attr) = &self.attributes {
            f.write_char(' ')?;
            f.write_str(attr.as_str())?;
        }
        Ok(())
    }
}

impl TypedAttribute for ExtMap {
    const NAME: &'static str = "extmap";
}

/// Fingerprint Attribute
///
/// See [RFC 8122 Section 5](https://datatracker.ietf.org/doc/html/rfc8122#section-5)
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Fingerprint {
    /// Name of hash function used
    pub hash_func: HashFunc,
    /// Hash value
    pub fingerprint: Vec<u8>,
}

impl Fingerprint {
    pub fn new(hash_func: HashFunc) -> Self {
        Fingerprint {
            hash_func,
            fingerprint: vec![],
        }
    }

    pub fn with_fingerprint(
        hash_func: HashFunc,
        fingerprint: impl IntoIterator<Item = u8>,
    ) -> Self {
        Fingerprint {
            hash_func,
            fingerprint: std::iter::FromIterator::from_iter(fingerprint),
        }
    }

    pub fn set_fingerprint(&mut self, fingerprint: impl IntoIterator<Item = u8>) {
        self.fingerprint.clear();
        self.fingerprint.extend(fingerprint);
    }
}

impl FromStr for Fingerprint {
    type Err = AttributeError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut i = s.splitn(2, ' ');

        let hash_func = if let Some(hash_func) = i.next() {
            HashFunc::new(hash_func)
        } else {
            return Err(AttributeError::ParamNotFound {
                param: "Hash function".to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        };

        let mut fingerprint: Vec<u8> = vec![];
        if let Some(fp) = i.next() {
            for f in fp.split(':') {
                let Ok(mut f) = hex::decode(f) else {
                    return Err(AttributeError::InvalidParamValue {
                        param: "Fingerprint value".to_string(),
                        val: f.to_string(),
                        attr: <Self as TypedAttribute>::NAME.to_string(),
                    });
                };

                fingerprint.append(&mut f);
            }
        } else {
            return Err(AttributeError::ParamNotFound {
                param: "Hash value".to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        };

        Ok(Self {
            hash_func,
            fingerprint,
        })
    }
}

impl Display for Fingerprint {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.hash_func.as_str())?;
        let mut first = true;
        for v in &self.fingerprint {
            if first {
                f.write_char(' ')?;
                first = false;
            } else {
                f.write_char(':')?;
            }
            write!(f, "{v:02X}")?;
        }
        Ok(())
    }
}

impl TypedAttribute for Fingerprint {
    const NAME: &'static str = "fingerprint";
}

/// Group Attribute
///
/// See [RFC 5888 Section 5](https://datatracker.ietf.org/doc/html/rfc5888#section-5)
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Group {
    pub semantics: GroupSemantics,
    pub mid_tags: Vec<String>,
}

impl Group {
    pub fn new(semantics: GroupSemantics) -> Self {
        Group {
            semantics,
            mid_tags: vec![],
        }
    }

    pub fn add_mid_tag(&mut self, mid_tag: impl ToString) {
        self.mid_tags.push(mid_tag.to_string())
    }

    pub fn add_mid_tags(&mut self, mid_tags: impl IntoIterator<Item = impl ToString>) {
        self.mid_tags
            .extend(mid_tags.into_iter().map(|i| i.to_string()))
    }
}

impl FromStr for Group {
    type Err = AttributeError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut i = s.split(' ');

        let Some(semantics) = i.next() else {
            return Err(AttributeError::ParamNotFound {
                param: "Semantics".to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        };

        let semantics = GroupSemantics::new(semantics);

        let mut mid_tags = vec![];
        for mid in i {
            mid_tags.push(mid.to_string());
        }

        if mid_tags.is_empty() {
            return Err(AttributeError::ParamNotFound {
                param: "Media identification tags".to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        }

        Ok(Self {
            semantics,
            mid_tags,
        })
    }
}

impl Display for Group {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.semantics.as_str())?;
        for m in &self.mid_tags {
            f.write_char(' ')?;
            f.write_str(m)?;
        }
        Ok(())
    }
}

impl TypedAttribute for Group {
    const NAME: &'static str = "group";
}

/// Setup attribute for the session or media.
///
/// See [RFC 4145 Section 4](https://datatracker.ietf.org/doc/html/rfc4145#section-4) for more details.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Setup {
    /// Initiator of the connection.
    Active,
    /// Acceptor of the connection.
    Passive,
    /// Act as either initiator or acceptor of the connection.
    ActPass,
    /// Do not establish a connection.
    HoldConn,
}

impl FromStr for Setup {
    type Err = AttributeError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if "active".eq_ignore_ascii_case(s) {
            Ok(Setup::Active)
        } else if "passive".eq_ignore_ascii_case(s) {
            Ok(Setup::Passive)
        } else if "actpass".eq_ignore_ascii_case(s) {
            Ok(Setup::ActPass)
        } else if "holdconn".eq_ignore_ascii_case(s) {
            Ok(Setup::HoldConn)
        } else {
            Err(AttributeError::Other {
                error: format!("Invalid Setup value {s}"),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            })
        }
    }
}

impl Display for Setup {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let s = match self {
            Setup::Active => "active",
            Setup::Passive => "passive",
            Setup::ActPass => "actpass",
            Setup::HoldConn => "holdconn",
        };
        f.write_str(s)
    }
}

impl TypedAttribute for Setup {
    const NAME: &'static str = "setup";
}

/// SSRC media attribute.
///
/// See [RFC 5576 Section 4.1](https://datatracker.ietf.org/doc/html/rfc5576#section-4.1)
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Ssrc {
    pub ssrc_id: u32,
    pub attribute: SsrcAttribute,
    pub value: Option<String>,
}

impl Ssrc {
    pub fn new(ssrc_id: u32, attribute: SsrcAttribute) -> Self {
        Ssrc {
            ssrc_id,
            attribute,
            value: None,
        }
    }

    pub fn with_typed_attribute(ssrc_id: u32, attribute: impl TypedAttribute) -> Self {
        let value = attribute.to_string();
        Ssrc {
            ssrc_id,
            attribute: SsrcAttribute::from(attribute),
            value: Some(value),
        }
    }

    pub fn with_value(ssrc_id: u32, attribute: SsrcAttribute, value: impl ToString) -> Self {
        Ssrc {
            ssrc_id,
            attribute,
            value: Some(value.to_string()),
        }
    }

    pub fn set_value(&mut self, value: impl ToString) {
        self.value = Some(value.to_string());
    }

    /// Gets the inner attribute as a `TypedAttribute`.
    ///
    /// # Errors
    ///
    /// * `AttributeError::Other` if the inner attribute doesn't match
    ///   the specified `TypedAttribute` or if the value is empty.
    /// * a specific `AttributeError` if the typed attribute couldn't be built.
    pub fn get_typed<T: TypedAttribute>(&self) -> Result<T, AttributeError> {
        if !self.attribute.as_str().eq_ignore_ascii_case(T::NAME) {
            return Err(AttributeError::Other {
                error: format!("Attribute type mismatch (requested {})", T::NAME),
                attr: self.attribute.as_str().to_string(),
            });
        }

        let Some(ref value) = self.value else {
            return Err(AttributeError::Other {
                error: "No value for the attribute".to_string(),
                attr: T::NAME.to_string(),
            });
        };

        T::from_str(value)
    }
}

impl FromStr for Ssrc {
    type Err = AttributeError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let Some((ssrc_id_str, rest)) = s.split_once(' ') else {
            return Err(AttributeError::ParamNotFound {
                param: "Ssrc id".to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        };

        let Ok(ssrc_id) = ssrc_id_str.parse::<u32>() else {
            return Err(AttributeError::InvalidParamValue {
                param: "Ssrc id".to_string(),
                val: ssrc_id_str.to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        };

        let (attr, value) = if let Some((attr_str, value)) = rest.split_once(':') {
            (attr_str, Some(value.to_string()))
        } else {
            (rest, None)
        };

        Ok(Self {
            ssrc_id,
            attribute: SsrcAttribute::new(attr),
            value,
        })
    }
}

impl Display for Ssrc {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        use crate::{Fmtp, MediaClockSource, ReferenceClock, Rtcp};

        let attr_str = match &self.attribute {
            SsrcAttribute::Cname => "cname",
            SsrcAttribute::PreviousSsrc => "previous-ssrc",
            SsrcAttribute::Fmtp => <Fmtp as TypedAttribute>::NAME,
            SsrcAttribute::Rtcp => <Rtcp as TypedAttribute>::NAME,
            SsrcAttribute::ReferenceClock => <ReferenceClock as TypedAttribute>::NAME,
            SsrcAttribute::MediaClockSource => <MediaClockSource as TypedAttribute>::NAME,
            SsrcAttribute::Other(other) => other.as_str(),
        };
        write!(f, "{} {attr_str}", self.ssrc_id)?;

        if let Some(value) = &self.value {
            f.write_char(':')?;
            f.write_str(value)?;
        }

        Ok(())
    }
}

impl TypedAttribute for Ssrc {
    const NAME: &'static str = "ssrc";
}

/// SSRC group attribute
///
/// See [RFC 5576 Section 4.2](https://datatracker.ietf.org/doc/html/rfc5576#section-4.2)
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SsrcGroup {
    pub semantics: GroupSemantics,
    pub ssrc_ids: Vec<u32>,
}

impl SsrcGroup {
    pub fn new(semantics: GroupSemantics) -> Self {
        SsrcGroup {
            semantics,
            ssrc_ids: vec![],
        }
    }

    pub fn add_ssrc_id(&mut self, ssrc_id: u32) {
        self.ssrc_ids.push(ssrc_id)
    }

    pub fn add_ssrc_ids(&mut self, ssrc_ids: impl IntoIterator<Item = u32>) {
        self.ssrc_ids.extend(ssrc_ids)
    }
}

impl FromStr for SsrcGroup {
    type Err = AttributeError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut i = s.split(' ');

        let Some(semantics) = i.next() else {
            return Err(AttributeError::ParamNotFound {
                param: "Semantics".to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        };

        let semantics = if "FEC".eq_ignore_ascii_case(semantics) {
            GroupSemantics::FEC
        } else if "FID".eq_ignore_ascii_case(semantics) {
            GroupSemantics::FID
        } else {
            // The initial defined semantics for ssrc-group attribute are FID and FEC
            // The other registered group semantics are not useful for source grouping
            // But keep this open for any other new semantics that are not part of GroupSemantics
            GroupSemantics::Other(semantics.to_string())
        };

        let mut ssrc_ids = vec![];
        for ssrc_id in i {
            let Ok(ssrc_id) = ssrc_id.parse::<u32>() else {
                return Err(AttributeError::InvalidParamValue {
                    param: "Ssrc id".to_string(),
                    val: ssrc_id.to_string(),
                    attr: <Self as TypedAttribute>::NAME.to_string(),
                });
            };
            ssrc_ids.push(ssrc_id);
        }

        if ssrc_ids.is_empty() {
            return Err(AttributeError::ParamNotFound {
                param: "ssrc_id".to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        }

        Ok(Self {
            semantics,
            ssrc_ids,
        })
    }
}

impl Display for SsrcGroup {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let sem = match &self.semantics {
            GroupSemantics::FEC => "FEC",
            GroupSemantics::FID => "FID",
            // Semantics other than FEC and FID are not useful for source grouping but still displaying
            // them for debugging purpose
            GroupSemantics::LS => "LS",
            GroupSemantics::SRF => "SRF",
            GroupSemantics::ANAT => "ANAT",
            GroupSemantics::DDP => "DDP",
            GroupSemantics::Other(s) => s.as_str(),
        };

        f.write_str(sem)?;
        for ssrc_id in &self.ssrc_ids {
            f.write_char(' ')?;
            write!(f, "{ssrc_id}")?;
        }

        Ok(())
    }
}

impl TypedAttribute for SsrcGroup {
    const NAME: &'static str = "ssrc-group";
}

/// SRTP Key parameter
///
/// See [RFC 4568 Section 6.1](https://datatracker.ietf.org/doc/html/rfc4568#section-6.1)
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SrtpKeyParam {
    /// Concatenated key and salt, base64 encoded
    pub key_and_salt: String,
    /// Master key lifetime (max number of SRTP or SRTCP packets using this master key)
    pub lifetime: Option<u32>,
    /// MKI (Master Key Identifier) and length of the MKI field in SRTP packets
    pub mki_and_length: Option<(u32, u32)>,
}

impl SrtpKeyParam {
    pub fn new(key_and_salt: impl ToString) -> Self {
        SrtpKeyParam {
            key_and_salt: key_and_salt.to_string(),
            lifetime: None,
            mki_and_length: None,
        }
    }

    pub fn with_lifetime(key_and_salt: impl ToString, lifetime: u32) -> Self {
        SrtpKeyParam {
            key_and_salt: key_and_salt.to_string(),
            lifetime: Some(lifetime),
            mki_and_length: None,
        }
    }

    pub fn with_lifetime_and_mki_and_length(
        key_and_salt: impl ToString,
        lifetime: u32,
        mki: u32,
        length: u32,
    ) -> Self {
        SrtpKeyParam {
            key_and_salt: key_and_salt.to_string(),
            lifetime: Some(lifetime),
            mki_and_length: Some((mki, length)),
        }
    }

    pub fn set_lifetime(&mut self, lifetime: u32) {
        self.lifetime = Some(lifetime);
    }

    pub fn set_mki_and_length(&mut self, mki: u32, length: u32) {
        self.mki_and_length = Some((mki, length));
    }
}

impl FromStr for SrtpKeyParam {
    type Err = AttributeError;
    fn from_str(key_param: &str) -> Result<Self, Self::Err> {
        let mut k = key_param.split('|');

        let Some(key_and_salt_with_method) = k.next() else {
            return Err(AttributeError::ParamNotFound {
                param: "Srtp Key and Salt".to_string(),
                attr: Crypto::NAME.to_string(),
            });
        };

        let key_and_salt = if key_and_salt_with_method
            .get(..7)
            .is_some_and(|p| p.eq_ignore_ascii_case("inline:"))
        {
            &key_and_salt_with_method[7..]
        } else {
            return Err(AttributeError::InvalidParamValue {
                param: "Srtp Key and Salt".to_string(),
                val: key_and_salt_with_method.to_string(),
                attr: Crypto::NAME.to_string(),
            });
        };

        let (lifetime, mki_and_length) = if let Some(next_param) = k.next() {
            match next_param.split_once(':') {
                Some(mki_and_length) => {
                    // lifetime is not specified, but only MKI and its length
                    let Ok(mki) = mki_and_length.0.parse::<u32>() else {
                        return Err(AttributeError::InvalidParamValue {
                            param: "MKI".to_string(),
                            val: next_param.to_string(),
                            attr: Crypto::NAME.to_string(),
                        });
                    };

                    let Ok(len) = mki_and_length.1.parse::<u32>() else {
                        return Err(AttributeError::InvalidParamValue {
                            param: "Length".to_string(),
                            val: next_param.to_string(),
                            attr: Crypto::NAME.to_string(),
                        });
                    };
                    (None, Some((mki, len)))
                }
                None => {
                    // lifetime is specified
                    let lifetime = match next_param.strip_prefix("2^") {
                        Some(exp) => {
                            let Ok(exp) = exp.parse::<u32>() else {
                                return Err(AttributeError::InvalidParamValue {
                                    param: "Lifetime".to_string(),
                                    val: next_param.to_string(),
                                    attr: Crypto::NAME.to_string(),
                                });
                            };
                            // 2u32.pow(exp) panics for exp >= 32
                            if exp >= 32 {
                                return Err(AttributeError::InvalidParamValue {
                                    param: "Lifetime".to_string(),
                                    val: format!("{exp}(expected 0-32)"),
                                    attr: Crypto::NAME.to_string(),
                                });
                            }
                            Some(2u32.pow(exp))
                        }
                        None => {
                            let Ok(lifetime) = next_param.parse::<u32>() else {
                                return Err(AttributeError::InvalidParamValue {
                                    param: "Lifetime".to_string(),
                                    val: next_param.to_string(),
                                    attr: Crypto::NAME.to_string(),
                                });
                            };
                            Some(lifetime)
                        }
                    };

                    // now parse the MKI and length
                    let mki_and_length = if let Some(m) = k.next() {
                        if let Some(p) = m.split_once(':') {
                            let Ok(mki) = p.0.parse::<u32>() else {
                                return Err(AttributeError::InvalidParamValue {
                                    param: "MKI".to_string(),
                                    val: m.to_string(),
                                    attr: Crypto::NAME.to_string(),
                                });
                            };

                            let Ok(len) = p.1.parse::<u32>() else {
                                return Err(AttributeError::InvalidParamValue {
                                    param: "Length".to_string(),
                                    val: m.to_string(),
                                    attr: Crypto::NAME.to_string(),
                                });
                            };
                            Some((mki, len))
                        } else {
                            return Err(AttributeError::ParamNotFound {
                                param: "MKI and Length".to_string(),
                                attr: Crypto::NAME.to_string(),
                            });
                        }
                    } else {
                        None
                    };

                    (lifetime, mki_and_length)
                }
            }
        } else {
            (None, None)
        };

        if let Some((_, len)) = mki_and_length {
            if !(1..=128).contains(&len) {
                return Err(AttributeError::InvalidParamValue {
                    param: "MKI length".to_string(),
                    val: len.to_string(),
                    attr: Crypto::NAME.to_string(),
                });
            }
        }

        if let Some(unexpected) = k.next() {
            return Err(AttributeError::UnexpectedTrailingItem {
                val: unexpected.to_string(),
                attr: Crypto::NAME.to_string(),
            });
        }

        Ok(Self {
            key_and_salt: key_and_salt.to_string(),
            lifetime,
            mki_and_length,
        })
    }
}

impl Display for SrtpKeyParam {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "inline:{}", self.key_and_salt)?;
        if let Some(lifetime) = self.lifetime {
            if lifetime.is_power_of_two() {
                write!(f, "|2^{}", lifetime.trailing_zeros())?;
            } else {
                write!(f, "|{lifetime}")?;
            }
        }
        if let Some((mki, length)) = self.mki_and_length {
            write!(f, "|{mki}:{length}")?;
        }
        Ok(())
    }
}

/// Cryptographic information for the media
///
/// See [RFC 4568 Section 4](https://datatracker.ietf.org/doc/html/rfc4568#section-4)
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Crypto {
    pub tag: u32,
    pub crypto_suite: CryptoSuite,
    pub key_params: Vec<SrtpKeyParam>,
    pub session_params: Vec<SrtpSessionParam>,
}

impl Crypto {
    pub fn new(tag: u32, crypto_suite: CryptoSuite) -> Self {
        Crypto {
            tag,
            crypto_suite,
            key_params: vec![],
            session_params: vec![],
        }
    }

    pub fn add_key_param(&mut self, key_param: SrtpKeyParam) {
        self.key_params.push(key_param)
    }

    pub fn add_key_params(&mut self, key_params: impl IntoIterator<Item = SrtpKeyParam>) {
        self.key_params.extend(key_params)
    }

    pub fn add_session_param(&mut self, session_param: SrtpSessionParam) {
        self.session_params.push(session_param)
    }

    pub fn add_session_params(
        &mut self,
        session_params: impl IntoIterator<Item = SrtpSessionParam>,
    ) {
        self.session_params.extend(session_params)
    }
}

impl FromStr for Crypto {
    type Err = AttributeError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut i = s.split(' ');

        let Some(tag) = i.next() else {
            return Err(AttributeError::ParamNotFound {
                param: "Tag".to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        };

        let Ok(tag) = tag.parse::<u32>() else {
            return Err(AttributeError::InvalidParamValue {
                param: "Tag".to_string(),
                val: tag.to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        };

        let Some(crypto_suite) = i.next() else {
            return Err(AttributeError::ParamNotFound {
                param: "CryptoSuite".to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        };

        let crypto_suite = CryptoSuite::new(crypto_suite);

        let Some(key_params_str) = i.next() else {
            return Err(AttributeError::ParamNotFound {
                param: "Key params".to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        };

        let mut key_params: Vec<SrtpKeyParam> = Vec::new();

        for key_param in key_params_str.split(';') {
            let key_param = SrtpKeyParam::from_str(key_param)?;
            key_params.push(key_param);
        }

        let mut session_params: Vec<SrtpSessionParam> = Vec::new();
        for s in &mut i {
            let param = if s.get(..4).is_some_and(|p| p.eq_ignore_ascii_case("KDR=")) {
                let kdr_val = &s[4..];
                let Ok(kdr_val) = kdr_val.parse::<u8>() else {
                    return Err(AttributeError::InvalidParamValue {
                        param: "KDR".to_string(),
                        val: kdr_val.to_string(),
                        attr: <Self as TypedAttribute>::NAME.to_string(),
                    });
                };

                // Note: the range for KDR value is conflicting in the spec,
                // rfc4568#section-6.3.1 says the range should be 1,2,...24 and
                // the grammar in rfc4568#section-9.2 says it should be 0..24.
                // So using the bigger range i.e., 0..24 for now
                if !(0..=24).contains(&kdr_val) {
                    return Err(AttributeError::InvalidParamValue {
                        param: "KDR".to_string(),
                        val: format!("{kdr_val}(expected range 0..24)"),
                        attr: <Self as TypedAttribute>::NAME.to_string(),
                    });
                }
                SrtpSessionParam::Kdr(kdr_val)
            } else if s.eq_ignore_ascii_case("UNENCRYPTED_SRTCP") {
                SrtpSessionParam::UnencryptedSrtcp
            } else if s.eq_ignore_ascii_case("UNENCRYPTED_SRTP") {
                SrtpSessionParam::UnencryptedSrtp
            } else if s.eq_ignore_ascii_case("UNAUTHENTICATED_SRTP") {
                SrtpSessionParam::UnauthenticatedSrtp
            } else if s
                .get(..10)
                .is_some_and(|p| p.eq_ignore_ascii_case("FEC_ORDER="))
            {
                let fec_ord = &s[10..];
                if fec_ord.eq_ignore_ascii_case("FEC_SRTP") {
                    SrtpSessionParam::FecOrder(FecOrder::FecSrtp)
                } else if fec_ord.eq_ignore_ascii_case("SRTP_FEC") {
                    SrtpSessionParam::FecOrder(FecOrder::SrtpFec)
                } else {
                    return Err(AttributeError::InvalidParamValue {
                        param: "FEC order".to_string(),
                        val: s.to_string(),
                        attr: <Self as TypedAttribute>::NAME.to_string(),
                    });
                }
            } else if s
                .get(..8)
                .is_some_and(|p| p.eq_ignore_ascii_case("FEC_KEY="))
            {
                let key_params_str = &s[8..];
                let mut key_params: Vec<SrtpKeyParam> = Vec::new();

                for key_param in key_params_str.split(';') {
                    let key_param = SrtpKeyParam::from_str(key_param)?;
                    key_params.push(key_param);
                }
                SrtpSessionParam::FecKey(key_params)
            } else if s.get(..4).is_some_and(|p| p.eq_ignore_ascii_case("WSH=")) {
                let wsh_val = &s[4..];
                let Ok(wsh_val) = wsh_val.parse::<u8>() else {
                    return Err(AttributeError::InvalidParamValue {
                        param: "WSH".to_string(),
                        val: wsh_val.to_string(),
                        attr: <Self as TypedAttribute>::NAME.to_string(),
                    });
                };

                if wsh_val < 64 {
                    return Err(AttributeError::InvalidParamValue {
                        param: "WSH".to_string(),
                        val: wsh_val.to_string(),
                        attr: <Self as TypedAttribute>::NAME.to_string(),
                    });
                }
                SrtpSessionParam::Wsh(wsh_val)
            } else {
                // Extension
                SrtpSessionParam::Extension(s.to_string())
            };
            session_params.push(param);
        }

        Ok(Self {
            tag,
            key_params,
            crypto_suite,
            session_params,
        })
    }
}

impl Display for Crypto {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{} {}", self.tag, self.crypto_suite.as_str())?;

        for (i, key_param) in self.key_params.iter().enumerate() {
            if i == 0 {
                f.write_char(' ')?;
            } else {
                f.write_char(';')?;
            }

            write!(f, "{}", key_param)?;
        }

        for session_param in &self.session_params {
            match session_param {
                SrtpSessionParam::Kdr(kdr) => write!(f, " KDR={kdr}")?,
                SrtpSessionParam::UnencryptedSrtp => write!(f, " UNENCRYPTED_SRTP")?,
                SrtpSessionParam::UnencryptedSrtcp => write!(f, " UNENCRYPTED_SRTCP")?,
                SrtpSessionParam::UnauthenticatedSrtp => write!(f, " UNAUTHENTICATED_SRTP")?,
                SrtpSessionParam::FecOrder(fec_order) => {
                    let order = match fec_order {
                        FecOrder::FecSrtp => "FEC_SRTP",
                        FecOrder::SrtpFec => "SRTP_FEC",
                    };
                    write!(f, " FEC_ORDER={order}")?;
                }
                SrtpSessionParam::FecKey(srtp_key_params) => {
                    write!(f, " FEC_KEY")?;
                    for (i, key_param) in srtp_key_params.iter().enumerate() {
                        if i == 0 {
                            f.write_char('=')?;
                        } else {
                            f.write_char(';')?;
                        }

                        write!(f, "{}", key_param)?;
                    }
                }
                SrtpSessionParam::Wsh(wsh) => write!(f, " WSH={wsh}")?,
                SrtpSessionParam::Extension(extn) => {
                    f.write_char(' ')?;
                    f.write_str(extn)?;
                }
            }
        }
        Ok(())
    }
}

impl TypedAttribute for Crypto {
    const NAME: &'static str = "crypto";
}

/// ICE Candidate attribute of the media
///
/// See [RFC 8839 Section 5.1](https://datatracker.ietf.org/doc/html/rfc8839#section-5.1)
#[derive(Debug, PartialEq, Eq, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Candidate {
    /// Arbitrary string used in the freezing algorithm to group similar candidates
    /// See [RFC 8445 Section 5.1.1.3](https://datatracker.ietf.org/doc/html/rfc8445#section-5.1.1.3)
    pub foundation: String,
    /// Identifies the specific component of the data stream
    /// 1 for RTP and 2 for RTCP
    pub component_id: u32,
    /// Transport protocol of the candidate
    pub transport: String,
    /// Candidate's priority
    pub priority: u64,
    /// IP address of the candidate
    /// IPv4, IPv6 addresses and FQDN allowed
    pub address: CandidateAddress,
    /// Port of the candidate
    pub port: u16,
    /// Type of the candidate
    pub typ: CandidateType,
    /// Address related to the candidate
    /// Required for srflx, prflx and relay type candidates
    pub rel_addr: Option<IpAddr>,
    /// Port related to the candidate
    /// Required for srflx, prflx and relay type candidates
    pub rel_port: Option<u16>,
    /// Extensions
    pub extensions: Vec<(String, String)>,
}

impl Candidate {
    pub fn new(
        foundation: impl ToString,
        component_id: u32,
        transport: impl ToString,
        priority: u64,
        address: CandidateAddress,
        port: u16,
        typ: CandidateType,
    ) -> Self {
        Candidate {
            foundation: foundation.to_string(),
            component_id,
            transport: transport.to_string(),
            priority,
            address,
            port,
            typ,
            rel_addr: None,
            rel_port: None,
            extensions: vec![],
        }
    }

    #[allow(clippy::too_many_arguments)]
    pub fn with_rel_addr(
        foundation: impl ToString,
        component_id: u32,
        transport: impl ToString,
        priority: u64,
        address: CandidateAddress,
        port: u16,
        typ: CandidateType,
        rel_addr: impl Into<IpAddr>,
    ) -> Self {
        Candidate {
            foundation: foundation.to_string(),
            component_id,
            transport: transport.to_string(),
            priority,
            address,
            port,
            typ,
            rel_addr: Some(rel_addr.into()),
            rel_port: None,
            extensions: vec![],
        }
    }

    #[allow(clippy::too_many_arguments)]
    pub fn with_rel_addr_and_port(
        foundation: impl ToString,
        component_id: u32,
        transport: impl ToString,
        priority: u64,
        address: CandidateAddress,
        port: u16,
        typ: CandidateType,
        rel_addr: impl Into<IpAddr>,
        rel_port: u16,
    ) -> Self {
        Candidate {
            foundation: foundation.to_string(),
            component_id,
            transport: transport.to_string(),
            priority,
            address,
            port,
            typ,
            rel_addr: Some(rel_addr.into()),
            rel_port: Some(rel_port),
            extensions: vec![],
        }
    }

    pub fn set_rel_addr(&mut self, rel_addr: impl Into<IpAddr>) {
        self.rel_addr = Some(rel_addr.into());
    }

    pub fn set_rel_port(&mut self, rel_port: u16) {
        self.rel_port = Some(rel_port);
    }

    pub fn add_extension(&mut self, name: impl ToString, value: impl ToString) {
        self.extensions.push((name.to_string(), value.to_string()))
    }
}

impl FromStr for Candidate {
    type Err = AttributeError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut i = s.split(' ');

        let Some(foundation) = i.next() else {
            return Err(AttributeError::ParamNotFound {
                param: "Foundation".to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        };

        let Some(comp_id) = i.next() else {
            return Err(AttributeError::ParamNotFound {
                param: "Component id".to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        };

        let Ok(comp_id) = comp_id.parse::<u32>() else {
            return Err(AttributeError::InvalidParamValue {
                param: "Component id".to_string(),
                val: comp_id.to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        };

        let Some(transport) = i.next() else {
            return Err(AttributeError::ParamNotFound {
                param: "Transport".to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        };

        let Some(priority) = i.next() else {
            return Err(AttributeError::ParamNotFound {
                param: "Priority".to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        };

        let Ok(priority) = priority.parse::<u64>() else {
            return Err(AttributeError::InvalidParamValue {
                param: "Priority".to_string(),
                val: priority.to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        };

        let Some(address) = i.next() else {
            return Err(AttributeError::ParamNotFound {
                param: "Address".to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        };

        let address = match address.parse::<IpAddr>() {
            Ok(a) => CandidateAddress::IpAddr(a),
            Err(_) => CandidateAddress::FQDN(address.to_string()),
        };

        let Some(port) = i.next() else {
            return Err(AttributeError::ParamNotFound {
                param: "Port".to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        };

        let Ok(port) = port.parse::<u16>() else {
            return Err(AttributeError::InvalidParamValue {
                param: "Port".to_string(),
                val: port.to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        };

        let Some(typ_str) = i.next() else {
            return Err(AttributeError::ParamNotFound {
                param: "'typ' string".to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        };

        if !typ_str.eq_ignore_ascii_case("typ") {
            return Err(AttributeError::ParamNotFound {
                param: "'typ' string".to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        }

        let Some(cand_type) = i.next() else {
            return Err(AttributeError::ParamNotFound {
                param: "Candidate type".to_string(),
                attr: <Self as TypedAttribute>::NAME.to_string(),
            });
        };

        let cand_type = CandidateType::new(cand_type);

        let mut rel_addr: Option<IpAddr> = None;
        let mut rel_port: Option<u16> = None;
        let mut exts: Vec<(String, String)> = Vec::new();

        while let Some(key) = i.next() {
            if key.eq_ignore_ascii_case("raddr") {
                let Some(raddr) = i.next() else {
                    return Err(AttributeError::ParamNotFound {
                        param: "Relative address".to_string(),
                        attr: <Self as TypedAttribute>::NAME.to_string(),
                    });
                };

                if let Ok(raddr) = raddr.parse::<IpAddr>() {
                    rel_addr = Some(raddr);
                } else {
                    return Err(AttributeError::InvalidParamValue {
                        param: "Relative address".to_string(),
                        val: raddr.to_string(),
                        attr: <Self as TypedAttribute>::NAME.to_string(),
                    });
                };
            } else if key.eq_ignore_ascii_case("rport") {
                let Some(rport) = i.next() else {
                    return Err(AttributeError::ParamNotFound {
                        param: "Relative port".to_string(),
                        attr: <Self as TypedAttribute>::NAME.to_string(),
                    });
                };

                if let Ok(rport) = rport.parse::<u16>() {
                    rel_port = Some(rport);
                } else {
                    return Err(AttributeError::InvalidParamValue {
                        param: "Relative port".to_string(),
                        val: rport.to_string(),
                        attr: <Self as TypedAttribute>::NAME.to_string(),
                    });
                }
            } else {
                let Some(val) = i.next() else {
                    return Err(AttributeError::Other {
                        error: format!("No val for the extension {key}"),
                        attr: <Self as TypedAttribute>::NAME.to_string(),
                    });
                };

                exts.push((key.to_string(), val.to_string()));
            }
        }

        Ok(Self {
            foundation: foundation.to_string(),
            component_id: comp_id,
            transport: transport.to_string(),
            priority,
            address,
            port,
            typ: cand_type,
            rel_addr,
            rel_port,
            extensions: exts,
        })
    }
}

impl Display for Candidate {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let candidate_addr = match &self.address {
            CandidateAddress::IpAddr(a) => a.to_string(),
            CandidateAddress::FQDN(d) => d.clone(),
        };
        write!(
            f,
            "{} {} {} {} {} {} typ {}",
            self.foundation,
            self.component_id,
            self.transport,
            self.priority,
            candidate_addr,
            self.port,
            self.typ.as_str(),
        )?;
        if let Some(rel_addr) = self.rel_addr {
            write!(f, " raddr {rel_addr}")?;
        }
        if let Some(rel_port) = self.rel_port {
            write!(f, " rport {rel_port}")?;
        }
        for (key, val) in &self.extensions {
            write!(f, " {key} {val}")?;
        }
        Ok(())
    }
}

impl TypedAttribute for Candidate {
    const NAME: &'static str = "candidate";
}

#[cfg(test)]
mod tests {
    use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};

    use super::*;
    use crate::*;

    #[test]
    fn direction_parse() {
        assert_eq!("sendonly".parse::<Direction>(), Ok(Direction::SendOnly));
        assert_eq!("recvonly".parse::<Direction>(), Ok(Direction::RecvOnly));
        assert_eq!("sendrecv".parse::<Direction>(), Ok(Direction::SendRecv));
        assert_eq!("inactive".parse::<Direction>(), Ok(Direction::Inactive));
        assert!("invalid".parse::<Direction>().is_err());
    }

    #[test]
    fn direction_display() {
        assert_eq!(Direction::SendOnly.to_string(), "sendonly");
        assert_eq!(Direction::RecvOnly.to_string(), "recvonly");
        assert_eq!(Direction::SendRecv.to_string(), "sendrecv");
        assert_eq!(Direction::Inactive.to_string(), "inactive");
    }

    #[test]
    fn parse_rtcp_fb() {
        let sdp = "v=0\r
o=alice 3203093520 3203093520 IN IP4 host.example.com\r
s=Multicast video with feedback\r
t=3203130148 3203137348\r
m=audio 49170 RTP/AVP 0\r
c=IN IP4 224.2.1.183\r
a=rtpmap:0 PCMU/8000\r
m=video 51372 RTP/AVPF 98 99\r
c=IN IP4 224.2.1.184\r
a=rtpmap:98 H263-1998/90000\r
a=rtpmap:99 H261/90000\r
a=rtcp-fb:* nack\r
a=rtcp-fb:98 nack rpsi\r
a=rtcp-fb:* trr-int 1000\r
a=rtcp-fb:98 ccm vbcm 1 2\r
a=rtcp-fb:* ccm tmmbr smaxpr=120\r
";

        let parsed = Session::parse(sdp.as_bytes()).unwrap();
        let mut written = vec![];
        parsed.write(&mut written).unwrap();

        let v = fallible_iterator::convert(parsed.medias[1].attributes_typed::<RtcpFb>())
            .collect::<Vec<_>>()
            .expect("Valid vector of attributes");
        assert_eq!(v[0].pt, RtcpFbPt::Wildcard);
        assert_eq!(v[1].val, RtcpFbVal::Nack(Some(RtcpFbNack::Rpsi)));
        assert_eq!(v[2].val, RtcpFbVal::TrrInt(1000));
        assert_eq!(v[3].val, RtcpFbVal::Ccm(RtcpFbCcm::Vbcm(vec![1, 2])));
        assert_eq!(
            v[4].val,
            RtcpFbVal::Ccm(RtcpFbCcm::Tmmbr(Some("smaxpr=120".to_string())))
        );
    }

    #[test]
    fn parse_group_attribute() {
        let sdp = "v=0\r
o=Laura 289083124 289083124 IN IP4 two.example.com\r
c=IN IP4 233.252.0.1/127\r
t=0 0\r
a=group:LS 1 2\r
m=audio 30000 RTP/AVP 0\r
a=mid:1\r
m=video 30002 RTP/AVP 31\r
a=mid:2\r
m=audio 30004 RTP/AVP 0\r
i=This media stream contains the Spanish translation\r
a=mid:3\r
";
        let parsed = Session::parse(sdp.as_bytes()).unwrap();

        let g = parsed.attributes_typed::<Group>().collect::<Vec<_>>();
        assert_eq!(g.len(), 1);
        assert_eq!(g[0].as_ref().unwrap().semantics, GroupSemantics::LS);
        assert_eq!(
            g[0].as_ref().unwrap().mid_tags,
            vec!["1".to_string(), "2".to_string()]
        );
    }

    #[test]
    fn parse_setup_attribute() {
        let sdp = "v=0\r
m=image 54111 TCP t38\r
c=IN IP4 192.0.2.2\r
a=setup:actpass\r
a=connection:new\r
";
        let media = Session::parse(sdp.as_bytes()).unwrap().medias;

        let s = media[0].attributes_typed::<Setup>().collect::<Vec<_>>();

        assert_eq!(s.len(), 1);
        assert_eq!(s[0].as_ref().unwrap().to_owned(), Setup::ActPass);
    }

    #[test]
    fn parse_ssrc_attributes() {
        let sdp = "v=0\r
o=jdoe 2890844526 2890842807 IN IP4 10.47.16.5\r
m=video 49174 RTP/AVPF 96 98\r
a=rtpmap:98 rtx/90000\r
a=fmtp:98 apt=96;rtx-time=3000\r
a=ssrc-group:FID 11111 22222\r
a=ssrc:11111 cname:user3@example.com\r
a=ssrc:22222 fmtp:0 0-15\r
a=ssrc-group:FID 33333 44444\r
a=ssrc:33333 cname:user3@example.com\r
a=ssrc:44444 cname:user3@example.com\r
a=ssrc:1698359993 rtcp:5003 IN IP4 127.0.0.1
";

        let parsed = Session::parse(sdp.as_bytes()).unwrap();
        let m = &parsed.medias[0];

        let ssrcs = m
            .attributes_typed::<Ssrc>()
            .filter(|s| {
                let Ok(ssrc) = s else { return false };
                ssrc.attribute == SsrcAttribute::Fmtp || ssrc.attribute == SsrcAttribute::Rtcp
            })
            .collect::<Vec<_>>();

        let ssrc_id = ssrcs[0].as_ref().unwrap().ssrc_id;

        let ssrc_groups = m
            .attributes_typed::<SsrcGroup>()
            .filter(|s| {
                let Ok(ssrc_group) = s else { return false };

                ssrc_group.ssrc_ids[1] == ssrc_id
            })
            .collect::<Vec<_>>();

        assert_eq!(
            ssrc_groups[0].as_ref().unwrap().semantics,
            GroupSemantics::FID
        );

        assert_eq!(ssrcs[1].as_ref().unwrap().attribute, SsrcAttribute::Rtcp);
    }

    #[test]
    fn parse_crypto_attributes() {
        let sdp = "v=0\r
o=sam 2890844526 2890842807 IN IP4 10.47.16.5\r
s=SRTP Discussion\r
i=A discussion of Secure RTP\r
u=http://www.example.com/seminars/srtp.pdf\r
e=marge@example.com (Marge Simpson)\r
c=IN IP4 168.2.17.12\r
t=2873397496 2873404696\r
m=audio 49170 RTP/SAVP 0\r
a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:WVNfX19zZW1jdGwgKCkgewkyMjA7fQp9CnVubGVz|2^20|1:4 FEC_ORDER=SRTP_FEC\r
a=crypto:2 F8_128_HMAC_SHA1_80 inline:MTIzNDU2Nzg5QUJDREUwMTIzNDU2Nzg5QUJjZGVm|2^20|1:4;inline:QUJjZGVmMTIzNDU2Nzg5QUJDREUwMTIzNDU2Nzg5|2^20|2:4 FEC_ORDER=FEC_SRTP\r
m=video 51372 RTP/SAVP 31\r
a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:YUJDZGVmZ2hpSktMbW9QUXJzVHVWd3l6MTIzNDU2|1066:4\r
";

        let parsed = Session::parse(sdp.as_bytes()).unwrap();
        let a = &parsed.medias[0];

        let audio_cryptos = a.attributes_typed::<Crypto>().collect::<Vec<_>>();

        assert_eq!(
            audio_cryptos[0].as_ref().unwrap().crypto_suite,
            CryptoSuite::AesCm128HmacSha1_80
        );
        assert_eq!(audio_cryptos[1].as_ref().unwrap().key_params.len(), 2);

        assert_eq!(
            audio_cryptos[1].as_ref().unwrap().key_params[1].mki_and_length,
            Some((2, 4))
        );

        assert_eq!(
            audio_cryptos[1].as_ref().unwrap().session_params[0],
            SrtpSessionParam::FecOrder(FecOrder::FecSrtp)
        );

        let v = &parsed.medias[1];

        let video_cryptos = v
            .attributes_typed::<Crypto>()
            .filter(|c| {
                let Ok(crypto) = c else { return false };

                crypto.tag == 1
            })
            .collect::<Vec<_>>();

        let test_crypto = Crypto {
            tag: 1,
            crypto_suite: CryptoSuite::AesCm128HmacSha1_80,
            key_params: vec![SrtpKeyParam {
                key_and_salt: "YUJDZGVmZ2hpSktMbW9QUXJzVHVWd3l6MTIzNDU2".to_string(),
                lifetime: None,
                mki_and_length: Some((1066, 4)),
            }],
            session_params: Vec::new(),
        };

        assert_eq!(&test_crypto, video_cryptos[0].as_ref().unwrap());
    }

    #[test]
    fn write_crypto_attribute() {
        let crypto = Crypto {
            tag: 1,
            crypto_suite: CryptoSuite::AesCm128HmacSha1_80,
            key_params: vec![
                SrtpKeyParam {
                    key_and_salt: "WVNfX19zZW1jdGwgKCkgewkyMjA7fQp9CnVubGVz".to_string(),
                    lifetime: Some(1048576),
                    mki_and_length: Some((1, 4)),
                },
                SrtpKeyParam {
                    key_and_salt: "WVNfX19zZW1jdGwgKCkgewkyMjA7fQp9CnVubGVz".to_string(),
                    lifetime: Some(1048576),
                    mki_and_length: Some((1, 4)),
                },
            ],
            session_params: vec![SrtpSessionParam::FecOrder(FecOrder::SrtpFec)],
        };

        assert_eq!(
            crypto.to_string(),
            "1 AES_CM_128_HMAC_SHA1_80 inline:WVNfX19zZW1jdGwgKCkgewkyMjA7fQp9CnVubGVz|2^20|1:4;inline:WVNfX19zZW1jdGwgKCkgewkyMjA7fQp9CnVubGVz|2^20|1:4 FEC_ORDER=SRTP_FEC"
        );
    }

    #[test]
    fn parse_candidate_attributes() {
        use std::net::{Ipv4Addr, Ipv6Addr};

        let sdp = "v=0\r
o=- 2890844526 2890842807 IN IP4 192.168.1.1\r
s=-\r
c=IN IP4 192.168.1.1\r
t=0 0\r
m=audio 49152 RTP/AVP 0\r
a=candidate:1 1 UDP 2130706432 192.168.1.1 49152 typ host raddr 10.0.1.1 rport 49153 generation 0\r
a=candidate:2 1 UDP 1692467200 10.0.1.1 49152 typ srflx raddr 192.168.1.1 rport 49153\r
a=candidate:3 2 UDP 1692467184 192.168.1.1 49153 typ host\r
a=candidate:4 1 UDP 100 2001:db8::1 49152 typ host\r
a=candidate:5 1 UDP 50 192.168.1.1 49154 typ prflx\r
a=candidate:6 1 UDP 25 192.168.1.1 49155 typ relay raddr 10.0.0.1 rport 49156\r
a=candidate:7 1 UDP 10 192.168.1.1 49157 typ unknown_type\r
";

        let session = Session::parse(sdp.as_bytes()).unwrap();
        let candidates: Vec<Candidate> =
            fallible_iterator::convert(session.medias[0].attributes_typed::<Candidate>())
                .collect::<Vec<_>>()
                .expect("Valid vector of candidates");

        assert_eq!(candidates.len(), 7);

        assert_eq!(candidates[0].foundation, "1");
        assert_eq!(candidates[0].component_id, 1);
        assert_eq!(
            candidates[0].address,
            CandidateAddress::IpAddr(IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1)))
        );
        assert_eq!(candidates[0].port, 49152);
        assert_eq!(candidates[0].typ, CandidateType::Host);
        assert_eq!(
            candidates[0].rel_addr,
            Some(IpAddr::V4(Ipv4Addr::new(10, 0, 1, 1)))
        );
        assert_eq!(candidates[0].rel_port, Some(49153));
        assert_eq!(
            candidates[0].extensions,
            vec![("generation".to_string(), "0".to_string())]
        );

        assert_eq!(candidates[1].foundation, "2");
        assert_eq!(candidates[1].typ, CandidateType::Srflx);
        assert_eq!(
            candidates[1].rel_addr,
            Some(IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1)))
        );
        assert_eq!(candidates[1].rel_port, Some(49153));

        assert_eq!(candidates[2].foundation, "3");
        assert_eq!(candidates[2].component_id, 2);
        assert_eq!(candidates[2].typ, CandidateType::Host);

        assert_eq!(candidates[3].foundation, "4");
        assert_eq!(
            candidates[3].address,
            CandidateAddress::IpAddr(IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1)))
        );
        assert_eq!(candidates[3].typ, CandidateType::Host);

        assert_eq!(candidates[4].foundation, "5");
        assert_eq!(candidates[4].typ, CandidateType::Prflx);

        assert_eq!(candidates[5].foundation, "6");
        assert_eq!(candidates[5].typ, CandidateType::Relay);

        assert_eq!(candidates[6].foundation, "7");
        assert_eq!(
            candidates[6].typ,
            CandidateType::Other("unknown_type".to_string())
        );
    }

    #[test]
    fn write_candidate() {
        use std::net::Ipv4Addr;

        let candidate = Candidate {
            foundation: "abcd/1234".into(),
            component_id: 1,
            transport: "UDP".into(),
            priority: 2130706432,
            address: CandidateAddress::IpAddr(IpAddr::V4(Ipv4Addr::new(192, 168, 0, 1))),
            port: 49152,
            typ: CandidateType::Srflx,
            rel_addr: Some(IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1))),
            rel_port: Some(49153),
            extensions: vec![("tcptype".to_string(), "active".to_string())],
        };

        assert_eq!(
            candidate.to_string(),
            "abcd/1234 1 UDP 2130706432 192.168.0.1 49152 typ srflx raddr 10.0.0.1 rport 49153 tcptype active"
        );
    }

    #[test]
    fn test_attribute_errors() {
        // Test RtpMap error paths
        assert_eq!(
            "99".parse::<RtpMap>().unwrap_err(),
            AttributeError::UnsupportedFormat {
                val: "99".to_string(),
                attr: "rtpmap".to_string()
            }
        );
        assert_eq!(
            "abc 90000".parse::<RtpMap>().unwrap_err(),
            AttributeError::InvalidParamValue {
                param: "Payload type".to_string(),
                val: "abc".to_string(),
                attr: "rtpmap".to_string()
            }
        );
        assert_eq!(
            "200 enc/90000".parse::<RtpMap>().unwrap_err(),
            AttributeError::InvalidParamValue {
                param: "Payload type".to_string(),
                val: "200(expected 0-127)".to_string(),
                attr: "rtpmap".to_string()
            }
        );
        assert_eq!(
            "99 ".parse::<RtpMap>().unwrap_err(),
            AttributeError::ParamNotFound {
                param: "Clock rate".to_string(),
                attr: "rtpmap".to_string()
            }
        );
        assert_eq!(
            "99 /".parse::<RtpMap>().unwrap_err(),
            AttributeError::InvalidParamValue {
                param: "Clock rate".to_string(),
                val: "".to_string(),
                attr: "rtpmap".to_string()
            }
        );

        assert_eq!(
            "invalid".parse::<Fmtp>().unwrap_err(),
            AttributeError::UnsupportedFormat {
                val: "invalid".to_string(),
                attr: "fmtp".to_string()
            }
        );
        assert_eq!(
            "abc profile=1".parse::<Fmtp>().unwrap_err(),
            AttributeError::InvalidParamValue {
                param: "fmtp".to_string(),
                val: "abc".to_string(),
                attr: "fmtp".to_string()
            }
        );

        // Test Rtcp error paths
        assert_eq!(
            "".parse::<Rtcp>().unwrap_err(),
            AttributeError::InvalidParamValue {
                param: "Port".to_string(),
                val: "".to_string(),
                attr: "rtcp".to_string()
            }
        );
        assert_eq!(
            "abc IN IP4 127.0.0.1".parse::<Rtcp>().unwrap_err(),
            AttributeError::InvalidParamValue {
                param: "Port".to_string(),
                val: "abc".to_string(),
                attr: "rtcp".to_string()
            }
        );

        // Test Fingerprint error paths
        assert_eq!(
            "".parse::<Fingerprint>().unwrap_err(),
            AttributeError::ParamNotFound {
                param: "Hash value".to_string(),
                attr: "fingerprint".to_string()
            }
        );
        assert_eq!(
            "SHA-1".parse::<Fingerprint>().unwrap_err(),
            AttributeError::ParamNotFound {
                param: "Hash value".to_string(),
                attr: "fingerprint".to_string()
            }
        );

        // Test Candidate error paths
        assert_eq!(
            "".parse::<Candidate>().unwrap_err(),
            AttributeError::ParamNotFound {
                param: "Component id".to_string(),
                attr: "candidate".to_string()
            }
        );
        assert_eq!(
            "1 1 UDP 100".parse::<Candidate>().unwrap_err(),
            AttributeError::ParamNotFound {
                param: "Address".to_string(),
                attr: "candidate".to_string()
            }
        );

        // Test ExtMap error paths
        assert_eq!(
            "".parse::<ExtMap>().unwrap_err(),
            AttributeError::InvalidParamValue {
                param: "Id".to_string(),
                val: "".to_string(),
                attr: "extmap".to_string()
            }
        );
        assert_eq!(
            "999999 http://example.com".parse::<ExtMap>().unwrap_err(),
            AttributeError::InvalidParamValue {
                param: "Id".to_string(),
                val: "999999".to_string(),
                attr: "extmap".to_string()
            }
        );

        // Test Group error paths
        assert_eq!(
            "".parse::<Group>().unwrap_err(),
            AttributeError::ParamNotFound {
                param: "Media identification tags".to_string(),
                attr: "group".to_string()
            }
        );
        assert_eq!(
            "LS".parse::<Group>().unwrap_err(),
            AttributeError::ParamNotFound {
                param: "Media identification tags".to_string(),
                attr: "group".to_string()
            }
        );

        // Test Ssrc error paths
        assert_eq!(
            "".parse::<Ssrc>().unwrap_err(),
            AttributeError::ParamNotFound {
                param: "Ssrc id".to_string(),
                attr: "ssrc".to_string()
            }
        );
        assert_eq!(
            "abc".parse::<Ssrc>().unwrap_err(),
            AttributeError::ParamNotFound {
                param: "Ssrc id".to_string(),
                attr: "ssrc".to_string()
            }
        );

        // Test Setup error paths
        let setup_err = "foo".parse::<Setup>().err().unwrap();
        assert!(matches!(setup_err, AttributeError::Other { .. }));
        assert_eq!(format!("{}", setup_err), "setup: Invalid Setup value foo");

        // Test Crypto error paths
        assert_eq!(
            "".parse::<Crypto>().unwrap_err(),
            AttributeError::InvalidParamValue {
                param: "Tag".to_string(),
                val: "".to_string(),
                attr: "crypto".to_string()
            }
        );
        assert_eq!(
            "abc AES_CM_128_HMAC_SHA1_32 inline:key"
                .parse::<Crypto>()
                .unwrap_err(),
            AttributeError::InvalidParamValue {
                param: "Tag".to_string(),
                val: "abc".to_string(),
                attr: "crypto".to_string()
            }
        );

        // Test RtcpFb error paths
        assert_eq!(
            "".parse::<RtcpFb>().unwrap_err(),
            AttributeError::InvalidParamValue {
                param: "Payload format".to_string(),
                val: "".to_string(),
                attr: "rtcp-fb".to_string()
            }
        );
        assert_eq!(
            "*".parse::<RtcpFb>().unwrap_err(),
            AttributeError::ParamNotFound {
                param: "Rtcp feedback value".to_string(),
                attr: "rtcp-fb".to_string()
            }
        );
        assert_eq!(
            "1 ack ccfb".parse::<RtcpFb>().unwrap_err(),
            AttributeError::InvalidParamValue {
                param: "Payload type of Congestion control feedback (ccfb)".to_string(),
                val: "1(expected wildcard (*))".to_string(),
                attr: "rtcp-fb".to_string()
            }
        );

        // Test attribute_typed with missing value
        let media = Media {
            media: "video".into(),
            port: 1234,
            num_ports: None,
            proto: "RTP/SAVPF".into(),
            fmt: "".into(),
            media_title: None,
            connections: vec![],
            bandwidths: vec![],
            key: None,
            attributes: vec![Attribute {
                attribute: "rtpmap".into(),
                value: None,
            }],
        };
        assert_eq!(
            media
                .attributes_typed::<RtpMap>()
                .collect::<Vec<Result<RtpMap, AttributeError>>>()
                .remove(0)
                .unwrap_err(),
            AttributeError::Other {
                error: "No value for the attribute".to_string(),
                attr: "rtpmap".to_string()
            }
        );
    }

    #[test]
    fn parse_rtcp_address() {
        let sdp = "v=0\r
o=alice 3203093520 3203093520 IN IP4 host.example.com\r
s=parse rtcp attribute address test\r
a=rtcp:5000 IN IP4 127.0.0.1\r
a=rtcp:5000 IN IP4 127.0.0.0/24\r
a=rtcp:5000 IN IP6 ::1\r
a=rtcp:5000 IN NONIP non-IP\r
";

        let parsed = Session::parse(sdp.as_bytes()).unwrap();
        let mut rtcp_attr_iter = parsed.attributes_typed::<Rtcp>();

        let rtcp = rtcp_attr_iter.next().unwrap().unwrap();
        assert_eq!(rtcp.addrtype, AddrType::Ip4);
        assert_eq!(&rtcp.connection_address, "127.0.0.1");
        assert_eq!(
            rtcp.try_parse_connection_ip_address().unwrap(),
            IpAddr::V4(Ipv4Addr::LOCALHOST),
        );

        let rtcp = rtcp_attr_iter.next().unwrap().unwrap();
        assert_eq!(rtcp.addrtype, AddrType::Ip4);
        assert_eq!(&rtcp.connection_address, "127.0.0.0/24");
        assert_eq!(
            &rtcp
                .try_parse_connection_ip_address()
                .expect_err("IPv4 with mask")
                .to_string(),
            "127.0.0.0/24"
        );

        let rtcp = rtcp_attr_iter.next().unwrap().unwrap();
        assert_eq!(rtcp.addrtype, AddrType::Ip6);
        assert_eq!(&rtcp.connection_address, "::1");
        assert_eq!(
            rtcp.try_parse_connection_ip_address().unwrap(),
            IpAddr::V6(Ipv6Addr::LOCALHOST),
        );

        let rtcp = rtcp_attr_iter.next().unwrap().unwrap();
        assert_eq!(rtcp.addrtype, AddrType::Other("NONIP".to_string()));
        assert_eq!(&rtcp.connection_address, "non-IP");
        assert_eq!(
            rtcp.try_parse_connection_ip_address().unwrap_err(),
            "non-IP",
        );
    }
}