medea-client-api-proto 0.10.0

Client API protocol implementation for Medea media server.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
//! Contains DTOs for [RTCPeerConnection] metrics according to the
//! [Identifiers for WebRTC's Statistics API][0] specification.
//!
//! [RTCPeerConnection]: https://w3.org/TR/webrtc#dom-rtcpeerconnection
//! [0]: https://w3.org/TR/webrtc-stats

use std::{
    collections::BTreeMap,
    hash::{Hash, Hasher},
    time::{Duration, SystemTime, SystemTimeError},
};

use derive_more::with_trait::{Display, From};
use serde::{Deserialize, Serialize};

/// Deserialization helper for enums, allowing to store unknown data as a
/// [`String`] in the [`Unknown`] variant.
///
/// [`Unknown`]: NonExhaustive::Unknown
#[derive(
    Clone,
    Debug,
    Deserialize,
    Display,
    Eq,
    Hash,
    Ord,
    PartialEq,
    PartialOrd,
    Serialize,
)]
#[serde(untagged)]
pub enum NonExhaustive<T> {
    /// Known enum variant if it successfully deserialized.
    Known(T),

    /// Unknown enum variant with its data as [`String`].
    #[display("Unknown: {_0}")]
    Unknown(String),
}

/// Unique ID that is associated with the object that was inspected to produce
/// an [`RtcStat`] object.
///
/// Two [`RtcStat`]s objects, extracted from two different [RTCStatsReport]
/// objects, MUST have the same ID if they were produced by inspecting the same
/// underlying object.
///
/// [RTCStatsReport]: https://w3.org/TR/webrtc#dom-rtcstatsreport
#[derive(
    Clone, Debug, Deserialize, Display, Eq, From, Hash, PartialEq, Serialize,
)]
#[from(forward)]
pub struct StatId(pub String);

/// [Stats object] constructed by inspecting a specific [monitored object].
///
/// [Full doc on W3C][spec].
///
/// [monitored object]: https://w3.org/TR/webrtc-stats#dfn-monitored-object
/// [spec]: https://w3.org/TR/webrtc-stats#dom-rtcstats
/// [Stats object]: https://w3.org/TR/webrtc-stats#dfn-stats-object
#[derive(Clone, Debug, Deserialize, Hash, PartialEq, Serialize)]
pub struct RtcStat {
    /// Unique ID that is associated with the object that was inspected to
    /// produce this [`RtcStat`] object.
    pub id: StatId,

    /// Timestamp associated with this [`RtcStat`] object.
    ///
    /// The time is relative to the UNIX epoch (Jan 1, 1970, UTC).
    ///
    /// For statistics that came from a remote source (e.g. from received [RTCP]
    /// packets), timestamp represents the time at which the information arrived
    /// at the local endpoint. The remote timestamp can be found in an
    /// additional field in an [`RtcStat`]-derived dictionary, if applicable.
    ///
    /// [RTCP]: https://webrtcglossary.com/rtcp
    pub timestamp: HighResTimeStamp,

    /// Actual stats of this [`RtcStat`].
    ///
    /// All possible stats are described in the [`RtcStatsType`] enum.
    #[serde(flatten)]
    pub stats: RtcStatsType,
}

/// Possible types of [`RtcStat`]s.
///
/// [Full doc on W3C][spec].
///
/// [spec]: https://w3.org/TR/webrtc-stats#dom-rtcstatstype
#[derive(Clone, Debug, Deserialize, Hash, PartialEq, Serialize)]
#[serde(tag = "type", rename_all = "kebab-case")]
pub enum RtcStatsType {
    /// Statistics for a codec that is currently used by [RTP stream]s being
    /// sent or received by [RTCPeerConnection] object.
    ///
    /// [RTCPeerConnection]: https://w3.org/TR/webrtc#dom-rtcpeerconnection
    /// [RTP stream]: https://w3.org/TR/webrtc-stats#dfn-rtp-stream
    Codec(Box<RtcCodecStats>),

    /// Statistics for an inbound [RTP stream] that is currently received with
    /// this [RTCPeerConnection] object.
    ///
    /// RTX streams do not show up as separate [`RtcInboundRtpStreamStats`]
    /// objects but affect the [`RtcReceivedRtpStreamStats::packets_received`],
    /// [`RtcInboundRtpStreamStats::bytes_received`],
    /// [`RtcInboundRtpStreamStats::retransmitted_packets_received`] and
    /// [`RtcInboundRtpStreamStats::retransmitted_bytes_received`] counters of
    /// the relevant [`RtcInboundRtpStreamStats`] objects.
    ///
    /// FEC streams do not show up as separate [`RtcInboundRtpStreamStats`]
    /// objects but affect the [`RtcReceivedRtpStreamStats::packets_received`],
    /// [`RtcInboundRtpStreamStats::bytes_received`],
    /// [`RtcInboundRtpStreamStats::fec_packets_received`] and
    /// [`RtcInboundRtpStreamStats::fec_bytes_received`] counters of the
    /// relevant [`RtcInboundRtpStreamStats`] objects.
    ///
    /// [RTCPeerConnection]: https://w3.org/TR/webrtc#dom-rtcpeerconnection
    /// [RTP stream]: https://w3.org/TR/webrtc-stats#dfn-rtp-stream
    InboundRtp(Box<RtcInboundRtpStreamStats>),

    /// Statistics for an outbound [RTP stream] that is currently sent with this
    /// [RTCPeerConnection] object.
    ///
    /// When there are multiple [RTP stream]s connected to the same sender due
    /// to using simulcast, there will be one [`RtcOutboundRtpStreamStats`]
    /// per [RTP stream], with distinct values of the [SSRC] member. RTX streams
    /// do not show up as separate [`RtcOutboundRtpStreamStats`] objects but
    /// affect the [`RtcSentRtpStreamStats::packets_sent`],
    /// [`RtcSentRtpStreamStats::bytes_sent`],
    /// [`RtcOutboundRtpStreamStats::retransmitted_packets_sent`] and
    /// [`RtcOutboundRtpStreamStats::retransmitted_bytes_sent`] counters of the
    /// relevant [`RtcOutboundRtpStreamStats`] objects.
    ///
    /// [RTCPeerConnection]: https://w3.org/TR/webrtc#dom-rtcpeerconnection
    /// [RTP stream]: https://w3.org/TR/webrtc-stats#dfn-rtp-stream
    /// [SSRC]: https://w3.org/TR/webrtc-stats#dfn-ssrc
    OutboundRtp(Box<RtcOutboundRtpStreamStats>),

    /// Statistics for the remote endpoint's inbound [RTP stream] corresponding
    /// to an outbound stream that is currently sent with this
    /// [RTCPeerConnection] object.
    ///
    /// It is measured at the remote endpoint and reported in an
    /// [RTCP Receiver Report][1] (RR) or [RTCP Extended Report][2] (XR).
    ///
    /// [RTCPeerConnection]: https://w3.org/TR/webrtc#dom-rtcpeerconnection
    /// [RTP stream]: https://w3.org/TR/webrtc-stats#dfn-rtp-stream
    /// [1]: https://w3.org/TR/webrtc-stats#dfn-receiver-report
    /// [2]: https://w3.org/TR/webrtc-stats#dfn-extended-report
    RemoteInboundRtp(Box<RtcRemoteInboundRtpStreamStats>),

    /// Statistics for the remote endpoint's outbound [RTP stream] corresponding
    /// to an inbound stream that is currently received with this
    /// [RTCPeerConnection] object.
    ///
    /// It is measured at the remote endpoint and reported in an
    /// [RTCP Sender Report][1] (SR).
    ///
    /// [RTCPeerConnection]: https://w3.org/TR/webrtc#dom-rtcpeerconnection
    /// [RTP stream]: https://w3.org/TR/webrtc-stats#dfn-rtp-stream
    /// [1]: https://w3.org/TR/webrtc-stats#dfn-sender-report
    RemoteOutboundRtp(Box<RtcRemoteOutboundRtpStreamStats>),

    /// Statistics for the media produced by a [MediaStreamTrack][1] that is
    /// currently attached to an [RTCRtpSender].
    ///
    /// This reflects the media that is fed to the encoder; after
    /// [getUserMedia()][2] constraints have been applied (i.e. not the raw
    /// media produced by the camera).
    ///
    /// [RTCRtpSender]: https://w3.org/TR/webrtc#dom-rtcrtpsender
    /// [1]: https://w3.org/TR/mediacapture-streams#dom-mediastreamtrack
    /// [2]: https://tinyurl.com/w3-streams#dom-mediadevices-getusermedia
    MediaSource(Box<RtcMediaSourceStats>),

    /// Statistics related to audio playout.
    MediaPlayout(Box<RtcAudioPlayoutStats>),

    /// Statistics related to an [RTCPeerConnection] object.
    ///
    /// [RTCPeerConnection]: https://w3.org/TR/webrtc#dom-rtcpeerconnection
    PeerConnection(Box<RtcPeerConnectionStats>),

    /// Statistics related to each [RTCDataChannel] ID.
    ///
    /// [RTCDataChannel]: https://w3.org/TR/webrtc#dom-rtcdatachannel
    DataChannel(Box<RtcDataChannelStats>),

    /// Transport statistics related to an [RTCPeerConnection] object.
    ///
    /// It is accessed by the [`RtcTransportStats`].
    ///
    /// [RTCPeerConnection]: https://w3.org/TR/webrtc#dom-rtcpeerconnection
    Transport(Box<RtcTransportStats>),

    /// [ICE] candidate pair statistics related to [RTCIceTransport] objects.
    ///
    /// A candidate pair that is not the current pair for a transport is
    /// [deleted][1] when the [RTCIceTransport] does an [ICE] restart, at the
    /// time the state changes to `new`. The candidate pair that is the current
    /// pair for a transport is deleted after an [ICE] restart when the
    /// [RTCIceTransport] switches to using a candidate pair generated from the
    /// new candidates; this time doesn't correspond to any other externally
    /// observable event.
    ///
    /// [ICE]: https://datatracker.ietf.org/doc/html/rfc8445
    /// [RTCIceTransport]: https://w3.org/TR/webrtc#dom-rtcicetransport
    /// [1]: https://w3.org/TR/webrtc-stats#dfn-deleted
    CandidatePair(Box<RtcIceCandidatePairStats>),

    /// [ICE] local candidate statistics related to the [RTCIceTransport]
    /// objects.
    ///
    /// A local candidate is [deleted][1] when the [RTCIceTransport] does an
    /// [ICE] restart, and the candidate is no longer a member of any
    /// non-deleted candidate pair.
    ///
    /// [ICE]: https://datatracker.ietf.org/doc/html/rfc8445
    /// [RTCIceTransport]: https://w3.org/TR/webrtc#dom-rtcicetransport
    /// [1]: https://w3.org/TR/webrtc-stats#dfn-deleted
    LocalCandidate(Box<RtcIceCandidateStats>),

    /// [ICE] remote candidate statistics related to the [RTCIceTransport]
    /// objects.
    ///
    /// A remote candidate is [deleted][1] when the [RTCIceTransport] does an
    /// [ICE] restart, and the candidate is no longer a member of any
    /// non-deleted candidate pair.
    ///
    /// [ICE]: https://datatracker.ietf.org/doc/html/rfc8445
    /// [RTCIceTransport]: https://w3.org/TR/webrtc#dom-rtcicetransport
    /// [1]: https://w3.org/TR/webrtc-stats#dfn-deleted
    RemoteCandidate(Box<RtcIceCandidateStats>),

    /// Information about a certificate used by the [RTCIceTransport].
    ///
    /// It is accessed by [`RtcCertificateStats`].
    ///
    /// [RTCIceTransport]: https://w3.org/TR/webrtc#dom-rtcicetransport
    Certificate(Box<RtcCertificateStats>),

    /// Disabled or unknown variants of stats will be deserialized as [`Other`].
    ///
    /// [`Other`]: RtcStatsType::Other
    #[serde(other)]
    Other,
}

/// Statistics that apply to any end of any [RTP stream].
///
/// [Full doc on W3C][spec].
///
/// [RTP stream]: https://w3.org/TR/webrtc-stats#dfn-rtp-stream
/// [spec]: https://w3.org/TR/webrtc-stats#dom-rtcrtpstreamstats
#[expect(clippy::module_name_repetitions, reason = "spec compliance")]
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RtcRtpStreamStats {
    /// Synchronization source ([SSRC]) identifier is an unsigned integer value
    /// per [RFC3550] used to identify the stream of [RTP] packets that this
    /// stats object is describing.
    ///
    /// For outbound and inbound local, [SSRC] describes the stats for the [RTP]
    /// stream that were sent and received, respectively by those endpoints.
    ///
    /// For the remote inbound and remote outbound, [SSRC] describes the stats
    /// for the [RTP] stream that were received by and sent to the remote
    /// endpoint.
    ///
    /// [RFC3550]: https://rfc-editor.org/rfc/rfc3550
    /// [RTP]: https://webrtcglossary.com/rtp
    /// [SSRC]: https://w3.org/TR/webrtc-stats#dfn-ssrc
    pub ssrc: Option<u32>,

    /// Either `audio` or `video`.
    ///
    /// This MUST match the [`kind` attribute][1] of the related
    /// [MediaStreamTrack][0].
    ///
    /// [0]: https://w3.org/TR/mediacapture-streams#dom-mediastreamtrack
    /// [1]: https://w3.org/TR/mediacapture-streams#dom-mediastreamtrack-kind
    pub kind: String,

    /// Unique identifier that is associated to the object that was inspected to
    /// produce the [`RtcTransportStats`] associated with this [RTP stream].
    ///
    /// [RTP stream]: https://w3.org/TR/webrtc-stats#dfn-rtp-stream
    pub transport_id: Option<String>,

    /// Unique identifier that is associated to the object that was inspected to
    /// produce the [`RtcCodecStats`] associated with this [RTP stream].
    ///
    /// [RTP stream]: https://w3.org/TR/webrtc-stats#dfn-rtp-stream
    pub codec_id: Option<String>,
}

/// Statistics measured at the receiving end of an [RTP stream], known either
/// because they're measured locally or transmitted via an
/// [RTCP Receiver Report] (RR) or [Extended Report] (XR) block.
///
/// [Full doc on W3C][spec].
///
/// [Extended Report]: https://w3.org/TR/webrtc-stats#dfn-extended-report
/// [RTP stream]: https://w3.org/TR/webrtc-stats#dfn-rtp-stream
/// [RTCP Receiver Report]: https://w3.org/TR/webrtc-stats#dfn-receiver-report
/// [spec]: https://w3.org/TR/webrtc-stats#dom-rtcreceivedrtpstreamstats
#[expect(clippy::module_name_repetitions, reason = "spec compliance")]
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Deserialize, Serialize, Hash, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct RtcReceivedRtpStreamStats {
    /// Generic [RTP stream] data.
    ///
    /// [RTP stream]: https://w3.org/TR/webrtc-stats#dfn-rtp-stream
    #[serde(flatten)]
    pub stream: RtcRtpStreamStats,

    /// Total number of [RTP] packets received for this [SSRC].
    ///
    /// This includes retransmissions.
    ///
    /// At the receiving endpoint, this is calculated as defined in
    /// [RFC3550 Section 6.4.1][1].
    ///
    /// At the sending endpoint the [`packets_received`][0] is estimated by
    /// subtracting the Cumulative Number of Packets Lost from the Extended
    /// Highest Sequence Number Received, both reported in the
    /// [RTCP Receiver Report][2], and then subtracting the initial
    /// Extended Sequence Number that was sent to this [SSRC] in an
    /// [RTCP Sender Report] and then adding one, to mirror what is discussed in
    /// [Appendix A.3 in RFC3550][3], but for the sender side.
    ///
    /// If no [RTCP Receiver Report][0] has been received yet, then is `0`.
    ///
    /// [RTCP Sender Report]: https://w3.org/TR/webrtc-stats#dfn-sender-report
    /// [RTP]: https://webrtcglossary.com/rtp
    /// [SSRC]: https://w3.org/TR/webrtc-stats#dfn-ssrc
    /// [0]: RtcReceivedRtpStreamStats::packets_received
    /// [1]: https://rfc-editor.org/rfc/rfc3550#section-6.4.1
    /// [2]: https://w3.org/TR/webrtc-stats#dfn-receiver-report
    /// [3]: https://rfc-editor.org/rfc/rfc3550#appendix-A.3
    pub packets_received: Option<u64>,

    /// Total number of [RTP] packets received for this [SSRC] marked with the
    /// [ECT(1) marking][1].
    ///
    /// [RTP]: https://webrtcglossary.com/rtp
    /// [SSRC]: https://w3.org/TR/webrtc-stats#dfn-ssrc
    /// [1]: https://rfc-editor.org/rfc/rfc3168#section-3
    pub packets_received_with_ect1: Option<u64>,

    /// Total number of [RTP] packets received for this [SSRC] marked with the
    /// [CE marking][1].
    ///
    /// [RTP]: https://webrtcglossary.com/rtp
    /// [SSRC]: https://w3.org/TR/webrtc-stats#dfn-ssrc
    /// [1]: https://rfc-editor.org/rfc/rfc3168#section-4
    pub packets_received_with_ce: Option<u64>,

    /// Total number of [RTP] packets for which an [RFC8888 Section 3.1][1]
    /// report has been sent with a zero `R` bit.
    ///
    /// Only exists if support for the `ccfb` feedback mechanism has been
    /// negotiated.
    ///
    /// [RTP]: https://webrtcglossary.com/rtp
    /// [1]: https://rfc-editor.org/rfc/rfc8888#section-3.1
    pub packets_reported_as_lost: Option<u64>,

    /// Total number of [RTP] packets for which an [RFC8888 Section 3.1][1]
    /// report has been sent with a zero `R` bit, but a later report for the
    /// same packet has the `R` bit set to `1`.
    ///
    /// Only exists if support for the `ccfb` feedback mechanism has been
    /// negotiated.
    ///
    /// [RTP]: https://webrtcglossary.com/rtp
    /// [1]: https://rfc-editor.org/rfc/rfc8888#section-3.1
    pub packets_reported_as_lost_but_recovered: Option<u64>,

    /// Total number of [RTP] packets lost for this [SSRC].
    ///
    /// Calculated as defined in [RFC3550 Section 6.4.1][1].
    ///
    /// Note that because of how this is estimated, it can be negative if more
    /// packets are received than sent.
    ///
    /// [RTP]: https://webrtcglossary.com/rtp
    /// [SSRC]: https://w3.org/TR/webrtc-stats#dfn-ssrc
    /// [1]: https://rfc-editor.org/rfc/rfc3550#section-6.4.1
    pub packets_lost: Option<i64>,

    /// Packet jitter measured in seconds for this [SSRC].
    ///
    /// Calculated as defined in [Section 6.4.1 of RFC3550][1].
    ///
    /// [SSRC]: https://w3.org/TR/webrtc-stats#dfn-ssrc
    /// [1]: https://rfc-editor.org/rfc/rfc3550#section-6.4.1
    pub jitter: Option<Double>,
}

/// Statistics measured at the sending end of an [RTP stream], known either
/// because they're measured locally or because they're received via [RTCP],
/// usually in an [RTCP Sender Report] (SR).
///
/// [Full doc on W3C][spec].
///
/// [RTP stream]: https://w3.org/TR/webrtc-stats#dfn-rtp-stream
/// [RTCP]: https://webrtcglossary.com/rtcp
/// [RTCP Sender Report]: https://w3.org/TR/webrtc-stats#dfn-sender-report
/// [spec]: https://w3.org/TR/webrtc-stats#dom-rtcsentrtpstreamstats
#[expect(clippy::module_name_repetitions, reason = "spec compliance")]
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "camelCase")]
pub struct RtcSentRtpStreamStats {
    /// Generic [RTP stream] data.
    ///
    /// [RTP stream]: https://w3.org/TR/webrtc-stats#dfn-rtp-stream
    #[serde(flatten)]
    pub stream: RtcRtpStreamStats,

    /// Total number of [RTP] packets sent for this [SSRC].
    ///
    /// This includes retransmissions.
    ///
    /// Calculated as defined in [RFC3550 Section 6.4.1][1].
    ///
    /// [RTP]: https://webrtcglossary.com/rtp
    /// [SSRC]: https://w3.org/TR/webrtc-stats#dfn-ssrc
    /// [1]: https://rfc-editor.org/rfc/rfc3550#section-6.4.1
    pub packets_sent: Option<u64>,

    /// Total number of bytes sent for this [SSRC].
    ///
    /// This includes retransmissions.
    ///
    /// Calculated as defined in [RFC3550 Section 6.4.1][1].
    ///
    /// [SSRC]: https://w3.org/TR/webrtc-stats#dfn-ssrc
    /// [1]: https://rfc-editor.org/rfc/rfc3550#section-6.4.1
    pub bytes_sent: Option<u64>,
}

/// Codecs are created when registered for an [RTP] transport, but only the
/// subset of codecs that are in use (referenced by an [RTP stream]) are exposed
/// in [getStats()].
///
/// The [`RtcCodecStats`] object is created when one or more
/// [`RtcRtpStreamStats::codec_id`] references the codec. When there no longer
/// exists any reference to the [`RtcCodecStats`], the stats object is deleted.
/// If the same codec is used again in the future, the [`RtcCodecStats`] object
/// is revived with the same [`StatId`] as before.
///
/// Codec objects may be referenced by multiple [RTP stream]s in media sections
/// using the same transport, but similar codecs in different transports have
/// different [`RtcCodecStats`] objects.
///
/// [Full doc on W3C][spec].
///
/// [getStats()]: https://tinyurl.com/webrtc-rfc-get-stats
/// [RTP]: https://webrtcglossary.com/rtp
/// [RTP stream]: https://w3.org/TR/webrtc-stats#dfn-rtp-stream
/// [spec]: https://w3.org/TR/webrtc-stats#dom-rtccodecstats
#[expect(clippy::module_name_repetitions, reason = "spec compliance")]
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RtcCodecStats {
    /// Payload type as used in [RTP] encoding or decoding.
    ///
    /// [RTP]: https://webrtcglossary.com/rtp
    pub payload_type: u32,

    /// Unique identifier of the transport on which this codec is being used,
    /// which can be used to look up the corresponding [`RtcTransportStats`]
    /// object.
    pub transport_id: String,

    /// Codec MIME media type/subtype defined in the IANA media types registry
    /// [IANA-MEDIA-TYPES][0], e.g. `video/VP8`.
    ///
    /// [0]: https://iana.org/assignments/media-types/media-types.xhtml
    pub mime_type: String,

    /// Media sampling rate.
    pub clock_rate: Option<u32>,

    /// Number of channels (mono=1, stereo=2).
    pub channels: Option<u32>,

    /// The "format specific parameters" field from the `a=fmtp` line in the
    /// SDP corresponding to the codec, if one exists, as
    /// [defined by RFC8829][1].
    ///
    /// [1]: https://rfc-editor.org/rfc/rfc8829#section-5.8
    pub sdp_fmtp_line: Option<String>,
}

/// Measurement metrics for an incoming media [RTP stream].
///
/// The timestamp reported in the statistics object is the time at which the
/// data was sampled.
///
/// [Full doc on W3C][spec].
///
/// [RTP stream]: https://w3.org/TR/webrtc-stats#dfn-rtp-stream
/// [spec]: https://w3.org/TR/webrtc-stats#dom-rtcoutboundrtpstreamstats
#[expect(clippy::module_name_repetitions, reason = "spec compliance")]
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Deserialize, Hash, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RtcInboundRtpStreamStats {
    /// Generic ingress [RTP stream] data.
    ///
    /// [RTP stream]: https://w3.org/TR/webrtc-stats#dfn-rtp-stream
    #[serde(flatten)]
    pub received_stream: RtcReceivedRtpStreamStats,

    /// Media kind specific part of these [`RtcInboundRtpStreamStats`].
    #[serde(flatten)]
    pub media_specific: InboundRtpMediaType,

    /// [`id` attribute][2] value of the [MediaStreamTrack][1].
    ///
    /// [1]: https://w3.org/TR/mediacapture-streams#mediastreamtrack
    /// [2]: https://w3.org/TR/mediacapture-streams#dom-mediastreamtrack-id
    pub track_identifier: Option<String>,

    /// [mid] value of the [RTCRtpTransceiver][0] owning this stream.
    ///
    /// If the [RTCRtpTransceiver][0] owning this stream has a [mid] value that
    /// is not `null`, this is that value, otherwise this member MUST NOT be
    /// present.
    ///
    /// [mid]: https://w3.org/TR/webrtc#dom-rtptransceiver-mid
    /// [0]: https://w3.org/TR/webrtc#rtcrtptransceiver-interface
    pub mid: Option<String>,

    /// Identifier for looking up the remote [`RtcRemoteOutboundRtpStreamStats`]
    /// object for the same [SSRC].
    ///
    /// [SSRC]: https://w3.org/TR/webrtc-stats#dfn-ssrc
    pub remote_id: Option<String>,

    /// Total number of bytes received for this [SSRC].
    ///
    /// This includes retransmissions.
    ///
    /// Calculated as defined in [RFC3550 Section 6.4.1][1].
    ///
    /// [SSRC]: https://w3.org/TR/webrtc-stats#dfn-ssrc
    /// [1]: https://rfc-editor.org/rfc/rfc3550#section-6.4.1
    pub bytes_received: Option<u64>,

    /// Total number of audio samples or video frames that have come out of the
    /// jitter buffer (increasing the [`jitter_buffer_delay`][1]).
    ///
    /// [1]: RtcInboundRtpStreamStats::jitter_buffer_delay
    pub jitter_buffer_emitted_count: Option<u64>,

    /// Sum of the time, in seconds, each [audio sample] or a video frame takes
    /// from the time the first packet is received by the jitter buffer (ingest
    /// timestamp) to the time it exits the jitter buffer (emit timestamp).
    ///
    /// The purpose of the jitter buffer is to recombine [RTP] packets into
    /// frames (in the case of video) and have smooth playout. The model
    /// described here assumes that the samples or frames are still compressed
    /// and have not yet been decoded.
    ///
    /// In the case of audio, several samples belong to the same [RTP] packet,
    /// hence they will have the same ingest timestamp but different jitter
    /// buffer emit timestamps.
    ///
    /// In the case of video, the frame may be received over several [RTP]
    /// packets, hence the ingest timestamp is the earliest packet of the frame
    /// that entered the jitter buffer and the emit timestamp is when the whole
    /// frame exits the jitter buffer.
    ///
    /// This metric increases upon samples or frames exiting, having completed
    /// their time in the buffer (and incrementing the
    /// [`jitter_buffer_emitted_count`][1]).
    ///
    /// The average jitter buffer delay can be calculated by dividing the
    /// [`jitter_buffer_delay`][2] with the [`jitter_buffer_emitted_count`][1].
    ///
    /// [audio sample]: https://w3.org/TR/webrtc-stats#dfn-audio-sample
    /// [RTP]: https://webrtcglossary.com/rtp
    /// [1]: RtcInboundRtpStreamStats::jitter_buffer_emitted_count
    /// [2]: RtcInboundRtpStreamStats::jitter_buffer_delay
    pub jitter_buffer_delay: Option<Double>,

    /// Cumulative time of delays, in seconds, at the time that a sample is
    /// emitted from the jitter buffer.
    ///
    /// This value is increased by the target jitter buffer delay every time a
    /// sample is emitted by the jitter buffer. The added target is the target
    /// delay, in seconds, at the time that the sample was emitted from the
    /// jitter buffer.
    ///
    /// To get the average target delay, divide by
    /// [`jitter_buffer_emitted_count`][1].
    ///
    /// [1]: RtcInboundRtpStreamStats::jitter_buffer_emitted_count
    pub jitter_buffer_target_delay: Option<Double>,

    /// Minimum jitter buffer delay, in seconds.
    ///
    /// There are various reasons why the jitter buffer delay might be increased
    /// to a higher value, such as to achieve A/V synchronization or because a
    /// [jitterBufferTarget][0] was set on an [RTCRtpReceiver]. When using
    /// one of these mechanisms, it can be useful to keep track of the minimal
    /// jitter buffer delay that could have been achieved, so clients can track
    /// the amount of additional delay that is being added.
    ///
    /// This metric works the same way as the [`jitter_buffer_target_delay`][1],
    /// except that it is not affected by external mechanisms that increase the
    /// jitter buffer target delay, such as [jitterBufferTarget][0], A/V sync,
    /// or any other mechanisms. This metric is purely based on the network
    /// characteristics such as jitter and packet loss, and can be seen as the
    /// minimum obtainable jitter buffer delay if no external factors would
    /// affect it.
    ///
    /// This metric is updated every time the [`jitter_buffer_emitted_count`][2]
    /// is updated.
    ///
    /// [RTCRtpReceiver]: https://w3.org/TR/webrtc#rtcrtpreceiver-interface
    /// [0]: https://w3.org/TR/webrtc#dom-rtcrtpreceiver-jitterbuffertarget
    /// [1]: RtcInboundRtpStreamStats::jitter_buffer_target_delay
    /// [2]: RtcInboundRtpStreamStats::jitter_buffer_emitted_count
    pub jitter_buffer_minimum_delay: Option<Double>,

    /// Total number of [RTP] header and padding bytes received for this [SSRC].
    ///
    /// This includes retransmissions. Does not include transport headers
    /// (IP/UDP). [`header_bytes_received`][1] + [`bytes_received`][2] equals
    /// the total number of bytes received as payload over the transport.
    ///
    /// [RTP]: https://webrtcglossary.com/rtp
    /// [SSRC]: https://w3.org/TR/webrtc-stats#dfn-ssrc
    /// [1]: RtcInboundRtpStreamStats::header_bytes_received
    /// [2]: RtcInboundRtpStreamStats::bytes_received
    pub header_bytes_received: Option<u64>,

    /// Cumulative number of [RTP] packets discarded by the jitter buffer due to
    /// late or early-arrival, i.e. these packets are not played out.
    ///
    /// [RTP] packets discarded due to packet duplication are not reported in
    /// this metric [XRBLOCK-STATS].
    ///
    /// Calculated as defined in [RFC7002 Section 3.2][1] and [Appendix A.a][2].
    ///
    /// [RTP]: https://webrtcglossary.com/rtp
    /// [XRBLOCK-STATS]: https://tinyurl.com/xr-report
    /// [1]: https://rfc-editor.org/rfc/rfc7002#section-3.2
    /// [2]: https://rfc-editor.org/rfc/rfc7002#appendix-A
    pub packets_discarded: Option<u64>,

    /// Timestamp at which the last [RTP] packet was received for this [SSRC].
    ///
    /// This differs from the [`RtcStat::timestamp`], which represents the time
    /// at which the statistics were generated or received by the local
    /// endpoint.
    ///
    /// [RTP]: https://webrtcglossary.com/rtp
    /// [SSRC]: https://w3.org/TR/webrtc-stats#dfn-ssrc
    pub last_packet_received_timestamp: Option<HighResTimeStamp>,

    /// Estimated playout time of this receiver's track in sender [NTP] time.
    ///
    /// Can be used to estimate A/V sync across tracks from the same source.
    ///
    /// [NTP]: https://en.wikipedia.org/wiki/Network_Time_Protocol
    pub estimated_playout_timestamp: Option<HighResTimeStamp>,

    /// Total number of [RTP] FEC bytes received for this [SSRC], only including
    /// payload bytes.
    ///
    /// This is a subset of the [`bytes_received`][1].
    ///
    /// If FEC uses a different [SSRC], packets are still accounted for here.
    ///
    /// [RTP]: https://webrtcglossary.com/rtp
    /// [SSRC]: https://w3.org/TR/webrtc-stats#dfn-ssrc
    /// [1]: RtcInboundRtpStreamStats::bytes_received
    pub fec_bytes_received: Option<u64>,

    /// Total number of [RTP] FEC packets received for this [SSRC].
    ///
    /// If FEC uses a different [SSRC], packets are still accounted for here.
    ///
    /// Can also increment when receiving in-band FEC (for example, [Opus]).
    ///
    /// [Opus]: https://en.wikipedia.org/wiki/Opus_(audio_format)
    /// [RTP]: https://webrtcglossary.com/rtp
    /// [SSRC]: https://w3.org/TR/webrtc-stats#dfn-ssrc
    pub fec_packets_received: Option<u64>,

    /// Total number of [RTP] FEC packets received for this [SSRC] where the
    /// error correction payload was discarded (for example, sources already
    /// recovered or FEC arrived late).
    ///
    /// This is a subset of the [`fec_bytes_received`][1].
    ///
    /// [RTP]: https://webrtcglossary.com/rtp
    /// [SSRC]: https://w3.org/TR/webrtc-stats#dfn-ssrc
    /// [1]: RtcInboundRtpStreamStats::fec_bytes_received
    pub fec_packets_discarded: Option<u64>,

    /// Sum of the time, in seconds, each [audio sample] or video frame takes
    /// from the time the first [RTP] packet is received (reception timestamp)
    /// and to the time the corresponding sample or frame is decoded (decoded
    /// timestamp).
    ///
    /// At this point the audio sample or video frame is ready for playout by
    /// the [MediaStreamTrack][1]. Typically ready for playout here means after
    /// the audio sample or video frame is fully decoded by the decoder.
    ///
    /// [audio sample]: https://w3.org/TR/webrtc-stats#dfn-audio-sample
    /// [RTP]: https://webrtcglossary.com/rtp
    /// [1]: https://w3.org/TR/mediacapture-streams#mediastreamtrack
    pub total_processing_delay: Option<Double>,

    /// Total number of [Negative ACKnowledgement (NACK)][1] [RTCP] feedback
    /// packets sent by this receiver for this [SSRC], as defined in
    /// [RFC4585 Section 6.2.1][0].
    ///
    /// [RTCP]: https://webrtcglossary.com/rtcp
    /// [SSRC]: https://w3.org/TR/webrtc-stats#dfn-ssrc
    /// [0]: https://rfc-editor.org/rfc/rfc4585#section-6.2.1
    /// [1]: https://bloggeek.me/webrtcglossary/nack
    pub nack_count: Option<u32>,

    /// Total number of retransmitted packets that were received for this
    /// [SSRC].
    ///
    /// This is a subset of the [`RtcReceivedRtpStreamStats::packets_received`].
    ///
    /// If RTX is not negotiated, retransmitted packets can not be identified
    /// and this member MUST NOT exist.
    ///
    /// [SSRC]: https://w3.org/TR/webrtc-stats#dfn-ssrc
    pub retransmitted_packets_received: Option<u64>,

    /// Total number of retransmitted bytes that were received for this [SSRC],
    /// only including payload bytes.
    ///
    /// This is a subset of the [`bytes_received`][1].
    ///
    /// If RTX is not negotiated, retransmitted packets can not be identified
    /// and this member MUST NOT exist.
    ///
    /// [SSRC]: https://w3.org/TR/webrtc-stats#dfn-ssrc
    /// [1]: RtcInboundRtpStreamStats::bytes_received
    pub retransmitted_bytes_received: Option<u64>,

    /// [SSRC] of the RTX stream that is associated with this stream's [SSRC].
    ///
    /// If RTX is negotiated for retransmissions on a separate [RTP stream],
    /// this is the [SSRC] of the RTX stream that is associated with this
    /// stream's [SSRC].
    ///
    /// If RTX is not negotiated, this value MUST NOT be present.
    ///
    /// [RTP stream]: https://w3.org/TR/webrtc-stats#dfn-rtp-stream
    /// [SSRC]: https://w3.org/TR/webrtc-stats#dfn-ssrc
    pub rtx_ssrc: Option<u32>,

    /// [SSRC] of the FEC stream that is associated with this stream's [SSRC].
    ///
    /// If a FEC mechanism that uses a separate [RTP stream] is negotiated, this
    /// is the [SSRC] of the FEC stream that is associated with this stream's
    /// [SSRC].
    ///
    /// If FEC is not negotiated or uses the same [RTP stream], this value MUST
    /// NOT be present.
    ///
    /// [RTP stream]: https://w3.org/TR/webrtc-stats#dfn-rtp-stream
    /// [SSRC]: https://w3.org/TR/webrtc-stats#dfn-ssrc
    pub fec_ssrc: Option<u32>,
}

/// Measurement metrics for the outgoing [RTP stream].
///
/// The timestamp reported in the statistics object is the time at which the
/// data was sampled.
///
/// [Full doc on W3C][spec].
///
/// [RTP stream]: https://w3.org/TR/webrtc-stats#dfn-rtp-stream
/// [spec]: https://w3.org/TR/webrtc-stats#dom-rtcoutboundrtpstreamstats
#[expect(clippy::module_name_repetitions, reason = "spec compliance")]
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Deserialize, Hash, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RtcOutboundRtpStreamStats {
    /// Generic egress [RTP stream] data.
    ///
    /// [RTP stream]: https://w3.org/TR/webrtc-stats#dfn-rtp-stream
    #[serde(flatten)]
    pub sent_stream: RtcSentRtpStreamStats,

    /// Media kind specific part of these [`RtcOutboundRtpStreamStats`].
    #[serde(flatten)]
    pub media_specific: OutboundRtpMediaType,

    /// [mid] value of the [RTCRtpTransceiver][0] owning this stream.
    ///
    /// If the [RTCRtpTransceiver][0] owning this stream has a [mid] value that
    /// is not `null`, this is that value, otherwise this member MUST NOT be
    /// present.
    ///
    /// [mid]: https://w3.org/TR/webrtc#dom-rtptransceiver-mid
    /// [0]: https://w3.org/TR/webrtc#rtcrtptransceiver-interface
    pub mid: Option<String>,

    /// Identifier of the stats object representing the track currently attached
    /// to the sender of this stream, an [`RtcMediaSourceStats`].
    pub media_source_id: Option<String>,

    /// Identifier for looking up the remote [`RtcRemoteInboundRtpStreamStats`]
    /// object for the same [SSRC].
    ///
    /// [SSRC]: https://w3.org/TR/webrtc-stats#dfn-ssrc
    pub remote_id: Option<String>,

    /// Total number of [RTP] header and padding bytes sent for this [SSRC].
    ///
    /// This does not include the size of transport layer headers such as IP or
    /// UDP.
    ///
    /// [`header_bytes_sent`] + [`RtcSentRtpStreamStats::bytes_sent`] equals the
    /// number of bytes sent as payload over the transport.
    ///
    /// [`header_bytes_sent`]: RtcOutboundRtpStreamStats::header_bytes_sent
    /// [RTP]: https://webrtcglossary.com/rtp
    /// [SSRC]: https://w3.org/TR/webrtc-stats#dfn-ssrc
    pub header_bytes_sent: Option<u64>,

    /// Total number of packets that were retransmitted for this [SSRC].
    ///
    /// This is a subset of the [`RtcSentRtpStreamStats::packets_sent`].
    ///
    /// If RTX is not negotiated, retransmitted packets are sent over this
    /// [SSRC].
    ///
    /// If RTX was negotiated, retransmitted packets are sent over a separate
    /// [SSRC] but is still accounted for here.
    ///
    /// [SSRC]: https://w3.org/TR/webrtc-stats#dfn-ssrc
    pub retransmitted_packets_sent: Option<u64>,

    /// Total number of bytes that were retransmitted for this [SSRC], only
    /// including payload bytes.
    ///
    /// This is a subset of [`RtcSentRtpStreamStats::bytes_sent`].
    ///
    /// If RTX is not negotiated, retransmitted bytes are sent over this [SSRC].
    ///
    /// If RTX was negotiated, retransmitted bytes are sent over a separate
    /// [SSRC] but is still accounted for here.
    ///
    /// [SSRC]: https://w3.org/TR/webrtc-stats#dfn-ssrc
    pub retransmitted_bytes_sent: Option<u64>,

    /// [SSRC] of the RTX stream that is associated with this stream's [SSRC].
    ///
    /// If RTX is negotiated for retransmissions on a separate [RTP stream],
    /// this is the [SSRC] of the RTX stream that is associated with this
    /// stream's [SSRC].
    ///
    /// If RTX is not negotiated, this value MUST NOT be present.
    ///
    /// [RTP stream]: https://w3.org/TR/webrtc-stats#dfn-rtp-stream
    /// [SSRC]: https://w3.org/TR/webrtc-stats#dfn-ssrc
    pub rtx_ssrc: Option<u32>,

    /// Current encoder target in bits per second.
    ///
    /// The target is an instantaneous value reflecting the encoder's settings,
    /// but the resulting payload bytes sent per second, excluding
    /// retransmissions, SHOULD closely correlate to the target.
    ///
    /// See also the [`RtcSentRtpStreamStats::bytes_sent`] and the
    /// [`retransmitted_bytes_sent`][1].
    ///
    /// This is defined in the same way as the ["TIAS" bitrate RFC3890][0].
    ///
    /// [0]: https://rfc-editor.org/rfc/rfc3890#section-6.2
    /// [1]: RtcOutboundRtpStreamStats::retransmitted_bytes_sent
    pub target_bitrate: Option<Double>,

    /// Total number of seconds that packets have spent buffered locally before
    /// being transmitted onto the network.
    ///
    /// The time is measured from when a packet is emitted from the [RTP]
    /// packetizer until it is handed over to the OS network socket. This
    /// measurement is added to [`total_packet_send_delay`][1] when
    /// [`RtcSentRtpStreamStats::packets_sent`] is incremented.
    ///
    /// [RTP]: https://webrtcglossary.com/rtp
    /// [1]: RtcOutboundRtpStreamStats::total_packet_send_delay
    pub total_packet_send_delay: Option<Double>,

    /// Total number of [Negative ACKnowledgement (NACK)][1] packets, as defined
    /// in [RFC4585 Section 6.2.1][0], received by this sender.
    ///
    /// [0]: https://rfc-editor.org/rfc/rfc4585#section-6.2.1
    /// [1]: https://bloggeek.me/webrtcglossary/nack
    pub nack_count: Option<u32>,

    /// Indicates whether this [RTP stream] is configured to be sent or
    /// disabled.
    ///
    /// Note that an active stream can still not be sending, e.g. when being
    /// limited by network conditions.
    ///
    /// [RTP stream]: https://w3.org/TR/webrtc-stats#dfn-rtp-stream
    pub active: Option<bool>,

    /// Total number of [RTP] packets sent for this [SSRC] with the [ECT(1)][1]
    /// marking defined in [RFC3168 Section 5][2] and used by the L4S protocol
    /// described in [RFC9331].
    ///
    /// [RFC9331]: https://rfc-editor.org/rfc/rfc9331
    /// [RTP]: https://webrtcglossary.com/rtp
    /// [SSRC]: https://w3.org/TR/webrtc-stats#dfn-ssrc
    /// [1]: https://rfc-editor.org/rfc/rfc3168#section-3
    /// [2]: https://rfc-editor.org/rfc/rfc3168#section-5
    pub packets_sent_with_ect1: Option<u64>,
}

/// Remote endpoint's measurement metrics for a particular incoming [RTP stream]
/// (corresponding to an outgoing [RTP stream] at the sending endpoint).
///
/// The timestamp reported in the statistics object is the time at which the
/// corresponding [RTCP RR] was received.
///
/// [Full doc on W3C][spec].
///
/// [RTP stream]: https://w3.org/TR/webrtc-stats#dfn-rtp-stream
/// [RTCP RR]: https://w3.org/TR/webrtc-stats#dfn-receiver-report
/// [spec]: https://w3.org/TR/webrtc-stats#dom-rtcremoteinboundrtpstreamstats
#[expect(clippy::module_name_repetitions, reason = "spec compliance")]
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Deserialize, Hash, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RtcRemoteInboundRtpStreamStats {
    /// Generic ingress [RTP stream] data.
    ///
    /// [RTP stream]: https://w3.org/TR/webrtc-stats#dfn-rtp-stream
    #[serde(flatten)]
    pub received_stream: RtcReceivedRtpStreamStats,

    /// Identifier of the local [`RtcOutboundRtpStreamStats`] object for the
    /// same [SSRC].
    ///
    /// [SSRC]: https://w3.org/TR/webrtc-stats#dfn-ssrc
    pub local_id: Option<String>,

    /// Estimated round trip time for this [SSRC] based on the [RTCP] timestamps
    /// in the [RTCP Receiver Report][0] (RR) and measured in seconds.
    ///
    /// Calculated as defined in [Section 6.4.1 of RFC3550][1].
    ///
    /// MUST NOT exist until a [RTCP Receiver Report][0] is received with a
    /// DLSR value other than `0` has been received.
    ///
    /// [RTCP]: https://webrtcglossary.com/rtcp
    /// [SSRC]: https://w3.org/TR/webrtc-stats#dfn-ssrc
    /// [0]: https://w3.org/TR/webrtc-stats#dfn-receiver-report
    /// [1]: https://rfc-editor.org/rfc/rfc3550#section-6.4.1
    pub round_trip_time: Option<Double>,

    /// Cumulative sum of all round trip time measurements in seconds since the
    /// beginning of the session.
    ///
    /// The individual round trip time is calculated based on the [RTCP]
    /// timestamps in the [RTCP Receiver Report][0] (RR) [RFC3550], hence
    /// requires a DLSR value other than `0`.
    ///
    /// The average round trip time can be computed from the
    /// [`total_round_trip_time`][1] by dividing it by
    /// [`round_trip_time_measurements`][2].
    ///
    /// [RFC3550]: https://rfc-editor.org/rfc/rfc3550
    /// [RTCP]: https://webrtcglossary.com/rtcp
    /// [0]: https://w3.org/TR/webrtc-stats#dfn-receiver-report
    /// [1]: RtcRemoteInboundRtpStreamStats::total_round_trip_time
    /// [2]: RtcRemoteInboundRtpStreamStats::round_trip_time_measurements
    pub total_round_trip_time: Option<Double>,

    /// Fraction packet loss reported for this [SSRC].
    ///
    /// Calculated as defined in [RFC3550 Section 6.4.1][1] and
    /// [Appendix A.3][2].
    ///
    /// [SSRC]: https://w3.org/TR/webrtc-stats#dfn-ssrc
    /// [1]: https://rfc-editor.org/rfc/rfc3550#section-6.4.1
    /// [2]: https://rfc-editor.org/rfc/rfc3550#appendix-A.3
    pub fraction_lost: Option<Double>,

    /// Total number of [RTCP RR] blocks received for this [SSRC] that contain a
    /// valid round trip time.
    ///
    /// This counter will not increment if the [`round_trip_time`][1] can not be
    /// calculated because no [RTCP Receiver Report][0] with a DLSR value other
    /// than `0` has been received.
    ///
    /// [RTCP RR]: https://w3.org/TR/webrtc-stats#dfn-receiver-report
    /// [SSRC]: https://w3.org/TR/webrtc-stats#dfn-ssrc
    /// [0]: https://w3.org/TR/webrtc-stats#dfn-receiver-report
    /// [1]: RtcRemoteInboundRtpStreamStats::round_trip_time
    pub round_trip_time_measurements: Option<u64>,

    /// Number of packets that were sent with [ECT(1)][2] markings per
    /// [RFC3168 Section 3][1], but where an [RFC8888] report gave information
    /// that the packet was received with a marking of "not-ECT".
    ///
    /// [RFC8888]: https://rfc-editor.org/rfc/rfc8888
    /// [1]: https://rfc-editor.org/rfc/rfc3168#section-3
    /// [2]: https://rfc-editor.org/rfc/rfc3168#section-5
    pub packets_with_bleached_ect1_marking: Option<u64>,
}

/// Remote endpoint's measurement metrics for its outgoing [RTP stream]
/// (corresponding to an outgoing [RTP stream] at the sending endpoint).
///
/// The timestamp reported in this statistics object is the time at which the
/// corresponding [RTCP SR] was received.
///
/// [Full doc on W3C][spec].
///
/// [RTP stream]: https://w3.org/TR/webrtc-stats#dfn-rtp-stream
/// [RTCP SR]: https://w3.org/TR/webrtc-stats#dfn-sender-report
/// [spec]: https://w3.org/TR/webrtc-stats#dom-rtcremoteoutboundrtpstreamstats
#[expect(clippy::module_name_repetitions, reason = "spec compliance")]
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Deserialize, Hash, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RtcRemoteOutboundRtpStreamStats {
    /// Generic egress [RTP stream] data.
    ///
    /// [RTP stream]: https://w3.org/TR/webrtc-stats#dfn-rtp-stream
    #[serde(flatten)]
    pub sent_stream: RtcSentRtpStreamStats,

    /// Identifier of the local [`RtcInboundRtpStreamStats`] object for the same
    /// [SSRC].
    ///
    /// [SSRC]: https://w3.org/TR/webrtc-stats#dfn-ssrc
    pub local_id: Option<String>,

    /// Remote timestamp at which these statistics were sent by the remote
    /// endpoint.
    ///
    /// This differs from the [`RtcStat::timestamp`], which represents the time
    /// at which the statistics were generated or received by the local
    /// endpoint.
    ///
    /// The remote timestamp, if present, is derived from the [NTP] timestamp in
    /// an [RTCP Sender Report] (SR) block, which reflects the remote endpoint's
    /// clock. That clock may not be synchronized with the local clock.
    ///
    /// [NTP]: https://en.wikipedia.org/wiki/Network_Time_Protocol
    /// [RTCP Sender Report]: https://w3.org/TR/webrtc-stats#dfn-sender-report
    pub remote_timestamp: Option<HighResTimeStamp>,

    /// Total number of [RTCP Sender Report] (SR) blocks sent for this [SSRC].
    ///
    /// [RTCP Sender Report]: https://w3.org/TR/webrtc-stats#dfn-sender-report
    /// [SSRC]: https://w3.org/TR/webrtc-stats#dfn-ssrc
    pub reports_sent: Option<u64>,

    /// Estimated round trip time for this [SSRC] based on the latest
    /// [RTCP Sender Report] (SR) that contains a [DLRR report block][1] as
    /// defined in [RFC3611].
    ///
    /// The calculation of the round trip time is defined in
    /// [Section 4.5 of RFC3611][1].
    ///
    /// MUST NOT exist if the latest SR does not contain the
    /// [DLRR report block][1], or if the last RR timestamp in the
    /// [DLRR report block][1] is zero, or if the delay since last RR value in
    /// the [DLRR report block][1] is zero.
    ///
    /// [SSRC]: https://w3.org/TR/webrtc-stats#dfn-ssrc
    /// [RFC3611]: https://rfc-editor.org/rfc/rfc3611
    /// [RTCP Sender Report]: https://w3.org/TR/webrtc-stats#dfn-sender-report
    /// [1]: https://www.rfc-editor.org/rfc/rfc3611#section-4.5
    pub round_trip_time: Option<Double>,

    /// Cumulative sum of all round trip time measurements in seconds since the
    /// beginning of the session.
    ///
    /// The individual round trip time is calculated based on the
    /// [DLRR report block][1] in the [RTCP Sender Report] (SR) [RFC3611].
    ///
    /// This counter will not increment if the [`round_trip_time`][2] can not be
    /// calculated. The average round trip time can be computed from the
    /// [`total_round_trip_time`][3] by dividing it by
    /// [`round_trip_time_measurements`][4].
    ///
    /// [RFC3611]: https://rfc-editor.org/rfc/rfc3611
    /// [RTCP Sender Report]: https://w3.org/TR/webrtc-stats#dfn-sender-report
    /// [1]: https://www.rfc-editor.org/rfc/rfc3611#section-4.5
    /// [2]: RtcRemoteOutboundRtpStreamStats::round_trip_time
    /// [3]: RtcRemoteOutboundRtpStreamStats::total_round_trip_time
    /// [4]: RtcRemoteOutboundRtpStreamStats::round_trip_time_measurements
    pub total_round_trip_time: Option<Double>,

    /// Total number of [RTCP Sender Report] (SR) blocks received for this
    /// [SSRC] that contain a [DLRR report block][1] that can derive a valid
    /// round trip time according to [RFC3611].
    ///
    /// This counter will not increment if the [`round_trip_time`][2] can not be
    /// calculated.
    ///
    /// [RFC3611]: https://rfc-editor.org/rfc/rfc3611
    /// [RTCP Sender Report]: https://w3.org/TR/webrtc-stats#dfn-sender-report
    /// [SSRC]: https://w3.org/TR/webrtc-stats#dfn-ssrc
    /// [1]: https://www.rfc-editor.org/rfc/rfc3611#section-4.5
    /// [2]: RtcRemoteOutboundRtpStreamStats::round_trip_time
    pub round_trip_time_measurements: Option<u64>,
}

/// Statistics of a track that is currently attached to one or more senders.
///
/// It contains information about media sources such as frame rate and
/// resolution prior to encoding. This is the media passed from the
/// [MediaStreamTrack][1] to the [RTCRtpSender]s. This is in contrast to
/// [`RtcOutboundRtpStreamStats`] whose members describe metrics as measured
/// after the encoding step. For example, a track may be captured from a
/// high-resolution camera, its frames downscaled due to track constraints and
/// then further downscaled by the encoders due to CPU and network conditions.
/// This dictionary reflects the video frames or [audio sample]s passed out from
/// the track - after track constraints have been applied but before any
/// encoding or further downsampling occurs.
///
/// [Full doc on W3C][spec].
///
/// [audio sample]: https://w3.org/TR/webrtc-stats#dfn-audio-sample
/// [RTCRtpSender]: https://w3.org/TR/webrtc#dom-rtcrtpsender
/// [spec]: https://w3.org/TR/webrtc-stats#dom-rtcmediasourcestats
/// [1]: https://w3.org/TR/mediacapture-streams#mediastreamtrack
#[expect(clippy::module_name_repetitions, reason = "spec compliance")]
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Deserialize, Hash, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RtcMediaSourceStats {
    /// [`id` attribute][2] value of the [MediaStreamTrack][1].
    ///
    /// [1]: https://w3.org/TR/mediacapture-streams#mediastreamtrack
    /// [2]: https://w3.org/TR/mediacapture-streams#dom-mediastreamtrack-id
    pub track_identifier: Option<String>,

    /// Fields which should be in the [`RtcStat`] based on its `kind`.
    #[serde(flatten)]
    pub kind: MediaSourceKind,
}

/// Statistics of one playout path.
///
/// If the same playout statistics object is referenced by multiple
/// [`RtcInboundRtpStreamStats`] this is an indication that audio mixing is
/// happening in which case sample counters in this statistics object refer to
/// the samples after mixing.
///
/// [Full doc on W3C][spec].
///
/// [spec]: https://w3.org/TR/webrtc-stats#dom-rtcaudioplayoutstats
#[expect(clippy::module_name_repetitions, reason = "spec compliance")]
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Hash, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct RtcAudioPlayoutStats {
    /// For audio playout, this has the value `audio`.
    ///
    /// This reflects the [`kind` attribute][1] of the [MediaStreamTrack][0]
    /// being played out.
    ///
    /// [0]: https://w3.org/TR/mediacapture-streams#mediastreamtrack
    /// [1]: https://w3.org/TR/mediacapture-streams#dom-mediastreamtrack-kind
    pub kind: Option<String>,

    /// Total duration, in seconds, of synthesized audio samples that have been
    /// played out.
    ///
    /// If the playout path is unable to produce audio samples on time for
    /// device playout, samples are synthesized to be playout out instead.
    /// [`synthesized_samples_duration`][1] is measured in seconds and is
    /// incremented each time an audio sample is synthesized by this playout
    /// path.
    ///
    /// This metric can be used together with [`total_samples_duration`][2] to
    /// calculate the percentage of played out media being synthesized.
    ///
    /// Synthesization typically only happens if the pipeline is
    /// underperforming. Samples synthesized by the [`RtcInboundRtpStreamStats`]
    /// are not counted for here, but in
    /// [`InboundRtpMediaType::Audio::concealed_samples`].
    ///
    /// [1]: RtcAudioPlayoutStats::synthesized_samples_duration
    /// [2]: RtcAudioPlayoutStats::total_samples_duration
    pub synthesized_samples_duration: Option<Double>,

    /// Number of synthesized samples events.
    ///
    /// This counter increases every time a sample is synthesized after a
    /// non-synthesized sample. That is, multiple consecutive synthesized
    /// samples will increase the [`synthesized_samples_duration`][1] multiple
    /// times but is a single synthesization samples event.
    ///
    /// [1]: RtcAudioPlayoutStats::synthesized_samples_duration
    pub synthesized_samples_events: Option<u32>,

    /// Total duration, in seconds, of all audio samples that have been played
    /// out.
    ///
    /// Includes both synthesized and non-synthesized samples.
    pub total_samples_duration: Option<Double>,

    /// Total estimated delay of the playout path for all audio samples.
    ///
    /// When audio samples are pulled by the playout device, this counter is
    /// incremented with the estimated delay of the playout path for that audio
    /// sample. The playout delay includes the delay from being emitted to the
    /// actual time of playout on the device.
    ///
    /// This metric can be used together with [`total_samples_count`][1] to
    /// calculate the average playout delay per sample.
    ///
    /// [1]: RtcAudioPlayoutStats::total_samples_count
    pub total_playout_delay: Option<Double>,

    /// Total number of samples emitted for playout.
    ///
    /// When audio samples are pulled by the playout device, this counter is
    /// incremented with the number of samples emitted for playout.
    pub total_samples_count: Option<u64>,
}

/// Statistics for an [RTCPeerConnection] object.
///
/// [Full doc on W3C][spec].
///
/// [RTCPeerConnection]: https://w3.org/TR/webrtc#dom-rtcpeerconnection
/// [spec]: https://w3.org/TR/webrtc-stats#dom-rtcpeerconnectionstats
#[expect(clippy::module_name_repetitions, reason = "spec compliance")]
#[serde_with::skip_serializing_none]
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RtcPeerConnectionStats {
    /// Number of unique [RTCDataChannel]s that have entered the
    /// [`open` state][1] during their lifetime.
    ///
    /// [RTCDataChannel]: https://w3.org/TR/webrtc#dom-rtcdatachannel
    /// [1]: https://w3.org/TR/webrtc#dom-rtcdatachannelstate-open
    pub data_channels_opened: Option<u32>,

    /// Number of unique [RTCDataChannel]s that have left the [`open` state][1]
    /// during their lifetime (due to being closed by either end or the
    /// underlying transport being closed).
    ///
    /// [RTCDataChannel]s that transition from [`connecting`][2] to
    /// [`closing`][3] or [`closed`][4] state without ever being [`open`][1] are
    /// not counted in this number.
    ///
    /// [RTCDataChannel]: https://w3.org/TR/webrtc#dom-rtcdatachannel
    /// [1]: https://w3.org/TR/webrtc#dom-rtcdatachannelstate-open
    /// [2]: https://w3.org/TR/webrtc#dom-rtcdatachannelstate-connecting
    /// [3]: https://w3.org/TR/webrtc#dom-rtcdatachannelstate-closing
    /// [4]: https://w3.org/TR/webrtc#dom-rtcdatachannelstate-closed
    pub data_channels_closed: Option<u32>,
}

/// Non-exhaustive version of a [`KnownRtcDataChannelState`].
pub type RtcDataChannelState = NonExhaustive<KnownRtcDataChannelState>;

/// Possible states of [RTCDataChannel]'s underlying data connection.
///
/// [RTCDataChannel]: https://w3.org/TR/webrtc#dom-rtcdatachannel
#[derive(
    Clone, Copy, Debug, Deserialize, Display, Eq, Hash, PartialEq, Serialize,
)]
#[serde(rename_all = "kebab-case")]
pub enum KnownRtcDataChannelState {
    /// User agent is attempting to establish the underlying data transport.
    ///
    /// This is the initial state of an [RTCDataChannel] object, whether created
    /// with [createDataChannel()][1], or dispatched as a part of an
    /// [RTCDataChannelEvent].
    ///
    /// [RTCDataChannel]: https://w3.org/TR/webrtc#dom-rtcdatachannel
    /// [RTCDataChannelEvent]: https://w3.org/TR/webrtc#dom-rtcdatachannelevent
    /// [1]: https://w3.org/TR/webrtc#dom-peerconnection-createdatachannel
    #[display("connecting")]
    Connecting,

    /// [Underlying data transport][1] is established and communication is
    /// possible.
    ///
    /// [1]: https://w3.org/TR/webrtc#dfn-data-transport
    #[display("open")]
    Open,

    /// [Procedure][2] to close down the [underlying data transport][1] has
    /// started.
    ///
    /// [1]: https://w3.org/TR/webrtc#dfn-data-transport
    /// [2]: https://w3.org/TR/webrtc#data-transport-closing-procedure
    #[display("closing")]
    Closing,

    /// [Underlying data transport][1] has been [`closed`][2] or could not be
    /// established.
    ///
    /// [1]: https://w3.org/TR/webrtc#dfn-data-transport
    /// [2]: https://w3.org/TR/webrtc#dom-rtcdatachannelstate-closed
    #[display("closed")]
    Closed,
}

/// Statistics related to each [RTCDataChannel] ID.
///
/// [Full doc on W3C][spec].
///
/// [RTCDataChannel]: https://w3.org/TR/webrtc#dom-rtcdatachannel
/// [spec]: https://w3.org/TR/webrtc-stats#dom-rtcdatachannelstats
#[expect(clippy::module_name_repetitions, reason = "spec compliance")]
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RtcDataChannelStats {
    /// [`label`] value of the [RTCDataChannel] object.
    ///
    /// [RTCDataChannel]: https://w3.org/TR/webrtc#dom-rtcdatachannel
    /// [`label`]: https://w3.org/TR/webrtc#dom-datachannel-label
    pub label: Option<String>,

    /// [`protocol`][1] value of the [RTCDataChannel] object.
    ///
    /// [RTCDataChannel]: https://w3.org/TR/webrtc#dom-rtcdatachannel
    /// [1]: https://w3.org/TR/webrtc#dom-datachannel-protocol
    pub protocol: Option<String>,

    /// [`id`][1] attribute of the [RTCDataChannel] object.
    ///
    /// [RTCDataChannel]: https://w3.org/TR/webrtc#dom-rtcdatachannel
    /// [1]: https://w3.org/TR/webrtc#dom-rtcdatachannel-id
    pub data_channel_identifier: Option<u16>,

    /// [`readyState`][1] value of the [RTCDataChannel] object.
    ///
    /// [RTCDataChannel]: https://w3.org/TR/webrtc#dom-rtcdatachannel
    /// [1]: https://w3.org/TR/webrtc#dom-datachannel-readystate
    pub state: Option<RtcDataChannelState>,

    /// Total number of API `message` events sent.
    pub messages_sent: Option<u32>,

    /// Total number of payload bytes sent on the [RTCDataChannel].
    ///
    /// [RTCDataChannel]: https://w3.org/TR/webrtc#dom-rtcdatachannel
    pub bytes_sent: Option<u64>,

    /// Total number of API `message` events received.
    pub messages_received: Option<u32>,

    /// Total number of bytes received on the [RTCDataChannel].
    ///
    /// [RTCDataChannel]: https://w3.org/TR/webrtc#dom-rtcdatachannel
    pub bytes_received: Option<u64>,
}

/// Statistics corresponding to an [RTCDtlsTransport] and its underlying
/// [RTCIceTransport].
///
/// When bundling is used, a single transport will be used for all
/// [MediaStreamTrack][0]s in the bundle group. If bundling is not used,
/// different [MediaStreamTrack][0]s will use different transports. Bundling is
/// described in [WebRTC].
///
/// [Full doc on W3C][spec].
///
/// [RTCDtlsTransport]: https://w3.org/TR/webrtc#dom-rtcdtlstransport
/// [RTCIceTransport]: https://w3.org/TR/webrtc#dom-rtcicetransport
/// [WebRTC]: https://w3.org/TR/webrtc
/// [spec]: https://w3.org/TR/webrtc-stats#dom-rtctransportstats
/// [0]: https://w3.org/TR/mediacapture-streams#mediastreamtrack
#[expect(clippy::module_name_repetitions, reason = "spec compliance")]
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RtcTransportStats {
    /// Total number of packets sent over the transport.
    pub packets_sent: Option<u64>,

    /// Total number of packets received on the transport.
    pub packets_received: Option<u64>,

    /// Total number of payload bytes sent on the underlying [RTCIceTransport],
    /// i.e. not including headers, padding or [ICE] connectivity checks.
    ///
    /// [ICE]: https://datatracker.ietf.org/doc/html/rfc8445
    /// [RTCIceTransport]: https://w3.org/TR/webrtc#dom-rtcicetransport
    pub bytes_sent: Option<u64>,

    /// Total number of payload bytes received on the underlying
    /// [RTCIceTransport], i.e. not including headers, padding or [ICE]
    /// connectivity checks.
    ///
    /// [ICE]: https://datatracker.ietf.org/doc/html/rfc8445
    /// [RTCIceTransport]: https://w3.org/TR/webrtc#dom-rtcicetransport
    pub bytes_received: Option<u64>,

    /// Current value of the [`role` attribute][1] of the underlying
    /// [RTCIceTransport].
    ///
    /// [RTCIceTransport]: https://w3.org/TR/webrtc#dom-rtcicetransport
    /// [1]: https://w3.org/TR/webrtc#dom-icetransport-role
    pub ice_role: Option<RtcIceRole>,

    /// Current value of the local username fragment used in message validation
    /// procedures [RFC5245] for the underlying [RTCIceTransport].
    ///
    /// It may be updated on [setLocalDescription()][0] and on [ICE] restart.
    ///
    /// [ICE]: https://datatracker.ietf.org/doc/html/rfc8445
    /// [RFC5245]: https://rfc-editor.org/rfc/rfc5245
    /// [RTCIceTransport]: https://w3.org/TR/webrtc#dom-rtcicetransport
    /// [0]: https://w3.org/TR/webrtc#dom-peerconnection-setlocaldescription
    pub ice_local_username_fragment: Option<String>,

    /// Current value of the [`state` attribute][1] of the underlying
    /// [RTCIceTransport].
    ///
    /// [RTCIceTransport]: https://w3.org/TR/webrtc#dom-rtcicetransport
    /// [1]: https://w3.org/TR/webrtc#dom-icetransport-state
    pub ice_state: Option<RtcIceTransportState>,

    /// Current value of the [`state` attribute][1] of the [RTCDtlsTransport].
    ///
    /// [RTCDtlsTransport]: https://w3.org/TR/webrtc#dom-rtcdtlstransport
    /// [1]: https://w3.org/TR/webrtc#dom-rtcdtlstransport-state
    pub dtls_state: Option<RtcDtlsTransportState>,

    /// Unique identifier that is associated to the object that was inspected to
    /// produce the [`RtcIceCandidatePairStats`] associated with the transport.
    pub selected_candidate_pair_id: Option<String>,

    /// Identified of the local certificate for components where [DTLS] is
    /// negotiated.
    ///
    /// [DTLS]: https://webrtcglossary.com/dtls
    pub local_certificate_id: Option<String>,

    /// Identified of the remote certificate for components where [DTLS] is
    /// negotiated.
    ///
    /// [DTLS]: https://webrtcglossary.com/dtls
    pub remote_certificate_id: Option<String>,

    /// Agreed [TLS] version for components where [DTLS] is negotiated.
    ///
    /// It's represented as four upper case hexadecimal digits representing the
    /// two bytes of the version.
    ///
    /// Only present after [DTLS] negotiation is complete.
    ///
    /// [DTLS]: https://webrtcglossary.com/dtls
    /// [TLS]: https://webrtcglossary.com/tls
    pub tls_version: Option<String>,

    /// Descriptive name of the cipher suite used for the [DTLS] transport, as
    /// defined in the
    /// ["Description" column of the IANA cipher suite registry][0].
    ///
    /// [DTLS]: https://webrtcglossary.com/dtls
    /// [0]: https://w3.org/TR/webrtc-stats#bib-iana-tls-ciphers
    pub dtls_cipher: Option<String>,

    /// [`Client`] or [`Server`] depending on the [DTLS] role.
    ///
    /// [`Unknown`] before the [DTLS] negotiation starts.
    ///
    /// [`Client`]: KnownRtcDtlsRole::Client
    /// [`Server`]: KnownRtcDtlsRole::Server
    /// [`Unknown`]: KnownRtcDtlsRole::Unknown
    /// [DTLS]: https://webrtcglossary.com/dtls
    pub dtls_role: Option<RtcDtlsRole>,

    /// Descriptive name of the protection profile used for the [SRTP]
    /// transport, as defined in the
    /// ["Profile" column of the IANA DTLS-SRTP protection profile registry][0]
    /// and described further in [RFC5764].
    ///
    /// [RFC5764]: https://rfc-editor.org/rfc/rfc5764
    /// [SRTP]: https://webrtcglossary.com/srtp
    /// [0]: https://iana.org/assignments/srtp-protection/srtp-protection.xhtml
    pub srtp_cipher: Option<String>,

    /// Number of Transport-Layer Feedback Messages of type
    /// `CongestionControl Feedback Packet`, as described in
    /// [RFC8888 Section 3.1][0], sent on the transport.
    ///
    /// [0]: https://rfc-editor.org/rfc/rfc8888#section-3.1
    pub ccfb_messages_sent: Option<u32>,

    /// Number of Transport-Layer Feedback Messages of type
    /// `CongestionControl Feedback Packet`, as described in
    /// [RFC8888 Section 3.1][0], received on the transport.
    ///
    /// [0]: https://rfc-editor.org/rfc/rfc8888#section-3.1
    pub ccfb_messages_received: Option<u32>,

    /// Number of times that the selected candidate pair of the transport has
    /// changed.
    ///
    /// Going from not having a selected candidate pair to having a selected
    /// candidate pair, or the other way around, also increases this counter.
    /// It is initially zero and becomes one when an initial candidate pair is
    /// selected.
    pub selected_candidate_pair_changes: Option<u32>,
}

/// [ICE] candidate pair statistics related to [RTCIceTransport] objects.
///
/// The candidate pair that is not the current pair for transport is
/// [deleted][1] when the [RTCIceTransport] does an [ICE] restart, at the time
/// the state changes to [`KnownRtcIceTransportState::New`].
///
/// The candidate pair that is the current pair for transport is [deleted][1]
/// after an [ICE] restart when the [RTCIceTransport] switches to using a
/// candidate pair generated from the new candidates; this time doesn't
/// correspond to any other externally observable event.
///
/// [`RtcStatsType::CandidatePair`] variant.
///
/// [Full doc on W3C][spec].
///
/// [ICE]: https://datatracker.ietf.org/doc/html/rfc8445
/// [RTCIceTransport]: https://w3.org/TR/webrtc#dom-rtcicetransport
/// [spec]: https://w3.org/TR/webrtc-stats#dom-rtcicecandidatepairstats
/// [1]: https://w3.org/TR/webrtc-stats#dfn-deleted
#[expect(clippy::module_name_repetitions, reason = "spec compliance")]
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Deserialize, Hash, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RtcIceCandidatePairStats {
    /// Unique identifier associated to the object that was inspected to produce
    /// the [`RtcTransportStats`] associated with this candidates pair.
    pub transport_id: Option<String>,

    /// Unique identifier associated to the object that was inspected to produce
    /// the [`RtcIceCandidateStats`] for the local candidate associated with
    /// this candidates pair.
    pub local_candidate_id: Option<String>,

    /// Unique identifier associated to the object that was inspected to produce
    /// the [`RtcIceCandidateStats`] for the remote candidate associated with
    /// this candidates pair.
    pub remote_candidate_id: Option<String>,

    /// State of the checklist for the local and remote candidates in a pair.
    pub state: RtcStatsIceCandidatePairState,

    /// Related to updating the nominated flag described in
    /// [Section 7.1.3.2.4 of RFC 5245][1].
    ///
    /// [1]: https://tools.ietf.org/html/rfc5245#section-7.1.3.2.4
    pub nominated: Option<bool>,

    /// Priority calculated as defined in [Section 15.1 of RFC 5245][1].
    ///
    /// [1]: https://tools.ietf.org/html/rfc5245#section-15.1
    pub priority: Option<u64>,

    /// Total number of packets sent on this candidate pair.
    pub packets_sent: Option<u64>,

    /// Total number of packets received on this candidate pair.
    pub packets_received: Option<u64>,

    /// Total number of payload bytes sent on this candidate pair, i.e. not
    /// including headers, padding or [ICE] connectivity checks.
    ///
    /// [ICE]: https://datatracker.ietf.org/doc/html/rfc8445
    pub bytes_sent: Option<u64>,

    /// Total number of payload bytes received on this candidate pair, i.e. not
    /// including headers, padding or [ICE] connectivity checks.
    ///
    /// [ICE]: https://datatracker.ietf.org/doc/html/rfc8445
    pub bytes_received: Option<u64>,

    /// Timestamp at which the last packet was sent on this particular candidate
    /// pair, excluding [STUN] packets.
    ///
    /// [STUN]: https://webrtcglossary.com/stun
    pub last_packet_sent_timestamp: Option<HighResTimeStamp>,

    /// Timestamp at which the last packet was received on this particular
    /// candidate pair, excluding [STUN] packets.
    ///
    /// [STUN]: https://webrtcglossary.com/stun
    pub last_packet_received_timestamp: Option<HighResTimeStamp>,

    /// Sum of all round trip time measurements in seconds since the beginning
    /// of the session, based on [STUN] connectivity check [STUN-PATH-CHAR]
    /// responses (`responsesReceived`), including those that reply to requests
    /// that are sent in order to verify consent [RFC7675].
    ///
    /// The average round trip time can be computed from
    /// [`total_round_trip_time`][1] by dividing it by
    /// [`responses_received`][2].
    ///
    /// [RFC7675]: https://tools.ietf.org/html/rfc7675
    /// [STUN]: https://webrtcglossary.com/stun
    /// [STUN-PATH-CHAR]: https://w3.org/TR/webrtc-stats#bib-stun-path-char
    /// [1]: RtcIceCandidatePairStats::total_round_trip_time
    /// [2]: RtcIceCandidatePairStats::responses_received
    pub total_round_trip_time: Option<Double>,

    /// Latest round trip time measured in seconds, computed from both [STUN]
    /// connectivity checks [STUN-PATH-CHAR], including those that are sent for
    /// consent verification [RFC7675].
    ///
    /// [RFC7675]: https://tools.ietf.org/html/rfc7675
    /// [STUN]: https://webrtcglossary.com/stun
    /// [STUN-PATH-CHAR]: https://w3.org/TR/webrtc-stats#bib-stun-path-char
    pub current_round_trip_time: Option<Double>,

    /// Bitrate calculated by the underlying congestion control by combining the
    /// available bitrate for all the outgoing [RTP stream]s using this
    /// candidate pair.
    ///
    /// The bitrate measurement doesn't count the size of the IP or other
    /// transport layers like TCP or UDP. It's similar to the TIAS defined in
    /// [RFC3890], i.e. it's measured in bits per second and the bitrate is
    /// calculated over a 1-second window. For candidate pairs in use, the
    /// estimate is normally no lower than the bitrate for the packets sent at
    /// [`last_packet_sent_timestamp`][1], but might be higher.
    ///
    /// [RTP stream]: https://w3.org/TR/webrtc-stats#dfn-rtp-stream
    /// [RFC3890]: https://rfc-editor.org/rfc/rfc3890
    /// [1]: RtcIceCandidatePairStats::last_packet_sent_timestamp
    pub available_outgoing_bitrate: Option<Double>,

    /// Bitrate calculated by the underlying congestion control by combining the
    /// available bitrate for all the incoming [RTP stream]s using this
    /// candidate pair.
    ///
    /// The bitrate measurement doesn't count the size of the IP or other
    /// transport layers like TCP or UDP. It's similar to the TIAS defined in
    /// [RFC3890], i.e. it's measured in bits per second and the bitrate is
    /// calculated over a 1-second window. For candidate pairs in use, the
    /// estimate is normally no lower than the bitrate for the packets sent at
    /// [`last_packet_received_timestamp`][1], but might be higher.
    ///
    /// [RTP stream]: https://w3.org/TR/webrtc-stats#dfn-rtp-stream
    /// [RFC3890]: https://rfc-editor.org/rfc/rfc3890
    /// [1]: RtcIceCandidatePairStats::last_packet_received_timestamp
    pub available_incoming_bitrate: Option<Double>,

    /// Total number of connectivity check requests received (including
    /// retransmissions).
    ///
    /// It's impossible for the receiver to tell whether the request was sent in
    /// order to check connectivity or check consent, so all connectivity checks
    /// requests are counted here.
    pub requests_received: Option<u64>,

    /// Total number of connectivity check requests sent (not including
    /// retransmissions).
    pub requests_sent: Option<u64>,

    /// Total number of connectivity check responses received.
    pub responses_received: Option<u64>,

    /// Total number of connectivity check responses sent.
    ///
    /// Since we cannot distinguish connectivity check requests and consent
    /// requests, all responses are counted.
    pub responses_sent: Option<u64>,

    /// Total number of consent requests sent.
    pub consent_requests_sent: Option<u64>,

    /// Total number of packets for this candidate pair that have been discarded
    /// due to socket errors, i.e. a socket error occurred when
    /// handing the packets to the socket.
    ///
    /// This might happen due to various reasons, including full buffer or no
    /// available memory.
    pub packets_discarded_on_send: Option<u32>,

    /// Total number of bytes for this candidate pair that have been discarded
    /// due to socket errors, i.e. a socket error occurred when handing the
    /// packets containing the bytes to the socket.
    ///
    /// This might happen due to various reasons, including full buffer or no
    /// available memory.
    ///
    /// Calculated as defined in [RFC3550 section 6.4.1][1].
    ///
    /// [1]: https://rfc-editor.org/rfc/rfc3550#section-6.4.1
    pub bytes_discarded_on_send: Option<u64>,
}

/// Properties of a `candidate` in [Section 15.1 of RFC5245][1].
///
/// It corresponds to a [RTCIceCandidate] object.
///
/// [Full doc on W3C][spec].
///
/// [RTCIceCandidate]: https://w3.org/TR/webrtc#dom-rtcicecandidate
/// [spec]: https://w3.org/TR/webrtc-stats#dom-rtcicecandidatestats
/// [1]: https://rfc-editor.org/rfc/rfc5245#section-15.1
#[expect(clippy::module_name_repetitions, reason = "spec compliance")]
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RtcIceCandidateStats {
    /// Unique ID that is associated to the object that was inspected to produce
    /// the [`RtcTransportStats`] associated with the candidate.
    pub transport_id: Option<String>,

    /// Address of the candidate, allowing for IPv4 addresses, IPv6 addresses,
    /// and fully qualified domain names (FQDNs).
    ///
    /// See [RFC5245 Section 15.1][1] for details.
    ///
    /// [1]: https://rfc-editor.org/rfc/rfc5245#section-15.1
    pub address: Option<String>,

    /// Port number of the candidate.
    pub port: Option<i32>,

    /// Valid values for transport is one of `udp` and `tcp`.
    ///
    /// Based on the `transport` defined in [RFC5245 Section 15.1][1].
    ///
    /// [1]: https://rfc-editor.org/rfc/rfc5245#section-15.1
    pub protocol: Option<String>,

    /// Type of the [ICE] candidate.
    ///
    /// [ICE]: https://datatracker.ietf.org/doc/html/rfc8445
    pub candidate_type: RtcIceCandidateType,

    /// Priority calculated as defined in [RFC5245 Section 15.1][1].
    ///
    /// [1]: https://rfc-editor.org/rfc/rfc5245#section-15.1
    pub priority: Option<i32>,

    /// For local candidates of type [`KnownRtcIceCandidateType::Srflx`] or type
    /// [`KnownRtcIceCandidateType::Relay`] this is the URL of the [ICE] server
    /// from which the candidate was obtained and defined in [WebRTC].
    ///
    /// For remote candidates, this property MUST NOT be present.
    ///
    /// [ICE]: https://datatracker.ietf.org/doc/html/rfc8445
    /// [WebRTC]: https://w3.org/TR/webrtc
    pub url: Option<String>,

    /// Protocol used by the endpoint to communicate with the [TURN] server.
    ///
    /// This is only present for local relay candidates and defined in [WebRTC].
    ///
    /// For remote candidates, this property MUST NOT be present.
    ///
    /// [TURN]: https://webrtcglossary.com/turn
    /// [WebRTC]: https://w3.org/TR/webrtc
    pub relay_protocol: Option<IceServerTransportProtocol>,

    /// [ICE] foundation as defined in [RFC5245 Section 15.1][1].
    ///
    /// [ICE]: https://datatracker.ietf.org/doc/html/rfc8445
    /// [1]: https://rfc-editor.org/rfc/rfc5245#section-15.1
    pub foundation: Option<String>,

    /// [ICE] `rel-addr` as defined in [RFC5245 Section 15.1][1].
    ///
    /// Only set for [`KnownRtcIceCandidateType::Srflx`],
    /// [`KnownRtcIceCandidateType::Prflx`] and
    /// [`KnownRtcIceCandidateType::Relay`] candidates.
    ///
    /// [ICE]: https://datatracker.ietf.org/doc/html/rfc8445
    /// [1]: https://rfc-editor.org/rfc/rfc5245#section-15.1
    pub related_address: Option<String>,

    /// [ICE] `rel-port` as defined in [RFC5245 Section 15.1][1].
    ///
    /// Only set for [`KnownRtcIceCandidateType::Srflx`],
    /// [`KnownRtcIceCandidateType::Prflx`] and
    /// [`KnownRtcIceCandidateType::Relay`] candidates.
    ///
    /// [ICE]: https://datatracker.ietf.org/doc/html/rfc8445
    /// [1]: https://rfc-editor.org/rfc/rfc5245#section-15.1
    pub related_port: Option<i32>,

    /// [ICE] username fragment as defined in [RFC5245 section 7.1.2.3][1].
    ///
    /// For [`KnownRtcIceCandidateType::Prflx`] remote candidates this is not
    /// set unless the [ICE] username fragment has been previously signaled.
    ///
    /// [ICE]: https://datatracker.ietf.org/doc/html/rfc8445
    /// [1]: https://rfc-editor.org/rfc/rfc5245#section-7.1.2.3
    pub username_fragment: Option<String>,

    /// [ICE] candidate TCP type, as defined іn [`RtcIceTcpCandidateType`] and
    /// used in [RTCIceCandidate].
    ///
    /// [ICE]: https://datatracker.ietf.org/doc/html/rfc8445
    /// [RTCIceCandidate]: https://w3.org/TR/webrtc#dom-rtcicecandidate
    pub tcp_type: Option<RtcIceTcpCandidateType>,

    /// Type of network used by a local [ICE] candidate.
    ///
    /// **Not spec compliant**, but provided by most user agents.
    ///
    /// [ICE]: https://datatracker.ietf.org/doc/html/rfc8445
    pub network_type: Option<String>,
}

/// Non-exhaustive version of a [`KnownIceServerTransportProtocol`].
pub type IceServerTransportProtocol =
    NonExhaustive<KnownIceServerTransportProtocol>;

/// Possible types of the transport protocol used between the client and the
/// server, as defined in [RFC8656 Section 3.1][1].
///
/// [1]: https://rfc-editor.org/rfc/rfc8656#section-3.1
#[derive(
    Clone, Copy, Debug, Deserialize, Display, Eq, Hash, PartialEq, Serialize,
)]
#[serde(rename_all = "lowercase")]
pub enum KnownIceServerTransportProtocol {
    /// UDP as transport to the server.
    #[display("udp")]
    Udp,

    /// TCP as transport to the server.
    #[display("tcp")]
    Tcp,

    /// TLS as transport to the server.
    #[display("tls")]
    Tls,
}

/// Non-exhaustive version of a [`KnownRtcIceTcpCandidateType`].
pub type RtcIceTcpCandidateType = NonExhaustive<KnownRtcIceTcpCandidateType>;

/// Possible types of an [ICE] TCP candidate, as defined in [RFC6544].
///
/// [ICE]: https://datatracker.ietf.org/doc/html/rfc8445
/// [RFC6544]: https://rfc-editor.org/rfc/rfc6544
#[derive(
    Clone, Copy, Debug, Deserialize, Display, Eq, Hash, PartialEq, Serialize,
)]
#[serde(rename_all = "kebab-case")]
pub enum KnownRtcIceTcpCandidateType {
    /// Candidate for which the transport will attempt to open an outbound
    /// connection but will not receive incoming connection requests.
    #[display("active")]
    Active,

    /// Candidate for which the transport will receive incoming connection
    /// attempts, but not attempt a connection.
    #[display("passive")]
    Passive,

    /// Candidate for which the transport will attempt to open a connection
    /// simultaneously with its peer.
    #[display("so")]
    So,
}

/// Information about a certificate used by an [RTCIceTransport].
///
/// [Full doc on W3C][spec].
///
/// [RTCIceTransport]: https://w3.org/TR/webrtc#dom-rtcicetransport
/// [spec]: https://w3.org/TR/webrtc-stats#dom-rtccertificatestats
#[expect(clippy::module_name_repetitions, reason = "spec compliance")]
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RtcCertificateStats {
    /// Fingerprint of the certificate.
    ///
    /// Only use the fingerprint value as defined in
    /// [Section 5 of RFC4572][1].
    ///
    /// [1]: https://tools.ietf.org/html/rfc4572#section-5
    pub fingerprint: String,

    /// Hash function used to compute the certificate fingerprint.
    ///
    /// For instance, `sha-256`.
    pub fingerprint_algorithm: String,

    /// The DER-encoded [Base64] representation of the certificate.
    ///
    /// [Base64]: https://en.wikipedia.org/wiki/Base64
    /// [DER]: https://en.wikipedia.org/wiki/X.690#DER_encoding
    pub base64_certificate: String,

    /// Identifier referring to the stats object that contains the next
    /// certificate in the certificate chain.
    ///
    /// If the current certificate is at the end of the chain (i.e. a
    /// self-signed certificate), this will not be set.
    pub issuer_certificate_id: Option<String>,
}

/// Non-exhaustive version of a [`KnownRtcIceRole`].
pub type RtcIceRole = NonExhaustive<KnownRtcIceRole>;

/// Variants of [ICE roles][1].
///
/// More info in the [RFC5245].
///
/// [RFC5245]: https://tools.ietf.org/html/rfc5245
/// [1]: https://w3.org/TR/webrtc#dom-icetransport-role
#[derive(
    Clone, Copy, Debug, Deserialize, Display, Eq, Hash, PartialEq, Serialize,
)]
#[serde(rename_all = "camelCase")]
pub enum KnownRtcIceRole {
    /// Agent whose role as defined by [Section 3 in RFC 5245][1], has not yet
    /// been determined.
    ///
    /// [1]: https://tools.ietf.org/html/rfc5245#section-3
    #[display("unknown")]
    Unknown,

    /// Controlling agent as defined by [Section 3 in RFC 5245][1].
    ///
    /// [1]: https://tools.ietf.org/html/rfc5245#section-3
    #[display("controlling")]
    Controlling,

    /// Controlled agent as defined by [Section 3 in RFC 5245][1].
    ///
    /// [1]: https://tools.ietf.org/html/rfc5245#section-3
    #[display("controlled")]
    Controlled,
}

/// Non-exhaustive version of a [`KnownRtcDtlsTransportState`].
pub type RtcDtlsTransportState = NonExhaustive<KnownRtcDtlsTransportState>;

/// Possible states of a [DTLS] transport.
///
/// [DTLS]: https://webrtcglossary.com/dtls
#[derive(
    Clone, Copy, Debug, Deserialize, Display, Eq, Hash, PartialEq, Serialize,
)]
#[serde(rename_all = "camelCase")]
pub enum KnownRtcDtlsTransportState {
    /// [DTLS] has not started negotiating yet.
    ///
    /// [DTLS]: https://webrtcglossary.com/dtls
    #[display("new")]
    New,

    /// [DTLS] is in the process of negotiating a secure connection and
    /// verifying the remote fingerprint.
    ///
    /// [DTLS]: https://webrtcglossary.com/dtls
    #[display("connecting")]
    Connecting,

    /// [DTLS] has completed negotiation of a secure connection and verified the
    /// remote fingerprint.
    ///
    /// [DTLS]: https://webrtcglossary.com/dtls
    #[display("connected")]
    Connected,

    /// [DTLS] transport has been closed intentionally as the result of receipt
    /// of a `close_notify` alert, or calling [close()].
    ///
    /// [close()]: https://w3.org/TR/webrtc#dom-rtcpeerconnection-close
    /// [DTLS]: https://webrtcglossary.com/dtls
    #[display("closed")]
    Closed,

    /// [DTLS] transport has failed as the result of an error (such as receipt
    /// of an error alert or failure to validate the remote fingerprint).
    ///
    /// [DTLS]: https://webrtcglossary.com/dtls
    #[display("failed")]
    Failed,
}

/// Non-exhaustive version of a [`KnownRtcIceTransportState`].
pub type RtcIceTransportState = NonExhaustive<KnownRtcIceTransportState>;

/// Possible states of the underlying [ICE] transport used by a
/// [RTCPeerConnection].
///
/// [ICE]: https://datatracker.ietf.org/doc/html/rfc8445
/// [RTCPeerConnection]: https://w3.org/TR/webrtc#dom-rtcpeerconnection
#[derive(
    Clone, Copy, Debug, Deserialize, Display, Eq, Hash, PartialEq, Serialize,
)]
#[serde(rename_all = "camelCase")]
pub enum KnownRtcIceTransportState {
    /// [RTCIceTransport] has shut down and is no longer responding to [STUN]
    /// requests.
    ///
    /// [RTCIceTransport]: https://w3.org/TR/webrtc#dom-rtcicetransport
    /// [STUN]: https://webrtcglossary.com/stun
    #[display("closed")]
    Closed,

    /// [RTCIceTransport] has finished gathering, received an indication that
    /// there are no more remote candidates, finished checking all candidate
    /// pairs, and all pairs have either failed connectivity checks or lost
    /// consent, and either zero local candidates were gathered or the PAC timer
    /// has expired (see [RFC8863]).
    ///
    /// This is a terminal state until [ICE] is restarted. Since an [ICE]
    /// restart may cause connectivity to resume, entering the [`Failed`] state
    /// doesn't cause [DTLS] transports, [SCTP] associations or the data
    /// channels that run over them to close, or tracks to mute.
    ///
    /// [`Failed`]: KnownRtcIceTransportState::Failed
    /// [DTLS]: https://webrtcglossary.com/dtls
    /// [ICE]: https://datatracker.ietf.org/doc/html/rfc8445
    /// [RTCIceTransport]: https://w3.org/TR/webrtc#dom-rtcicetransport
    /// [RFC8863]: https://rfc-editor.org/rfc/rfc8863
    /// [SCTP]: https://webrtcglossary.com/sctp
    #[display("failed")]
    Failed,

    /// [ICE Agent] has determined that connectivity is currently lost for thw
    /// [RTCIceTransport].
    ///
    /// This is a transient state that may trigger intermittently (and resolve
    /// itself without action) on a flaky network. The way this state is
    /// determined is implementation dependent. Examples include:
    /// - Losing the network interface for the connection in use.
    /// - Repeatedly failing to receive a response to STUN requests.
    ///
    /// Alternatively, the [RTCIceTransport] has finished checking all existing
    /// candidates pairs and not found a connection (or consent checks [RFC7675]
    /// once successful, have now failed), but it is still gathering and/or
    /// waiting for additional remote candidates.
    ///
    /// [ICE Agent]: https://w3.org/TR/webrtc#dfn-ice-agent
    /// [RTCIceTransport]: https://w3.org/TR/webrtc#dom-rtcicetransport
    /// [RFC7675]: https://rfc-editor.org/rfc/rfc7675
    /// [STUN]: https://webrtcglossary.com/stun
    #[display("disconnected")]
    Disconnected,

    /// [RTCIceTransport] is gathering candidates and/or waiting for remote
    /// candidates to be supplied, and has not yet started checking.
    ///
    /// [RTCIceTransport]: https://w3.org/TR/webrtc#dom-rtcicetransport
    #[display("new")]
    New,

    /// [RTCIceTransport] has received at least one remote candidate (by means
    /// of [addIceCandidate()][0] or discovered as a peer-reflexive
    /// candidate when receiving a [STUN] binding request) and is checking
    /// candidate pairs and has either not yet found a connection or consent
    /// checks [RFC7675] have failed on all previously successful candidate
    /// pairs.
    ///
    /// In addition to checking, it may also still be gathering.
    ///
    /// [RTCIceTransport]: https://w3.org/TR/webrtc#dom-rtcicetransport
    /// [RFC7675]: https://rfc-editor.org/rfc/rfc7675
    /// [STUN]: https://webrtcglossary.com/stun
    /// [0]: https://w3.org/TR/webrtc#dom-peerconnection-addicecandidate
    #[display("checking")]
    Checking,

    /// [RTCIceTransport] has finished gathering, received an indication
    /// that there are no more remote candidates, finished checking all
    /// candidate pairs and found a connection.
    ///
    /// If consent checks [RFC7675] subsequently fail on all successful
    /// candidate pairs, the state transitions to [`Failed`].
    ///
    /// [`Failed`]: KnownRtcIceTransportState::Failed
    /// [RTCIceTransport]: https://w3.org/TR/webrtc#dom-rtcicetransport
    /// [RFC7675]: https://rfc-editor.org/rfc/rfc7675
    #[display("completed")]
    Completed,

    /// [RTCIceTransport] has found a usable connection, but is still checking
    /// other candidate pairs to see if there is a better connection.
    ///
    /// It may also still be gathering and/or waiting for additional remote
    /// candidates. If consent checks [RFC7675] fail on the connection in use,
    /// and there are no other successful candidate pairs available, then the
    /// state transitions to [`Checking`] (if there are candidate pairs
    /// remaining to be checked) or [`Disconnected`] (if there are no candidate
    /// pairs to check, but the peer is still gathering and/or waiting for
    /// additional remote candidates).
    ///
    /// [`Checking`]: KnownRtcIceTransportState::Checking
    /// [`Disconnected`]: KnownRtcIceTransportState::Disconnected
    /// [RTCIceTransport]: https://w3.org/TR/webrtc#dom-rtcicetransport
    /// [RFC7675]: https://rfc-editor.org/rfc/rfc7675
    #[display("connected")]
    Connected,
}

/// Non-exhaustive version of a [`KnownRtcDtlsRole`].
pub type RtcDtlsRole = NonExhaustive<KnownRtcDtlsRole>;

/// Possible roles in the DTLS handshake for transport.
///
/// [DTLS]: https://webrtcglossary.com/dtls
#[derive(
    Clone, Copy, Debug, Deserialize, Display, Eq, Hash, PartialEq, Serialize,
)]
#[serde(rename_all = "camelCase")]
pub enum KnownRtcDtlsRole {
    /// [RTCPeerConnection] is acting as a [DTLS] client as defined in
    /// [RFC6347].
    ///
    /// [DTLS]: https://webrtcglossary.com/dtls
    /// [RTCPeerConnection]: https://w3.org/TR/webrtc#dom-rtcpeerconnection
    /// [RFC6347]: https://rfc-editor.org/rfc/rfc6347
    #[display("client")]
    Client,

    /// [RTCPeerConnection] is acting as a [DTLS] server as defined in
    /// [RFC6347].
    ///
    /// [DTLS]: https://webrtcglossary.com/dtls
    /// [RTCPeerConnection]: https://w3.org/TR/webrtc#dom-rtcpeerconnection
    /// [RFC6347]: https://rfc-editor.org/rfc/rfc6347
    #[display("server")]
    Server,

    /// [DTLS] role of the [RTCPeerConnection] hasn't been determined yet.
    ///
    /// [DTLS]: https://webrtcglossary.com/dtls
    /// [RTCPeerConnection]: https://w3.org/TR/webrtc#dom-rtcpeerconnection
    #[display("unknown")]
    Unknown,
}

/// Non-exhaustive version of a [`KnownRtcStatsIceCandidatePairState`].
pub type RtcStatsIceCandidatePairState =
    NonExhaustive<KnownRtcStatsIceCandidatePairState>;

/// Possible states of a candidate pair.
#[derive(
    Clone, Copy, Debug, Deserialize, Display, Eq, Hash, PartialEq, Serialize,
)]
#[serde(rename_all = "kebab-case")]
pub enum KnownRtcStatsIceCandidatePairState {
    /// Check for this pair hasn't been performed, and it can't yet be performed
    /// until some other check succeeds, allowing this pair to unfreeze and move
    /// into the [`Waiting`] state.
    ///
    /// [`Waiting`]: KnownRtcStatsIceCandidatePairState::Waiting
    #[display("frozen")]
    Frozen,

    /// Check has not been performed for this pair, and can be performed as soon
    /// as it's the highest-priority waiting pair on the check list.
    #[display("waiting")]
    Waiting,

    /// Check has been sent for this pair, but the transaction is in progress.
    #[display("in-progress")]
    InProgress,

    /// Check for this pair was already done and failed, either never producing
    /// any response or producing an unrecoverable failure response.
    #[display("failed")]
    Failed,

    /// Check for this pair was already done and produced a successful result.
    #[display("succeeded")]
    Succeeded,

    /// Other candidate pair was nominated.
    ///
    /// This state is **obsolete and not spec compliant**, however, it still
    /// may be emitted by some implementations.
    #[display("cancelled")]
    Cancelled,
}

/// Non-exhaustive version of a [`KnownRtcIceCandidateType`].
pub type RtcIceCandidateType = NonExhaustive<KnownRtcIceCandidateType>;

/// [RTCIceCandidateType] represents the type of the ICE candidate, as defined
/// in [Section 15.1 of RFC 5245][1].
///
/// [RTCIceCandidateType]: https://w3.org/TR/webrtc#rtcicecandidatetype-enum
/// [1]: https://tools.ietf.org/html/rfc5245#section-15.1
#[derive(
    Clone, Copy, Debug, Deserialize, Display, Eq, Hash, PartialEq, Serialize,
)]
#[serde(rename_all = "lowercase")]
pub enum KnownRtcIceCandidateType {
    /// Host candidate, as defined in [Section 4.1.1.1 of RFC 5245][1].
    ///
    /// [1]: https://tools.ietf.org/html/rfc5245#section-4.1.1.1
    #[display("host")]
    Host,

    /// Server reflexive candidate, as defined in
    /// [Section 4.1.1.2 of RFC 5245][1].
    ///
    /// [1]: https://tools.ietf.org/html/rfc5245#section-4.1.1.2
    #[display("srflx")]
    Srflx,

    /// Peer reflexive candidate, as defined in
    /// [Section 4.1.1.2 of RFC 5245][1].
    ///
    /// [1]: https://tools.ietf.org/html/rfc5245#section-4.1.1.2
    #[display("prflx")]
    Prflx,

    /// Relay candidate, as defined in [Section 7.1.3.2.1 of RFC 5245][1].
    ///
    /// [1]: https://tools.ietf.org/html/rfc5245#section-7.1.3.2.1
    #[display("relay")]
    Relay,
}

/// [`RtcStat`] fields of [`RtcStatsType::InboundRtp`] type based on its `kind`.
///
/// [Full doc on W3C][spec].
///
/// [spec]: https://w3.org/TR/webrtc-stats#dom-rtcinboundrtpstreamstats
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Deserialize, Hash, PartialEq, Serialize)]
#[serde(tag = "mediaType", rename_all = "camelCase")]
pub enum InboundRtpMediaType {
    /// Fields when the `kind` is `audio`.
    ///
    /// [Full doc on W3C][spec].
    ///
    /// [spec]: https://w3.org/TR/webrtc-stats#dom-rtcinboundrtpstreamstats
    #[serde(rename_all = "camelCase")]
    Audio {
        /// Total number of samples that have been received on the [RTP stream].
        ///
        /// This includes [`InboundRtpMediaType::Audio::concealed_samples`].
        ///
        /// [RTP stream]: https://w3.org/TR/webrtc-stats#dfn-rtp-stream
        total_samples_received: Option<u64>,

        /// Total number of samples that are concealed samples.
        ///
        /// A concealed sample is a sample that was replaced with synthesized
        /// samples generated locally before being played out. Examples of
        /// samples that have to be concealed are samples from lost packets
        /// (reported in [`RtcReceivedRtpStreamStats::packets_lost`]) or samples
        /// from packets that arrive too late to be played out (reported in
        /// [`RtcInboundRtpStreamStats::packets_discarded`]).
        concealed_samples: Option<u64>,

        /// Total number of concealed samples inserted that are "silent".
        ///
        /// Playing out silent samples results in silence or comfort noise.
        ///
        /// This is a subset of
        /// [`InboundRtpMediaType::Audio::concealed_samples`].
        silent_concealed_samples: Option<u64>,

        /// Number of concealment events.
        ///
        /// This counter increases every time a concealed sample is synthesized
        /// after a non-concealed sample. That is, multiple consecutive
        /// concealed samples will increase the
        /// [`InboundRtpMediaType::Audio::concealed_samples`] count multiple
        /// times, but is a single concealment event.
        concealment_events: Option<u64>,

        /// Number of inserted deceleration samples.
        ///
        /// When playout is slowed down, this counter is increased by the
        /// difference between the number of samples received and the number of
        /// samples played out. If playout is slowed down by inserting samples,
        /// this will be the number of inserted samples.
        inserted_samples_for_deceleration: Option<u64>,

        /// Number of removed acceleration samples.
        ///
        /// When playout is sped up, this counter is increased by the difference
        /// between the number of samples received and the number of samples
        /// played out. If speedup is achieved by removing samples, this will be
        /// the count of samples removed.
        removed_samples_for_acceleration: Option<u64>,

        /// Audio level of the receiving track.
        ///
        /// For audio levels of tracks attached locally, see the
        /// [`MediaSourceKind::Audio`] instead.
        ///
        /// The value is between `0..1` (linear), where `1.0` represents
        /// `0 dBov`, `0` represents silence, and `0.5` represents approximately
        /// `6 dBSPL` change in the sound pressure level from `0 dBov`.
        ///
        /// The audio level is averaged over some small interval, using the
        /// algorithm described under [totalAudioEnergy][1]. The interval used
        /// is implementation-defined.
        ///
        /// [1]: https://tinyurl.com/webrtc-stats-totalaudioenergy
        audio_level: Option<Double>,

        /// Audio energy of the receiving track.
        ///
        /// For audio energy of tracks attached locally, see the
        /// [`MediaSourceKind::Audio`] instead.
        total_audio_energy: Option<Double>,

        /// Audio duration of the receiving track.
        ///
        /// For audio durations of tracks attached locally, see the
        /// [`MediaSourceKind::Audio`] instead.
        total_samples_duration: Option<Double>,

        /// Indicator whether audio playout is happening.
        ///
        /// This is used to look up the corresponding [`RtcAudioPlayoutStats`].
        playout_id: Option<String>,
    },

    /// Fields when the `kind` is `video`.
    ///
    /// [Full doc on W3C][spec].
    ///
    /// [spec]: https://w3.org/TR/webrtc-stats#dom-rtcinboundrtpstreamstats
    #[serde(rename_all = "camelCase")]
    Video {
        /// Total number of frames correctly decoded for the [RTP stream], i.e.
        /// frames that would be displayed if no frames are dropped.
        ///
        /// [RTP stream]: https://w3.org/TR/webrtc-stats#dfn-rtp-stream
        frames_decoded: Option<u32>,

        /// Total number of key frames, such as key frames in VP8 [RFC6386] or
        /// IDR-frames in H.264 [RFC6184], successfully decoded for the media
        /// [RTP stream].
        ///
        /// This is a subset of [`InboundRtpMediaType::Video::frames_decoded`].
        /// [`InboundRtpMediaType::Video::frames_decoded`] -
        /// [`InboundRtpMediaType::Video::key_frames_decoded`] gives the number
        /// of delta frames decoded.
        ///
        /// [RFC6386]: https://w3.org/TR/webrtc-stats#bib-rfc6386
        /// [RFC6184]: https://w3.org/TR/webrtc-stats#bib-rfc6184
        /// [RTP stream]: https://w3.org/TR/webrtc-stats#dfn-rtp-stream
        key_frames_decoded: Option<u32>,

        /// Total number of frames that have been rendered.
        ///
        /// It's incremented just after a frame has been rendered.
        frames_rendered: Option<u32>,

        /// Total number of frames dropped prior to decode or dropped because
        /// the frame missed its display deadline for the receiver's track.
        ///
        /// The measurement begins when the receiver is created and is a
        /// cumulative metric as defined in Appendix A (g) of [RFC7004].
        ///
        /// [RFC7004]: https://rfc-editor.org/rfc/rfc7004
        frames_dropped: Option<u32>,

        /// Width of the last decoded frame.
        ///
        /// Before the first frame is decoded this attribute is missing.
        frame_width: Option<u32>,

        /// Height of the last decoded frame.
        ///
        /// Before the first frame is decoded this attribute is missing.
        frame_height: Option<u32>,

        /// Number of decoded frames in the last second.
        frames_per_second: Option<Double>,

        /// Sum of the QP values of frames decoded by the receiver.
        ///
        /// The count of frames is in
        /// [`InboundRtpMediaType::Video::frames_decoded`].
        ///
        /// The definition of QP value depends on the codec; for VP8, the QP
        /// value is the value carried in the frame header as the syntax element
        /// `y_ac_qi`, and defined in [RFC6386] section 19.2. Its range is
        /// `0..127`.
        ///
        /// Note, that the QP value is only an indication of quantizer values
        /// used; many formats have ways to vary the quantizer value within the
        /// frame.
        ///
        /// [RFC6386]: https://rfc-editor.org/rfc/rfc6386
        qp_sum: Option<u64>,

        /// Total number of seconds that have been spent decoding the
        /// [`InboundRtpMediaType::Video::frames_decoded`] frames of
        /// the [RTP stream].
        ///
        /// The average decode time can be calculated by dividing this value
        /// with the [`InboundRtpMediaType::Video::frames_decoded`]. The time
        /// it takes to decode one frame is the time passed between feeding the
        /// decoder a frame and the decoder returning decoded data for that
        /// frame.
        ///
        /// [RTP stream]: https://w3.org/TR/webrtc-stats#dfn-rtp-stream
        total_decode_time: Option<Double>,

        /// Sum of the interframe delays in seconds between consecutively
        /// rendered frames, recorded just after a frame has been rendered.
        ///
        /// The interframe delay variance be calculated from
        /// [`InboundRtpMediaType::Video::total_inter_frame_delay`],
        /// [`InboundRtpMediaType::Video::total_squared_inter_frame_delay`],
        /// and [`InboundRtpMediaType::Video::frames_rendered`] according to the
        /// formula:
        /// `(total_squared_inter_frame_delay - total_inter_frame_delay^2 /
        /// frames_rendered) / frames_rendered`.
        total_inter_frame_delay: Option<Double>,

        /// Sum of the squared interframe delays in seconds between
        /// consecutively rendered frames, recorded just after a frame has been
        /// rendered.
        ///
        /// See the [`InboundRtpMediaType::Video::total_inter_frame_delay`] for
        /// details on how to calculate the interframe delay variance.
        total_squared_inter_frame_delay: Option<Double>,

        /// Total number of video pauses experienced by the receiver.
        ///
        /// Video is considered to be paused if time passed since last rendered
        /// frame exceeds 5 seconds. It's incremented when a frame is rendered
        /// after such a pause.
        pause_count: Option<u32>,

        /// Total duration of pauses, in seconds.
        ///
        /// For definition of pause see the
        /// [`InboundRtpMediaType::Video::pause_count`].
        ///
        /// This value is updated when a frame is rendered.
        total_pauses_duration: Option<Double>,

        /// Total number of video freezes experienced by the receiver.
        ///
        /// It's a freeze if frame duration, which is time interval between two
        /// consecutively rendered frames, is equal or exceeds
        /// `Max(3 * avg_frame_duration_ms, avg_frame_duration_ms + 150)`,
        /// where `avg_frame_duration_ms` is linear average of durations of last
        /// 30 rendered frames.
        freeze_count: Option<u32>,

        /// Total duration of rendered frames which are considered as frozen, in
        /// seconds.
        ///
        /// For definition of freeze see the
        /// [`InboundRtpMediaType::Video::freeze_count`].
        ///
        /// This value is updated when a frame is rendered.
        total_freezes_duration: Option<Double>,

        /// Total number of Full Intra Request (FIR) packets, as defined in
        /// [RFC5104] section 4.3.1, sent by the receiver.
        ///
        /// Doesn't count the RTCP FIR indicated in [RFC2032] which was
        /// deprecated by [RFC4587].
        ///
        /// [RFC5104]: https://rfc-editor.org/rfc/rfc5104
        /// [RFC2032]: https://rfc-editor.org/rfc/rfc2032
        /// [RFC4587]: https://rfc-editor.org/rfc/rfc4587
        fir_count: Option<u32>,

        /// Total number of Picture Loss Indication (PLI) packets, as defined in
        /// [RFC4585] section 6.3.1, sent by the receiver.
        ///
        /// [RFC4585]: https://rfc-editor.org/rfc/rfc4585
        pli_count: Option<u32>,

        /// Total number of complete frames received on the [RTP stream].
        ///
        /// This metric is incremented when the complete frame is received.
        ///
        /// [RTP stream]: https://w3.org/TR/webrtc-stats#dfn-rtp-stream
        frames_received: Option<u32>,

        /// Identification of the used the decoder implementation.
        ///
        /// This is useful for diagnosing interoperability issues.
        decoder_implementation: Option<String>,

        /// Indicator whether the decoder currently used is considered power
        /// efficient by the user agent.
        ///
        /// This SHOULD reflect if the configuration results in hardware
        /// acceleration, but the user agent MAY take other information into
        /// account when deciding if the configuration is considered power
        /// efficient.
        power_efficient_decoder: Option<bool>,

        /// Total number of frames correctly decoded for the [RTP stream] that
        /// consist of more than one RTP packet.
        ///
        /// For such frames the [`total_assembly_time`][1] is incremented. The
        /// average frame assembly time can be calculated by dividing the
        /// [`total_assembly_time`][1] with this value.
        ///
        /// [RTP stream]: https://w3.org/TR/webrtc-stats#dfn-rtp-stream
        /// [1]: InboundRtpMediaType::Video::total_assembly_time
        frames_assembled_from_multiple_packets: Option<u32>,

        /// Sum of the time, in seconds, each video frame takes from the time
        /// the first RTP packet is received (reception timestamp) and to the
        /// time the last RTP packet of a frame is received.
        ///
        /// Only incremented for frames consisting of more than one RTP packet.
        ///
        /// Given the complexities involved, the time of arrival or the
        /// reception timestamp is measured as close to the network layer as
        /// possible. This metric is not incremented for frames that are not
        /// decoded, i.e., [`InboundRtpMediaType::Video::frames_dropped`] or
        /// frames that fail decoding for other reasons (if any).
        total_assembly_time: Option<Double>,

        /// Cumulative sum of all corruption probability measurements that have
        /// been made for this SSRC.
        ///
        /// See the [`InboundRtpMediaType::Video::corruption_measurements`]
        /// regarding when this attribute SHOULD be present.
        ///
        /// Each measurement added to
        /// [`InboundRtpMediaType::Video::total_corruption_probability`] MUST be
        /// in the range `[0.0, 1.0]`, where a value of `0.0` indicates the
        /// system has estimated there is no or negligible corruption present in
        /// the processed frame. Similarly, a value of `1.0` indicates there is
        /// almost certainly a corruption visible in the processed frame. A
        /// value in between those two, indicates there is likely some
        /// corruption visible, but it could for instance have a low magnitude
        /// or be present only in a small portion of the frame.
        total_corruption_probability: Option<Double>,

        /// Cumulative sum of all corruption probability measurements squared
        /// that have been made for this SSRC.
        ///
        /// See the [`InboundRtpMediaType::Video::corruption_measurements`]
        /// regarding when this attribute SHOULD be present.
        total_squared_corruption_probability: Option<Double>,

        /// Number of corruption probability measurements.
        ///
        /// When the user agent is able to make a corruption probability
        /// measurement, this counter is incremented for each such measurement
        /// and the [`total_corruption_probability`][2] and the
        /// [`total_squared_corruption_probability`][1] are aggregated with this
        /// measurement and measurement squared respectively. If the
        /// [corruption-detection][0] header extension is present in the RTP
        /// packets, corruption probability measurements MUST be present.
        ///
        /// [0]: https://tinyurl.com/goog-corruption-detection
        /// [1]:InboundRtpMediaType::Video::total_squared_corruption_probability
        /// [2]: InboundRtpMediaType::Video::total_corruption_probability
        corruption_measurements: Option<u64>,
    },
}

/// [`RtcStat`] fields of [`RtcStatsType::OutboundRtp`] type based on its
/// `kind`.
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Deserialize, Hash, PartialEq, Serialize)]
#[serde(tag = "mediaType", rename_all = "camelCase")]
pub enum OutboundRtpMediaType {
    /// Fields when the `kind` is `audio`.
    #[serde(rename_all = "camelCase")]
    Audio {
        /// Total number of samples that have been sent over the [RTP stream].
        ///
        /// [RTP stream]: https://w3.org/TR/webrtc-stats#dfn-rtp-stream
        total_samples_sent: Option<u64>,

        /// Indicator whether the last [RTP] packet sent contained voice
        /// activity or not, based on the presence of the `V` bit in the
        /// extension header.
        ///
        /// [RTP]: https://webrtcglossary.com/rtp
        voice_activity_flag: Option<bool>,
    },

    /// Fields when the `kind` is `video`.
    ///
    /// [Full doc on W3C][spec].
    ///
    /// [spec]: https://w3.org/TR/webrtc-stats#dom-rtcoutboundrtpstreamstats
    #[serde(rename_all = "camelCase")]
    Video(Box<RtcOutboundRtpStreamVideo>),
}

/// Video-specific [`RtcOutboundRtpStreamStats`] part.
///
/// [Full doc on W3C][spec].
///
/// [spec]: https://w3.org/TR/webrtc-stats#dom-rtcoutboundrtpstreamstats
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Deserialize, Hash, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RtcOutboundRtpStreamVideo {
    /// Only exists if a [rid] has been set for the [RTP stream].
    ///
    /// If [rid] is set, this value will be present regardless if the
    /// [RID RTP header extension][1] has been negotiated.
    ///
    /// [rid]: https://w3.org/TR/webrtc#dom-rtcrtpcodingparameters-rid
    /// [RTP stream]: https://w3.org/TR/webrtc-stats#dfn-rtp-stream
    /// [1]: https://www.rfc-editor.org/rfc/rfc9429#section-5.2.1-13.11
    pub rid: Option<String>,

    /// Index of the encoding that represents the [RTP stream] in the RTP
    /// sender's list of [encodings][0].
    ///
    /// [0]: https://w3.org/TR/webrtc#dom-rtcrtpsendparameters-encodings
    pub encoding_index: Option<u32>,

    /// Value, increased by the target frame size in bytes every time a frame
    /// has been encoded.
    ///
    /// The actual frame size may be bigger or smaller than this number.
    ///
    /// This value goes up every time the
    /// [`RtcOutboundRtpStreamVideo::frames_encoded`] goes up.
    pub total_encoded_bytes_target: Option<u64>,

    /// Width of the last encoded frame.
    ///
    /// The resolution of the encoded frame may be lower than the media source
    /// (see [RTCVideoSourceStats.width][1]).
    ///
    /// Before the first frame is encoded this attribute is missing.
    ///
    /// [1]: https://w3.org/TR/webrtc-stats#dom-rtcvideosourcestats-width
    pub frame_width: Option<u32>,

    /// Height of the last encoded frame.
    ///
    /// The resolution of the encoded frame may be lower than the media source
    /// (see [RTCVideoSourceStats.height][1]).
    ///
    /// Before the first frame is encoded this attribute is missing.
    ///
    /// [1]: https://w3.org/TR/webrtc-stats#dom-rtcvideosourcestats-height
    pub frame_height: Option<u32>,

    /// Number of encoded frames during the last second.
    ///
    /// This may be lower than the media source frame rate (see
    /// [RTCVideoSourceStats.framesPerSecond][1]).
    ///
    /// [1]: https://tinyurl.com/rrmkrfk
    pub frames_per_second: Option<Double>,

    /// Total number of frames sent on the [RTP stream].
    ///
    /// [RTP stream]: https://w3.org/TR/webrtc-stats#dfn-rtp-stream
    pub frames_sent: Option<u32>,

    /// Total number of huge frames sent by the [RTP stream].
    ///
    /// Huge frames, by definition, are frames that have an encoded size at
    /// least 2.5 times the average size of the frames. The average size of the
    /// frames is defined as the target bitrate per second divided by the target
    /// FPS at the time the frame was encoded. These are usually complex to
    /// encode frames with a lot of changes in the picture. This can be used to
    /// estimate slide changes in the streamed presentation.
    ///
    /// The multiplier of 2.5 is chosen from analyzing encoded frame sizes for a
    /// sample presentation using [WebRTC] standalone implementation. 2.5 is a
    /// reasonably large multiplier which still caused all slide change events
    /// to be identified as a huge frames. It, however, produced 1.4% of false
    /// positive slide change detections which is deemed reasonable.
    ///
    /// [RTP stream]: https://w3.org/TR/webrtc-stats#dfn-rtp-stream
    /// [WebRTC]: https://w3.org/TR/webrtc
    pub huge_frames_sent: Option<u32>,

    /// Total number of frames successfully encoded for the media [RTP stream].
    ///
    /// [RTP stream]: https://w3.org/TR/webrtc-stats#dfn-rtp-stream
    pub frames_encoded: Option<u32>,

    /// Total number of key frames, such as key frames in VP8 [RFC6386] or
    /// IDR-frames in H.264 [RFC6184], successfully encoded for the media
    /// [RTP stream].
    ///
    /// This is a subset of
    /// [`RtcOutboundRtpStreamVideo::frames_encoded`].
    /// [`RtcOutboundRtpStreamVideo::frames_encoded`] -
    /// [`RtcOutboundRtpStreamVideo::key_frames_encoded`] gives the number of
    /// delta frames encoded.
    ///
    /// [RFC6386]: https://rfc-editor.org/rfc/rfc6386
    /// [RFC6184]: https://rfc-editor.org/rfc/rfc6184
    /// [RTP stream]: https://w3.org/TR/webrtc-stats#dfn-rtp-stream
    pub key_frames_encoded: Option<u32>,

    /// Sum of the QP values of frames encoded by the sender.
    ///
    /// The count of frames is in [`RtcOutboundRtpStreamVideo::frames_encoded`].
    ///
    /// The definition of QP value depends on the codec; for VP8, the QP value
    /// is the value carried in the frame header as the syntax element
    /// `y_ac_qi`, and defined in [RFC6386] section 19.2. Its range is `0..127`.
    ///
    /// Note, that the QP value is only an indication of quantizer values used;
    /// many formats have ways to vary the quantizer value within the frame.
    ///
    /// [RFC6386]: https://rfc-editor.org/rfc/rfc6386
    pub qp_sum: Option<u64>,

    /// Cumulative sum of the PSNR values of frames encoded by the sender.
    ///
    /// The record includes values for the `y`, `u` and `v` components.
    ///
    /// The count of measurements is in [`Self::psnr_measurements`].
    pub psnr_sum: Option<BTreeMap<String, Double>>,

    /// Number of times PSNR was measured.
    ///
    /// The components of [`Self::psnr_sum`] are aggregated with this
    /// measurement.
    pub psnr_measurements: Option<u64>,

    /// Total number of seconds that has been spent encoding the
    /// [`RtcOutboundRtpStreamVideo::frames_encoded`] frames of the
    /// [RTP stream].
    ///
    /// The average encode time can be calculated by dividing this value with
    /// [`RtcOutboundRtpStreamVideo::frames_encoded`]. The time it takes to
    /// encode one frame is the time passed between feeding the encoder a frame
    /// and the encoder returning encoded data for that frame. This doesn't
    /// include any additional time it may take to packetize the resulting data.
    ///
    /// [RTP stream]: https://w3.org/TR/webrtc-stats#dfn-rtp-stream
    pub total_encode_time: Option<Double>,

    /// Total number of Full Intra Request (FIR) packets, as defined in
    /// [RFC5104] section 4.3.1, received by the sender.
    ///
    /// Doesn't count the RTCP FIR indicated in [RFC2032] which was deprecated
    /// by [RFC4587].
    ///
    /// [RFC5104]: https://rfc-editor.org/rfc/rfc5104
    /// [RFC2032]: https://rfc-editor.org/rfc/rfc2032
    /// [RFC4587]: https://rfc-editor.org/rfc/rfc4587
    pub fir_count: Option<u32>,

    /// Total number of Picture Loss Indication (PLI) packets, as defined in
    /// [RFC4585] section 6.3.1, received by the sender.
    ///
    /// [RFC4585]: https://rfc-editor.org/rfc/rfc4585
    pub pli_count: Option<u32>,

    /// Identification of the used encoder implementation.
    ///
    /// This is useful for diagnosing interoperability issues.
    pub encoder_implementation: Option<String>,

    /// Indicator whether the encoder currently used is considered power
    /// efficient by the user agent.
    ///
    /// This SHOULD reflect if the configuration results in hardware
    /// acceleration, but the user agent MAY take other information into account
    /// when deciding if the configuration is considered power efficient.
    pub power_efficient_encoder: Option<bool>,

    /// Current reason for limiting the resolution and/or framerate.
    ///
    /// The implementation reports the most limiting factor. If the
    /// implementation is not able to determine the most limiting factor because
    /// multiple may exist, the reasons MUST be reported in the following order
    /// of priority: `bandwidth`, `cpu`, `other`.
    pub quality_limitation_reason: Option<RtcQualityLimitationReason>,

    /// Record of the total time, in seconds, that the [RTP stream] has spent in
    /// each quality limitation state.
    ///
    /// The record includes a mapping for all [`RtcQualityLimitationReason`]
    /// types, including [`KnownRtcQualityLimitationReason::None`].
    ///
    /// The sum of all entries minus [`KnownRtcQualityLimitationReason::None`]
    /// gives the total time that the stream has been limited.
    ///
    /// [RTP stream]: https://w3.org/TR/webrtc-stats#dfn-rtp-stream
    pub quality_limitation_durations:
        Option<BTreeMap<RtcQualityLimitationReason, Double>>,

    /// Number of times that the resolution has changed because of the quality
    /// limit (`quality_limitation_reason` has a value other than
    /// [`KnownRtcQualityLimitationReason::None`]).
    ///
    /// The counter is initially zero and increases when the resolution goes up
    /// or down. For example, if a `720p` track is sent as `480p` for some time
    /// and then recovers to `720p`, this will have the value `2`.
    pub quality_limitation_resolution_changes: Option<u32>,

    /// Currently configured [scalability mode][0] the [RTP stream], if any.
    ///
    /// [0]: https://w3c.github.io/webrtc-svc#scalabilitymodes*
    /// [RTP stream]: https://w3.org/TR/webrtc-stats#dfn-rtp-stream
    pub scalability_mode: Option<String>,
}

/// Non-exhaustive version of a [`KnownRtcQualityLimitationReason`].
pub type RtcQualityLimitationReason =
    NonExhaustive<KnownRtcQualityLimitationReason>;

/// Reason of why media quality in a stream is being reduced by a codec during
/// encoding.
#[derive(
    Clone,
    Copy,
    Debug,
    Deserialize,
    Display,
    Eq,
    Hash,
    Ord,
    PartialEq,
    PartialOrd,
    Serialize,
)]
#[serde(rename_all = "kebab-case")]
pub enum KnownRtcQualityLimitationReason {
    /// Resolution and/or framerate is not limited.
    #[display("none")]
    None,

    /// Resolution and/or framerate is primarily limited due to CPU load.
    #[display("cpu")]
    Cpu,

    /// Resolution and/or framerate is primarily limited due to congestion cues
    /// during bandwidth estimation.
    ///
    /// Typical, congestion control algorithms use inter-arrival time,
    /// round-trip time, packet or other congestion cues to perform bandwidth
    /// estimation.
    #[display("bandwidth")]
    Bandwidth,

    /// Resolution and/or framerate is primarily limited for a reason other than
    /// the above.
    #[display("other")]
    Other,
}

/// [`RtcStat`] fields of an [`RtcStatsType::MediaSource`], based on its `kind`.
#[serde_with::skip_serializing_none]
#[derive(Clone, Copy, Debug, Deserialize, Hash, PartialEq, Serialize)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum MediaSourceKind {
    /// Representation of a video track that is attached to one or more senders.
    ///
    /// It's [`RtcMediaSourceStats`] whose kind is `video`.
    ///
    /// [Full doc on W3C][spec].
    ///
    /// [spec]: https://w3.org/TR/webrtc-stats#dom-rtcvideosourcestats
    #[serde(rename_all = "camelCase")]
    Video {
        /// Width (in pixels) of the last frame originating from the source.
        ///
        /// Before a frame has been produced this attribute is missing.
        width: Option<u32>,

        /// Height (in pixels) of the last frame originating from the source.
        ///
        /// Before a frame has been produced this attribute is missing.
        height: Option<u32>,

        /// Total number of frames originating from the source.
        frames: Option<u32>,

        /// Number of frames originating from the source, measured during the
        /// last second.
        ///
        /// For the first second of this object's lifetime this attribute is
        /// missing.
        frames_per_second: Option<Double>,
    },

    /// Representation of an audio track that is attached to one or more
    /// senders.
    ///
    /// It's [`RtcMediaSourceStats`] whose kind is `audio`.
    ///
    /// [Full doc on W3C][spec].
    ///
    /// [spec]: https://w3.org/TR/webrtc-stats#dom-rtcaudiosourcestats
    #[serde(rename_all = "camelCase")]
    Audio {
        /// Audio level of the media source.
        ///
        /// For audio levels of remotely sourced tracks, see
        /// [`RtcInboundRtpStreamStats`] instead.
        ///
        /// The value is between `0..1` (linear), where `1.0` represents `0`
        /// dBov, `0` represents silence, and `0.5` represents approximately
        /// `6` dBSPL change in the sound pressure level from `0` dBov.
        ///
        /// The audio level is averaged over some small interval, using the
        /// algorithm described under
        /// [`MediaSourceKind::Audio::total_audio_energy`]. The interval used
        /// is implementation-defined.
        audio_level: Option<Double>,

        /// Audio energy of the media source.
        ///
        /// For audio energy of remotely sourced tracks, see
        /// [`RtcInboundRtpStreamStats`] instead.
        total_audio_energy: Option<Double>,

        /// Audio duration of the media source.
        ///
        /// For audio durations of remotely sourced tracks, see
        /// [`RtcInboundRtpStreamStats`] instead.
        ///
        /// Represents the total duration in seconds of all samples that have
        /// been produced by this source for the lifetime of this stats object.
        /// Can be used with [`MediaSourceKind::Audio::total_audio_energy`]
        /// to compute an average audio level over different intervals.
        total_samples_duration: Option<Double>,

        /// Only exists when the [MediaStreamTrack][0] is sourced from a
        /// microphone where echo cancellation is applied.
        ///
        /// Calculated in decibels, as defined in [ECHO] (2012) section 3.14.
        ///
        /// If multiple audio channels are used, the channel of the least audio
        /// energy is considered for any sample.
        ///
        /// [0]: https://w3.org/TR/mediacapture-streams#dom-mediastreamtrack
        /// [ECHO]: https://w3.org/TR/webrtc-stats#bib-echo
        echo_return_loss: Option<Double>,

        /// Only exists when the [MediaStreamTrack][0] is sourced from a
        /// microphone where echo cancellation is applied.
        ///
        /// Calculated in decibels, as defined in [ECHO] (2012) section 3.15.
        ///
        /// If multiple audio channels are used, the channel of the least audio
        /// energy is considered for any sample.
        ///
        /// [0]: https://w3.org/TR/mediacapture-streams#dom-mediastreamtrack
        /// [ECHO]: https://w3.org/TR/webrtc-stats#bib-echo
        echo_return_loss_enhancement: Option<Double>,
    },
}

/// Representation of [DOMHighResTimeStamp][1].
///
/// Can be converted to the [`SystemTime`] with millisecond-wise accuracy.
///
/// [`HighResTimeStamp`] type is a [`f64`] and is used to store a time value
/// in milliseconds. This type can be used to describe a discrete point in time
/// or a time interval (the difference in time between two discrete points in
/// time).
///
/// The time, given in milliseconds, should be accurate to 5 µs (microseconds),
/// with the fractional part of the number indicating fractions of a
/// millisecond. However, if the browser is unable to provide a time value
/// accurate to 5 µs (due, for example, to hardware or software constraints),
/// the browser can represent the value as a time in milliseconds accurate to a
/// millisecond. Also note the section below on reduced time precision
/// controlled by browser preferences to avoid timing attacks and
/// fingerprinting.
///
/// Further, if the device or operating system the user agent is running on
/// doesn't have a clock accurate to the microsecond level, they may only be
/// accurate to the millisecond.
///
/// [1]: https://developer.mozilla.org/docs/Web/API/DOMHighResTimeStamp
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
pub struct HighResTimeStamp(pub f64);

impl From<HighResTimeStamp> for SystemTime {
    fn from(timestamp: HighResTimeStamp) -> Self {
        Self::UNIX_EPOCH + Duration::from_secs_f64(timestamp.0 / 1000.0)
    }
}

impl TryFrom<SystemTime> for HighResTimeStamp {
    type Error = SystemTimeError;

    fn try_from(time: SystemTime) -> Result<Self, Self::Error> {
        Ok(Self(
            time.duration_since(SystemTime::UNIX_EPOCH)?.as_secs_f64() * 1000.0,
        ))
    }
}

/// Hashing string representation.
///
/// Some people believe that such behavior is incorrect (but in some programming
/// languages this is a default behavior) due to `NaN`, `Inf` or `-Inf` (they
/// all will have the same hashes).
/// But in the case of [`RtcStat`] received from the client, there should be no
/// such situations, and the hash will always be correct.
impl Hash for HighResTimeStamp {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.0.to_string().hash(state);
    }
}

/// Comparison string representations.
///
/// Such implementation is required, so that the results of comparing values and
/// comparing hashes match.
impl PartialEq for HighResTimeStamp {
    fn eq(&self, other: &Self) -> bool {
        self.0.to_string().eq(&other.0.to_string())
    }
}

/// Floating point numeric type that corresponds to the set of *finite*
/// double-precision 64-bit [IEEE 754] floating point numbers.
///
/// Web IDL [double] type.
///
/// [double]: https://webidl.spec.whatwg.org#idl-double
/// [IEEE 754]: https://ieeexplore.ieee.org/document/8766229
#[derive(Copy, Clone, Debug, Deserialize, Serialize)]
pub struct Double(pub f64);

/// Hashing string representation.
///
/// Some people believe that such behavior is incorrect (but in some programming
/// languages this is a default behavior) due to `NaN`, `Inf` or `-Inf` (they
/// all will have the same hashes).
/// But in the case of [`RtcStat`] received from the client, there should be no
/// such situations, and the hash will always be correct.
impl Hash for Double {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.0.to_string().hash(state);
    }
}

/// Comparison string representations.
///
/// Such implementation is required, so that the results of comparing values and
/// comparing hashes match.
impl PartialEq for Double {
    fn eq(&self, other: &Self) -> bool {
        self.0.to_string().eq(&other.0.to_string())
    }
}