rtci 0.3.0

A sans-I/O WebRTC implementation: peer connections with ICE, DTLS-SRTP, SCTP data channels, RTP/RTCP and JSEP negotiation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
//! Statistics accumulator module.
//!
//! This module provides incremental statistics accumulation for WebRTC
//! peer connections. The accumulators are updated as events occur in the
//! handler pipeline, and snapshots can be taken at any time to produce
//! immutable stats reports.

mod ccfb;
mod certificate;
mod codec;
mod data_channel;
mod ice_candidate;
mod ice_candidate_pair;
mod media;
mod peer_connection;
#[cfg(test)]
mod retire_test;
mod rtcp_reports;
#[cfg(test)]
mod rtcp_reports_test;
mod rtp_stream;
mod seal;
mod transport;
mod transports;

pub(crate) use ccfb::CcfbTally;
pub(crate) use certificate::{CertificateStatsAccumulator, base64_encode};
pub(crate) use codec::{CodecDirection, CodecStatsAccumulator};
pub(crate) use data_channel::DataChannelStatsAccumulator;
pub(crate) use ice_candidate::IceCandidateAccumulator;
pub(crate) use ice_candidate_pair::IceCandidatePairAccumulator;
pub use media::app_provided::*;
pub(crate) use media::audio_playout::AudioPlayoutStatsAccumulator;
pub(crate) use media::media_source::{MediaSourceStatsAccumulator, media_source_stats_id};
pub(crate) use peer_connection::PeerConnectionStatsAccumulator;
pub(crate) use rtp_stream::inbound::InboundRtpStreamAccumulator;
pub(crate) use rtp_stream::outbound::OutboundRtpStreamAccumulator;
pub(crate) use seal::Seal;
pub(crate) use transport::TransportStatsAccumulator;

use crate::data_channel::RTCDataChannelId;
use crate::rtp_transceiver::rtp_sender::{RTCRtpCodec, RtpCodecKind};
use crate::rtp_transceiver::{PayloadType, RTCRtpTransceiverId, SSRC};
use crate::statistics::StatsSelector;
use crate::statistics::report::{RTCStatsReport, RTCStatsReportEntry};
use ice::CandidatePairStats;
use sctp::StreamId;
use shared::time::SystemInstant;
use std::collections::{HashMap, HashSet};
use std::sync::OnceLock;
use std::time::Instant;

/// Master statistics accumulator for a peer connection.
///
/// This struct aggregates all category-specific accumulators and provides
/// a unified interface for updating stats and generating snapshots.
///
/// # Design
///
/// The accumulator follows the "incremental accumulation + snapshot" pattern:
/// - Handler code calls methods like `on_rtp_received()` as events occur
/// - The `snapshot()` method produces an immutable `RTCStatsReport`
/// - All timestamps are provided explicitly for deterministic testing
///
/// # Thread Safety
///
/// This struct is not thread-safe. It is designed to be owned by the
/// pipeline context and accessed only from the handler thread.
/// How many closed data channels keep their stats object (webrtc-stats lifetime, bounded).
pub(crate) const MAX_CLOSED_DATA_CHANNEL_STATS: usize = 64;

#[derive(Debug, Default)]
pub(crate) struct RTCStatsAccumulator {
    /// Peer connection level stats.
    pub(crate) peer_connection: PeerConnectionStatsAccumulator,

    /// The statistics of the active transport: the one the connection's handlers work on
    /// (one per peer connection while every section is bundled). The other transports' are in
    /// `transports`.
    pub(crate) transport: TransportStatsAccumulator,

    /// The transports that are not the active one, and which transport each m= section runs
    /// over (webrtc-stats 7.1: a `transport` object per transport).
    transports: transports::ParkedTransports,

    /// ICE candidate pairs keyed by pair ID.
    pub(crate) ice_candidate_pairs: HashMap<String, IceCandidatePairAccumulator>,

    /// Local ICE candidates keyed by candidate ID.
    pub(crate) local_candidates: HashMap<String, IceCandidateAccumulator>,

    /// Remote ICE candidates keyed by candidate ID.
    pub(crate) remote_candidates: HashMap<String, IceCandidateAccumulator>,

    /// Certificate stats keyed by fingerprint.
    pub(crate) certificates: HashMap<String, CertificateStatsAccumulator>,

    /// Codec stats keyed by codec ID.
    pub(crate) codecs: HashMap<String, CodecStatsAccumulator>,

    /// Data channel stats keyed by channel ID.
    pub(crate) data_channels: HashMap<RTCDataChannelId, DataChannelStatsAccumulator>,

    /// The closed channels whose stats objects are kept, oldest first (at most
    /// [`MAX_CLOSED_DATA_CHANNEL_STATS`]).
    pub(crate) closed_data_channels: std::collections::VecDeque<RTCDataChannelId>,

    /// Inbound RTP stream accumulators keyed by SSRC.
    pub(crate) inbound_rtp_streams: HashMap<SSRC, InboundRtpStreamAccumulator>,

    /// Outbound RTP stream accumulators keyed by SSRC.
    pub(crate) outbound_rtp_streams: HashMap<SSRC, OutboundRtpStreamAccumulator>,
    /// The outbound streams whose `target_bitrate` is a share the connection allocated them
    /// (`on_target_bitrate`), reported whatever the number of streams.
    pub(crate) allocated_ssrcs: std::collections::HashSet<SSRC>,
    /// Each transport's congestion controller's last estimate, by transport key: the
    /// `availableOutgoingBitrate` of the pair it has selected.
    pub(crate) outgoing_estimates: std::collections::BTreeMap<usize, f64>,

    /// Media source stats keyed by track ID.
    pub(crate) media_sources: HashMap<String, MediaSourceStatsAccumulator>,

    /// Audio playout stats keyed by playout ID.
    pub(crate) audio_playouts: HashMap<String, AudioPlayoutStatsAccumulator>,

    // Reverse lookup maps for O(1) RTX/FEC SSRC detection. Each holds at most one entry per
    // stream: an entry goes when its stream goes, or when the stream is given another RTX / FEC
    // SSRC.
    /// Maps an inbound RTX SSRC to its primary SSRC.
    inbound_rtx_ssrc_to_primary: HashMap<SSRC, SSRC>,

    /// Maps an outbound RTX SSRC to its primary SSRC. Kept apart from the inbound map: the
    /// remote's SSRCs and ours are chosen independently and may coincide.
    outbound_rtx_ssrc_to_primary: HashMap<SSRC, SSRC>,

    /// Maps an inbound FEC SSRC to its primary SSRC.
    fec_ssrc_to_primary: HashMap<SSRC, SSRC>,

    /// The application's socket layer carries ECN (`SettingEngineBuilder::with_ecn`): RTP
    /// streams report their ECN counts.
    pub(crate) ecn: bool,
    /// How a stream with ECN on starts marking (`SettingEngineBuilder::with_ecn_initiation`).
    pub(crate) ecn_initiation: interceptor::EcnInitiation,
    /// Which ECT codepoint marked packets carry (`SettingEngineBuilder::with_ecn_marking`).
    pub(crate) ecn_marking: interceptor::EcnMarking,
    /// The RTCP CNAMEs remote sources named, in order (at most 16), for an ECN validation
    /// that starts after them.
    remote_cnames: Vec<String>,
    /// How many sender and receiver reports (fewer than 31 report blocks, so that none may
    /// have left a stream out for the next one) arrived on each transport, by transport key:
    /// what the DSCP fallback (RFC 8835 section 4.2) counts against a flow never reported on.
    pub(crate) reception_report_packets: HashMap<usize, u64>,

    /// How many RTP stream objects have been deleted. A stream object created now carries it in
    /// its id, so that id differs from the id of every deleted object with the same SSRC
    /// (webrtc-stats 4.3: the id of a deleted object is never reused). One counter rather than
    /// a memory of the SSRCs that went: a peer can go through any number of those.
    streams_retired: u64,

    /// The salt the report's ids are hashed with, drawn once per peer connection (webrtc 8.4:
    /// an id must not be predictable by an application). `None` (an accumulator built outside
    /// a peer connection) leaves the ids as the accumulators name them.
    id_salt: Option<[u64; 2]>,

    /// The wall-clock anchor of the report timestamps, taken at the first report (see
    /// [`Seal`]). A `OnceLock` rather than a `OnceCell`: the accumulator stays `Sync`.
    anchor: OnceLock<SystemInstant>,
}

/// Asserts a stats record was stamped with `expected`, ignoring the wall-clock half.
///
/// A [`SystemInstant`] pairs a monotonic instant with a wall-clock reading taken beside it, and
/// `PartialEq` compares both. Rebuilding one in a test — `SystemInstant::now(now)` — reproduces
/// the monotonic half exactly but takes a *fresh* wall-clock reading, so the two are never equal:
/// they differ by however long the test took to get there, typically a few hundred microseconds.
///
/// The monotonic half is the part under test: it says the snapshot stamped the record with the
/// instant the caller supplied rather than one it went and read. Recover it via the round-trip
/// `instant(duration_since_unix_epoch())`, which cancels the anchor and returns the instant the
/// `SystemInstant` was built from.
#[cfg(test)]
pub(crate) fn assert_stamped_at(stamp: shared::time::SystemInstant, expected: Instant) {
    assert_eq!(
        stamp.instant(stamp.duration_since_unix_epoch()),
        expected,
        "stats must be stamped with the caller's instant"
    );
}

impl RTCStatsAccumulator {
    /// Creates a new empty stats accumulator.
    pub(crate) fn new() -> Self {
        Self::default()
    }

    /// An empty accumulator whose RTP streams report ECN counts when `ecn` is on
    /// (`SettingEngineBuilder::with_ecn`).
    pub(crate) fn with_ecn(ecn: bool) -> Self {
        Self {
            ecn,
            ..Self::default()
        }
    }

    /// The accumulator of a peer connection: [`with_ecn`](Self::with_ecn), and report ids
    /// hashed with `id_salt`, which the connection draws at random.
    pub(crate) fn for_connection(
        ecn: bool,
        ecn_initiation: interceptor::EcnInitiation,
        id_salt: [u64; 2],
    ) -> Self {
        Self {
            ecn,
            ecn_initiation,
            ecn_marking: interceptor::EcnMarking::default(),
            id_salt: Some(id_salt),
            ..Self::default()
        }
    }

    /// The ECT codepoint marked packets carry (`SettingEngineBuilder::with_ecn_marking`).
    pub(crate) fn with_ecn_marking(mut self, marking: interceptor::EcnMarking) -> Self {
        self.ecn_marking = marking;
        self
    }

    /// What seals a report taken at `now`: the connection's id salt and the timestamp anchor,
    /// which the first report sets.
    fn seal(&self, now: Instant) -> Seal {
        Seal::new(
            self.id_salt,
            *self.anchor.get_or_init(|| SystemInstant::now(now)),
        )
    }

    /// The report holding `entries`, with their ids and timestamps sealed.
    fn report(&self, now: Instant, mut entries: Vec<RTCStatsReportEntry>) -> RTCStatsReport {
        let seal = self.seal(now);
        for entry in &mut entries {
            seal.entry(entry);
        }
        RTCStatsReport::new(entries)
    }

    /// The id a report gives the object the accumulators name `name` (for a test that looks
    /// an object up by what it is).
    #[cfg(test)]
    pub(crate) fn report_id(&self, now: Instant, name: &str) -> String {
        self.seal(now).id_of(name)
    }

    /// The outbound-rtp object of `stream`.
    ///
    /// Its `targetBitrate` is the encoder's target for the stream. The application supplies
    /// it; without that, the congestion controller's estimate stands in for it while the
    /// connection sends one stream, which then has the whole estimate. With several streams
    /// the estimate is not any one stream's target, and the member is left out.
    fn outbound_snapshot(
        &self,
        now: Instant,
        stream: &OutboundRtpStreamAccumulator,
    ) -> crate::statistics::stats::rtp_stream::sent::outbound::RTCOutboundRtpStreamStats {
        let mut stats = stream.snapshot(now, &stream.stats_id());
        if stream.encoder_stats.target_bitrate.is_none()
            && self.outbound_rtp_streams.len() > 1
            && !self.allocated_ssrcs.contains(&stream.ssrc)
        {
            stats.target_bitrate = None;
        }
        stats
    }

    /// The remote-candidate entries.
    ///
    /// webrtc-stats `RTCIceCandidateStats.address`: a remote candidate's address is null
    /// unless the application supplied that address itself (`addIceCandidate`, or a candidate
    /// line of a remote description); then every remote candidate with that address shows it.
    /// A peer-reflexive candidate learned from a connectivity check is the case that matters:
    /// its address was never given to the application.
    fn remote_candidate_entries(&self, now: Instant) -> Vec<RTCStatsReportEntry> {
        let signalled: HashSet<&str> = self
            .remote_candidates
            .values()
            .filter(|candidate| candidate.signalled)
            .filter_map(|candidate| candidate.address.as_deref())
            .collect();
        self.remote_candidates
            .iter()
            .map(|(id, candidate)| {
                let mut stats = candidate.snapshot_remote(now, id);
                if !stats
                    .address
                    .as_deref()
                    .is_some_and(|address| signalled.contains(address))
                {
                    stats.address = None;
                }
                RTCStatsReportEntry::RemoteCandidate(stats)
            })
            .collect()
    }

    /// Creates a snapshot of all accumulated stats at the given timestamp.
    ///
    /// This method iterates through all accumulators and produces an
    /// immutable `RTCStatsReport` containing all current statistics.
    ///
    /// # Parameters
    ///
    /// * `now` - The timestamp to use for all stats in the report
    ///
    /// # Returns
    ///
    /// An `RTCStatsReport` containing snapshots of all accumulated stats.
    pub(crate) fn snapshot(&self, now: Instant) -> RTCStatsReport {
        let mut entries = Vec::new();

        // Peer connection stats
        entries.push(RTCStatsReportEntry::PeerConnection(
            self.peer_connection.snapshot(now),
        ));

        // Transport stats: one object per transport
        for transport in self.every_transport() {
            entries.push(RTCStatsReportEntry::Transport(transport.snapshot(now)));
        }

        // ICE candidate pair stats
        for (id, pair) in &self.ice_candidate_pairs {
            entries.push(RTCStatsReportEntry::IceCandidatePair(
                pair.snapshot(now, id),
            ));
        }

        // Local ICE candidate stats
        for (id, candidate) in &self.local_candidates {
            entries.push(RTCStatsReportEntry::LocalCandidate(
                candidate.snapshot_local(now, id),
            ));
        }

        // Remote ICE candidate stats
        entries.extend(self.remote_candidate_entries(now));

        // Certificate stats
        for (id, cert) in &self.certificates {
            entries.push(RTCStatsReportEntry::Certificate(cert.snapshot(now, id)));
        }

        // Codec stats
        for (id, codec) in &self.codecs {
            entries.push(RTCStatsReportEntry::Codec(codec.snapshot(now, id)));
        }

        // Data channel stats
        for (id, channel) in &self.data_channels {
            entries.push(RTCStatsReportEntry::DataChannel(
                channel.snapshot(now, format!("RTCDataChannel_{}", id)),
            ));
        }

        // Inbound RTP stream stats, each with its remote-outbound object once an RTCP SR has
        // created it (webrtc-stats 6.1)
        for stream in self.inbound_rtp_streams.values() {
            let id = stream.stats_id();
            entries.push(RTCStatsReportEntry::InboundRtp(stream.snapshot(now, &id)));
            if stream.has_remote() {
                entries.push(RTCStatsReportEntry::RemoteOutboundRtp(
                    stream.snapshot_remote(now),
                ));
            }
        }

        // Outbound RTP stream stats, each with its remote-inbound object once a reception
        // report has created it (webrtc-stats 6.1)
        for stream in self.outbound_rtp_streams.values() {
            entries.push(RTCStatsReportEntry::OutboundRtp(
                self.outbound_snapshot(now, stream),
            ));
            if stream.has_remote() {
                entries.push(RTCStatsReportEntry::RemoteInboundRtp(
                    stream.snapshot_remote(now),
                ));
            }
        }

        // Media source stats
        for (track_id, source) in &self.media_sources {
            if let Some(entry) = Self::media_source_entry(now, track_id, source) {
                entries.push(entry);
            }
        }

        // Audio playout stats
        for (id, playout) in &self.audio_playouts {
            entries.push(RTCStatsReportEntry::AudioPlayout(playout.snapshot(now, id)));
        }

        self.report(now, entries)
    }

    /// The report entry of the media source for the track `track_id`.
    fn media_source_entry(
        now: Instant,
        track_id: &str,
        source: &MediaSourceStatsAccumulator,
    ) -> Option<RTCStatsReportEntry> {
        let id = media_source_stats_id(track_id);
        match source.kind {
            RtpCodecKind::Audio => Some(RTCStatsReportEntry::AudioSource(
                source.snapshot_audio(now, &id),
            )),
            RtpCodecKind::Video => Some(RTCStatsReportEntry::VideoSource(
                source.snapshot_video(now, &id),
            )),
            _ => None,
        }
    }

    /// Creates a snapshot of stats based on the provided selector.
    ///
    /// This method implements the W3C stats selection algorithm:
    /// - If selector is None, returns all stats
    /// - If selector is Sender, returns outbound RTP streams for that sender
    ///   and all stats referenced by those streams
    /// - If selector is Receiver, returns inbound RTP streams for that receiver
    ///   and all stats referenced by those streams
    ///
    /// # Parameters
    ///
    /// * `now` - The timestamp to use for all stats in the report
    /// * `selector` - Controls which statistics are included
    ///
    /// # Returns
    ///
    /// An `RTCStatsReport` containing the selected statistics.
    pub(crate) fn snapshot_with_selector(
        &self,
        now: Instant,
        selector: StatsSelector,
    ) -> RTCStatsReport {
        match selector {
            StatsSelector::None => self.snapshot(now),
            StatsSelector::Sender(sender_id) => self.snapshot_for_sender(now, sender_id.0),
            StatsSelector::Receiver(receiver_id) => self.snapshot_for_receiver(now, receiver_id.0),
        }
    }

    /// Creates a snapshot for a specific sender (outbound streams).
    fn snapshot_for_sender(
        &self,
        now: Instant,
        transceiver_id: RTCRtpTransceiverId,
    ) -> RTCStatsReport {
        let mut entries = Vec::new();
        let mut referenced_codec_ids = HashSet::new();
        let mut referenced_transport_ids: HashSet<String> = HashSet::new();
        let mut has_streams = false;

        // Collect outbound RTP streams for this sender
        for stream in self.outbound_rtp_streams.values() {
            if stream.transceiver_id == transceiver_id {
                has_streams = true;
                entries.push(RTCStatsReportEntry::OutboundRtp(
                    self.outbound_snapshot(now, stream),
                ));
                if stream.has_remote() {
                    entries.push(RTCStatsReportEntry::RemoteInboundRtp(
                        stream.snapshot_remote(now),
                    ));
                }
                // Track referenced codec
                if !stream.codec_id.is_empty() {
                    referenced_codec_ids.insert(stream.codec_id.clone());
                }
                referenced_transport_ids.insert(stream.transport_id.clone());
            }
        }

        // Add referenced stats if we have any streams
        if has_streams {
            // The transports the streams reference
            for transport in self.every_transport() {
                if referenced_transport_ids.contains(&transport.transport_id) {
                    entries.push(RTCStatsReportEntry::Transport(transport.snapshot(now)));
                }
            }

            // Referenced codec stats
            for (id, codec) in &self.codecs {
                if referenced_codec_ids.contains(id) {
                    entries.push(RTCStatsReportEntry::Codec(codec.snapshot(now, id)));
                }
            }

            // The media source of the sender's track (referenced by the outbound streams)
            for (track_id, source) in &self.media_sources {
                if source.transceiver_id == Some(transceiver_id)
                    && let Some(entry) = Self::media_source_entry(now, track_id, source)
                {
                    entries.push(entry);
                }
            }

            // ICE candidate pair stats (referenced by transport)
            for (id, pair) in &self.ice_candidate_pairs {
                if referenced_transport_ids.contains(&pair.transport_id) {
                    entries.push(RTCStatsReportEntry::IceCandidatePair(
                        pair.snapshot(now, id),
                    ));
                }
            }

            // Local ICE candidate stats
            for (id, candidate) in &self.local_candidates {
                entries.push(RTCStatsReportEntry::LocalCandidate(
                    candidate.snapshot_local(now, id),
                ));
            }

            // Remote ICE candidate stats
            entries.extend(self.remote_candidate_entries(now));

            // Certificate stats (referenced by transport)
            for (id, cert) in &self.certificates {
                entries.push(RTCStatsReportEntry::Certificate(cert.snapshot(now, id)));
            }
        }

        self.report(now, entries)
    }

    /// Creates a snapshot for a specific receiver (inbound streams).
    fn snapshot_for_receiver(
        &self,
        now: Instant,
        transceiver_id: RTCRtpTransceiverId,
    ) -> RTCStatsReport {
        let mut entries = Vec::new();
        let mut referenced_codec_ids = HashSet::new();
        let mut referenced_transport_ids: HashSet<String> = HashSet::new();
        let mut referenced_playout_ids: HashSet<String> = HashSet::new();
        let mut has_streams = false;

        // Collect inbound RTP streams for this receiver
        for stream in self.inbound_rtp_streams.values() {
            if stream.transceiver_id == transceiver_id {
                has_streams = true;
                let id = stream.stats_id();
                entries.push(RTCStatsReportEntry::InboundRtp(stream.snapshot(now, &id)));
                if stream.has_remote() {
                    entries.push(RTCStatsReportEntry::RemoteOutboundRtp(
                        stream.snapshot_remote(now),
                    ));
                }
                // Track referenced codec
                if !stream.codec_id.is_empty() {
                    referenced_codec_ids.insert(stream.codec_id.clone());
                }
                referenced_transport_ids.insert(stream.transport_id.clone());
                if let Some(playout_id) = &stream.playout_id {
                    referenced_playout_ids.insert(playout_id.clone());
                }
            }
        }

        // Add referenced stats if we have any streams
        if has_streams {
            // The transports the streams reference
            for transport in self.every_transport() {
                if referenced_transport_ids.contains(&transport.transport_id) {
                    entries.push(RTCStatsReportEntry::Transport(transport.snapshot(now)));
                }
            }

            // Referenced codec stats
            for (id, codec) in &self.codecs {
                if referenced_codec_ids.contains(id) {
                    entries.push(RTCStatsReportEntry::Codec(codec.snapshot(now, id)));
                }
            }

            // Referenced audio playouts
            for (id, playout) in &self.audio_playouts {
                if referenced_playout_ids.contains(id) {
                    entries.push(RTCStatsReportEntry::AudioPlayout(playout.snapshot(now, id)));
                }
            }

            // ICE candidate pair stats (referenced by transport)
            for (id, pair) in &self.ice_candidate_pairs {
                if referenced_transport_ids.contains(&pair.transport_id) {
                    entries.push(RTCStatsReportEntry::IceCandidatePair(
                        pair.snapshot(now, id),
                    ));
                }
            }

            // Local ICE candidate stats
            for (id, candidate) in &self.local_candidates {
                entries.push(RTCStatsReportEntry::LocalCandidate(
                    candidate.snapshot_local(now, id),
                ));
            }

            // Remote ICE candidate stats
            entries.extend(self.remote_candidate_entries(now));

            // Certificate stats (referenced by transport)
            for (id, cert) in &self.certificates {
                entries.push(RTCStatsReportEntry::Certificate(cert.snapshot(now, id)));
            }
        }

        self.report(now, entries)
    }

    // ========================================================================
    // Convenience methods for updating stats
    // ========================================================================

    /// Gets or creates an inbound stream accumulator for the given SSRC.
    ///
    /// # Parameters
    ///
    /// * `ssrc` - The SSRC identifier for this stream
    /// * `kind` - The media kind (audio/video)
    /// * `track_identifier` - The track identifier from MediaStreamTrack
    /// * `mid` - The media stream identification tag from SDP
    /// * `rtx_ssrc` - The RTX SSRC for retransmissions (if available)
    /// * `fec_ssrc` - The FEC SSRC for forward error correction (if available)
    /// * `transceiver_id` - The transceiver ID that owns this stream
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn get_or_create_inbound_rtp_streams(
        &mut self,
        ssrc: SSRC,
        kind: RtpCodecKind,
        track_identifier: &str,
        mid: &str,
        rtx_ssrc: Option<u32>,
        fec_ssrc: Option<u32>,
        transceiver_id: RTCRtpTransceiverId,
    ) -> &mut InboundRtpStreamAccumulator {
        // Populate reverse lookup maps for O(1) RTX/FEC detection, replacing the entry of a
        // repair SSRC the stream had before
        let existing = self.inbound_rtp_streams.get(&ssrc);
        let (old_rtx, old_fec) = (
            existing.and_then(|s| s.rtx_ssrc),
            existing.and_then(|s| s.fec_ssrc),
        );
        if let Some(rtx) = rtx_ssrc {
            associate(&mut self.inbound_rtx_ssrc_to_primary, old_rtx, rtx, ssrc);
        }
        if let Some(fec) = fec_ssrc {
            associate(&mut self.fec_ssrc_to_primary, old_fec, fec, ssrc);
        }

        let transport_id = self.section_transport_id(mid);
        let stream =
            self.inbound_rtp_streams
                .entry(ssrc)
                .or_insert_with(|| InboundRtpStreamAccumulator {
                    ssrc,
                    kind,
                    transport_id,
                    track_identifier: track_identifier.to_string(),
                    mid: mid.to_string(),
                    rtx_ssrc,
                    fec_ssrc,
                    transceiver_id,
                    generation: self.streams_retired,
                    ecn: self.ecn,
                    ..Default::default()
                });
        // An existing stream takes the repair SSRCs it is given now, as the reverse maps did.
        if rtx_ssrc.is_some() {
            stream.rtx_ssrc = rtx_ssrc;
        }
        if fec_ssrc.is_some() {
            stream.fec_ssrc = fec_ssrc;
        }
        stream
    }

    /// Drops the inbound stream accumulator for `ssrc` (its remote-outbound object with it) and
    /// every RTX / FEC lookup that points at it, once the stream is no longer bound (its rid
    /// moved to another SSRC).
    pub(crate) fn remove_inbound_rtp_stream(&mut self, ssrc: SSRC) {
        if self.inbound_rtp_streams.remove(&ssrc).is_some() {
            self.streams_retired += 1;
        }
        self.inbound_rtx_ssrc_to_primary
            .retain(|_, primary| *primary != ssrc);
        self.fec_ssrc_to_primary
            .retain(|_, primary| *primary != ssrc);
    }

    /// Updates the RTX SSRC association for an existing inbound RTP stream.
    ///
    /// This is used when `rrid` (repaired RTP stream ID) arrives after the base
    /// stream's `InboundRtpStreamAccumulator` has already been created. It updates
    /// both the reverse-lookup map (`inbound_rtx_ssrc_to_primary`) and the inbound stream's
    /// `rtx_ssrc` field so that `on_rtx_packet_received_if_rtx()` can recognize
    /// these packets and `getStats()` reports the correct `rtxSsrc`.
    ///
    /// # Arguments
    ///
    /// * `primary_ssrc` - The SSRC of the base/primary stream
    /// * `rtx_ssrc` - The RTX SSRC to associate with the primary stream
    pub(crate) fn update_inbound_rtx_ssrc(&mut self, primary_ssrc: SSRC, rtx_ssrc: SSRC) {
        let old_rtx = self
            .inbound_rtp_streams
            .get(&primary_ssrc)
            .and_then(|s| s.rtx_ssrc);
        associate(
            &mut self.inbound_rtx_ssrc_to_primary,
            old_rtx,
            rtx_ssrc,
            primary_ssrc,
        );
        if let Some(stream) = self.inbound_rtp_streams.get_mut(&primary_ssrc) {
            stream.rtx_ssrc = Some(rtx_ssrc);
        }
    }

    /// Gets or creates an outbound stream accumulator for the given SSRC.
    ///
    /// # Parameters
    ///
    /// * `ssrc` - The SSRC identifier for this stream
    /// * `kind` - The media kind (audio/video)
    /// * `mid` - The media stream identification tag from SDP
    /// * `rid` - The RTP stream ID for simulcast (empty if not simulcast)
    /// * `encoding_index` - The index of this encoding in the simulcast layer order
    /// * `rtx_ssrc` - The RTX SSRC for retransmissions (if available)
    /// * `transceiver_id` - The transceiver ID that owns this stream
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn get_or_create_outbound_rtp_streams(
        &mut self,
        ssrc: SSRC,
        kind: RtpCodecKind,
        mid: &str,
        rid: &str,
        encoding_index: u32,
        rtx_ssrc: Option<u32>,
        transceiver_id: RTCRtpTransceiverId,
    ) -> &mut OutboundRtpStreamAccumulator {
        if let Some(rtx) = rtx_ssrc {
            let old_rtx = self
                .outbound_rtp_streams
                .get(&ssrc)
                .and_then(|s| s.rtx_ssrc);
            associate(&mut self.outbound_rtx_ssrc_to_primary, old_rtx, rtx, ssrc);
        }

        // A media source the application already reported for this sender's track.
        let media_source_id = self
            .media_sources
            .iter()
            .find(|(_, source)| source.transceiver_id == Some(transceiver_id))
            .map(|(track_id, _)| media_source_stats_id(track_id))
            .unwrap_or_default();

        let transport_id = self.section_transport_id(mid);
        self.outbound_rtp_streams
            .entry(ssrc)
            .or_insert_with(|| OutboundRtpStreamAccumulator {
                ssrc,
                kind,
                transport_id,
                media_source_id,
                mid: mid.to_string(),
                rid: rid.to_string(),
                encoding_index,
                rtx_ssrc,
                transceiver_id,
                generation: self.streams_retired,
                active: true,
                ecn: self.ecn,
                ..Default::default()
            })
    }

    /// Gets or creates a data channel accumulator.
    ///
    /// # Parameters
    ///
    /// * `id` - The data channel identifier
    /// * `label` - The label assigned to the data channel
    /// * `protocol` - The sub-protocol name
    pub(crate) fn get_or_create_data_channel(
        &mut self,
        id: RTCDataChannelId,
        label: &str,
        protocol: &str,
    ) -> &mut DataChannelStatsAccumulator {
        self.data_channels
            .entry(id)
            .or_insert_with(|| DataChannelStatsAccumulator {
                // The wire value is filled in by `set_data_channel_stream_id` once the SCTP
                // connected procedure assigns one; the map itself is keyed by handle, so an
                // accumulator can exist before then.
                data_channel_identifier: None,
                label: label.to_string(),
                protocol: protocol.to_string(),
                ..Default::default()
            })
    }

    /// A data channel is gone for good. Its stats object stays, in the "closed" state
    /// (webrtc-stats section 3.3: a stats object outlives its closed object, its last values
    /// kept), for the [`MAX_CLOSED_DATA_CHANNEL_STATS`] channels closed last; an older one goes.
    /// If the channel had been open it is counted in `dataChannelsClosed` (webrtc-stats: the
    /// channels that "left the open state"; one that never opened, closed while connecting or
    /// by the handshake timeout, is not one of them).
    pub(crate) fn on_data_channel_gone(&mut self, id: RTCDataChannelId) {
        let Some(channel) = self.data_channels.get_mut(&id) else {
            return;
        };
        if channel.state == crate::data_channel::RTCDataChannelState::Closed
            && self.closed_data_channels.contains(&id)
        {
            return;
        }
        channel.state = crate::data_channel::RTCDataChannelState::Closed;
        if channel.opened {
            self.peer_connection.on_data_channel_closed();
        }
        self.closed_data_channels.push_back(id);
        while self.closed_data_channels.len() > MAX_CLOSED_DATA_CHANNEL_STATS {
            if let Some(oldest) = self.closed_data_channels.pop_front() {
                self.data_channels.remove(&oldest);
            }
        }
    }

    /// Records the SCTP stream identifier a data channel was assigned.
    ///
    /// The accumulator is keyed by the channel's handle, which exists from creation, but
    /// `data_channel_identifier` is the W3C-defined *wire* value and is only known once the
    /// SCTP connected procedure assigns one (RFC 8832 section 6). This fills it in at that
    /// point; until then the report leaves the member out.
    pub(crate) fn set_data_channel_stream_id(&mut self, id: RTCDataChannelId, stream_id: StreamId) {
        if let Some(dc) = self.data_channels.get_mut(&id) {
            dc.data_channel_identifier = Some(stream_id);
        }
    }

    /// Gets or creates an ICE candidate pair accumulator.
    pub(crate) fn get_or_create_candidate_pair(
        &mut self,
        local_id: &str,
        remote_id: &str,
    ) -> &mut IceCandidatePairAccumulator {
        self.ice_candidate_pairs
            .entry(candidate_pair_stats_id(local_id, remote_id))
            .or_insert_with(|| IceCandidatePairAccumulator {
                transport_id: self.transport.transport_id.clone(),
                // W3C RTCIceCandidatePairStats: localCandidateId / remoteCandidateId are the ids
                // of the local-candidate / remote-candidate stats objects, which are registered
                // under these names (`add_ice_local_candidate` / `add_ice_remote_candidate`).
                local_candidate_id: local_candidate_stats_id(local_id),
                remote_candidate_id: remote_candidate_stats_id(remote_id),
                ..Default::default()
            })
    }

    /// Registers a local ICE candidate.
    pub(crate) fn register_local_candidate(
        &mut self,
        id: String,
        candidate: IceCandidateAccumulator,
    ) {
        self.local_candidates.insert(id, candidate);
    }

    /// Registers a remote ICE candidate.
    pub(crate) fn register_remote_candidate(
        &mut self,
        id: String,
        candidate: IceCandidateAccumulator,
    ) {
        self.remote_candidates.insert(id, candidate);
    }

    /// Deletes the candidates that are gone: those the ICE agent no longer holds and no
    /// candidate pair object names.
    ///
    /// webrtc-stats 7.1: a candidate object is deleted when the ICE transport does an ICE
    /// restart and the candidate is no longer a member of any non-deleted candidate pair. A
    /// restart is when the agent lets go of its candidates; the selected pair's stay until
    /// another pair is selected, as that pair does.
    pub(crate) fn retain_candidates(
        &mut self,
        local_held: &HashSet<String>,
        remote_held: &HashSet<String>,
    ) {
        let (mut local_paired, mut remote_paired) = (HashSet::new(), HashSet::new());
        for pair in self.ice_candidate_pairs.values() {
            local_paired.insert(pair.local_candidate_id.clone());
            remote_paired.insert(pair.remote_candidate_id.clone());
        }
        // The candidates of the active transport's agent; another transport's are its own.
        let theirs = |candidates: &HashMap<String, IceCandidateAccumulator>| -> HashSet<String> {
            candidates
                .iter()
                .filter(|(_, candidate)| !self.of_active_transport(&candidate.transport_id))
                .map(|(id, _)| id.clone())
                .collect()
        };
        let (local_theirs, remote_theirs) = (
            theirs(&self.local_candidates),
            theirs(&self.remote_candidates),
        );
        self.local_candidates.retain(|id, _| {
            local_theirs.contains(id) || local_held.contains(id) || local_paired.contains(id)
        });
        self.remote_candidates.retain(|id, _| {
            remote_theirs.contains(id) || remote_held.contains(id) || remote_paired.contains(id)
        });
    }

    /// Registers a certificate.
    pub(crate) fn register_certificate(
        &mut self,
        fingerprint: String,
        cert: CertificateStatsAccumulator,
    ) {
        self.certificates.insert(fingerprint, cert);
    }

    /// Gets or creates a media source accumulator.
    pub(crate) fn get_or_create_media_source(
        &mut self,
        track_id: &str,
        kind: RtpCodecKind,
    ) -> &mut MediaSourceStatsAccumulator {
        self.media_sources
            .entry(track_id.to_string())
            .or_insert_with(|| MediaSourceStatsAccumulator {
                track_id: track_id.to_string(),
                kind,
                ..Default::default()
            })
    }

    /// Gets or creates an audio playout accumulator.
    pub(crate) fn get_or_create_audio_playout(
        &mut self,
        playout_id: &str,
    ) -> &mut AudioPlayoutStatsAccumulator {
        self.audio_playouts
            .entry(playout_id.to_string())
            .or_insert_with(|| AudioPlayoutStatsAccumulator {
                kind: RtpCodecKind::Audio,
                ..Default::default()
            })
    }

    /// Notes that the application wrote an RTP packet for the stream `ssrc` at `now`, before
    /// the interceptor chain has it (`totalPacketSendDelay` runs from here).
    pub(crate) fn on_rtp_written(&mut self, ssrc: SSRC, sequence_number: u16, now: Instant) {
        if let Some(stream) = self.outbound_rtp_streams.get_mut(&ssrc) {
            stream.on_rtp_written(sequence_number, now);
        }
    }

    /// Counts an RTP packet going out on `ssrc`: `overhead_bytes` is its header and padding,
    /// `payload_bytes` its payload, and `retransmission` says it answers a NACK.
    ///
    /// * On a stream's own SSRC it is a packet of the stream, and with `retransmission` (the
    ///   stream has no RTX stream, so the packet is sent again as it was, RFC 4585) one of its
    ///   retransmitted packets too.
    /// * On a stream's RTX SSRC it is a packet of that stream as well (webrtc-stats 7.1: an
    ///   RTX stream is no object of its own and counts in `packetsSent` / `bytesSent`). One
    ///   that repeats a packet is a retransmitted packet whose bytes are the repeated payload;
    ///   the original sequence number in front of it (RFC 4588 section 4) is header. One too
    ///   short to repeat anything (padding only: a bandwidth probe) is header and padding and
    ///   no retransmission.
    pub(crate) fn on_rtp_sent(
        &mut self,
        ssrc: SSRC,
        sequence_number: u16,
        overhead_bytes: usize,
        payload_bytes: usize,
        retransmission: bool,
        now: Instant,
    ) {
        if let Some(stream) = self.outbound_rtp_streams.get_mut(&ssrc) {
            stream.on_rtp_sent(overhead_bytes, payload_bytes, now);
            stream.on_sequence_number_sent(sequence_number);
            if retransmission {
                stream.on_rtx_sent(payload_bytes);
            } else {
                stream.on_written_rtp_sent(sequence_number, now);
            }
        } else if let Some(primary_ssrc) = self.outbound_rtx_ssrc_to_primary.get(&ssrc)
            && let Some(stream) = self.outbound_rtp_streams.get_mut(primary_ssrc)
        {
            match payload_bytes.checked_sub(RTX_OSN_BYTES) {
                Some(repeated_bytes) => {
                    stream.on_rtp_sent(overhead_bytes + RTX_OSN_BYTES, repeated_bytes, now);
                    stream.on_rtx_sent(repeated_bytes);
                }
                None => stream.on_rtp_sent(overhead_bytes + payload_bytes, 0, now),
            }
        }
    }

    /// The ECN codepoint to send an outgoing RTP packet `sequence_number` of `ssrc` with at
    /// `now`: ECT(1) or Not-ECT (`None`) as the stream's ECN validation decides (RFC 8888
    /// section 7, RFC 6679 sections 7.2-7.4: probes while initiating, every packet once
    /// confirmed, none after a failure), for a stream that marks at all
    /// ([`OutboundRtpStreamAccumulator::ect1_marking`]). An RTX packet is marked only while
    /// the stream it repairs marks every packet. ECT(1) packets are counted on the stream.
    pub(crate) fn ecn_for_rtp_sent(
        &mut self,
        ssrc: SSRC,
        sequence_number: u16,
        now: Instant,
    ) -> Option<shared::EcnCodepoint> {
        if !self.ecn {
            return None;
        }
        let (primary, own) = if self.outbound_rtp_streams.contains_key(&ssrc) {
            (ssrc, true)
        } else {
            (*self.outbound_rtx_ssrc_to_primary.get(&ssrc)?, false)
        };
        let marking = self.ecn_marking;
        let stream = self.outbound_rtp_streams.get_mut(&primary)?;
        if !stream.ect1_marking {
            return None;
        }
        let validation = stream.ecn_validation.as_deref_mut()?;
        let marked = if own {
            validation.on_send(now, sequence_number)
        } else {
            validation.marks_all()
        };
        if !marked {
            return None;
        }
        let codepoint = marking.codepoint(stream.ect_preference, rand::random::<bool>());
        if codepoint == shared::EcnCodepoint::Ect1 {
            stream.on_ect1_sent();
        }
        Some(codepoint)
    }

    /// The ECN failures each outbound stream's validation detected since the last call, by
    /// SSRC (RFC 6679 sections 7.2.1 and 7.4.2).
    pub(crate) fn take_ecn_failures(&mut self) -> Vec<(u32, interceptor::EcnFailure)> {
        let mut failures = vec![];
        for (ssrc, stream) in self.outbound_rtp_streams.iter_mut() {
            if let Some(validation) = stream.ecn_validation.as_deref_mut() {
                failures.extend(
                    validation
                        .take_failures()
                        .into_iter()
                        .map(|failure| (*ssrc, failure)),
                );
            }
        }
        failures
    }

    /// A remote source named its RTCP CNAME at `now`: each outbound stream's ECN validation
    /// watches for a second participant while its success is provisional (RFC 6679
    /// section 7.2.1).
    pub(crate) fn on_remote_cname(&mut self, now: Instant, cname: &str) {
        if !self.remote_cnames.iter().any(|known| known == cname) && self.remote_cnames.len() < 16 {
            self.remote_cnames.push(cname.to_owned());
        }
        for stream in self.outbound_rtp_streams.values_mut() {
            if let Some(validation) = stream.ecn_validation.as_deref_mut() {
                validation.on_remote_cname(now, cname);
            }
        }
    }

    /// Records the ECT codepoint the receiver of the outbound stream `ssrc` asks for (the
    /// `ect=` of its `a=ecn-capable-rtp`, RFC 6679 section 6.1); `None`: it asks for none,
    /// ECT(0) applies (section 7.3.1).
    pub(crate) fn set_outbound_ect_preference(
        &mut self,
        ssrc: SSRC,
        preference: Option<interceptor::EctPreference>,
    ) {
        let l4s = self.ecn_marking == interceptor::EcnMarking::L4s;
        if let Some(stream) = self.outbound_rtp_streams.get_mut(&ssrc) {
            stream.ect_preference = preference;
            stream.sends_ect1 = l4s || preference == Some(interceptor::EctPreference::Ect1);
        }
    }

    /// Counts the ECN codepoint an RTP packet of the inbound stream `ssrc` arrived with.
    pub(crate) fn on_rtp_ecn_received(&mut self, ssrc: SSRC, ecn: Option<shared::EcnCodepoint>) {
        if self.ecn
            && let Some(stream) = self.inbound_rtp_streams.get_mut(&ssrc)
        {
            stream.on_ecn_received(ecn);
        }
    }

    /// Records whether the inbound stream `ssrc`'s codec negotiated RFC 8888 feedback.
    pub(crate) fn set_inbound_ccfb(&mut self, ssrc: SSRC, negotiated: bool) {
        if let Some(stream) = self.inbound_rtp_streams.get_mut(&ssrc) {
            stream.ccfb_negotiated = negotiated;
        }
    }

    /// Records whether the outbound stream `ssrc` negotiated RFC 6679 ECN reports (the XR
    /// ECN Summary Report, `a=rtcp-xr:ecn-sum`, which RFC 6679 section 7.1 requires whatever
    /// the initiation; `nack ecn` adds the feedback packet). Set before
    /// [`set_outbound_ccfb`](Self::set_outbound_ccfb), which decides the marking: a stream
    /// that is not reported in RFC 8888 marks with these reports instead.
    pub(crate) fn set_outbound_rfc6679(&mut self, ssrc: SSRC, negotiated: bool) {
        if let Some(stream) = self.outbound_rtp_streams.get_mut(&ssrc) {
            stream.rfc6679_negotiated = negotiated;
        }
    }

    /// Records whether the outbound stream `ssrc`'s codec negotiated RFC 8888 feedback, and
    /// whether its section negotiated ECN (`ecn`: the initiation and the codepoint the receiver
    /// asks for, RFC 6679 section 6.1.1, `a=ecn-capable-rtp`); with ECN on and both
    /// negotiated, its packets are sent ECT. A stream that is not reported in RFC 8888 marks
    /// when it negotiated RFC 6679's own reports
    /// ([`set_outbound_rfc6679`](Self::set_outbound_rfc6679)), ECN negotiated too.
    pub(crate) fn set_outbound_ccfb(
        &mut self,
        ssrc: SSRC,
        negotiated: bool,
        ecn_negotiated: Option<crate::peer_connection::sdp::ecn::NegotiatedEcn>,
    ) {
        let ecn = self.ecn && ecn_negotiated.is_some();
        let initiation = ecn_negotiated.map_or(self.ecn_initiation, |n| n.initiation);
        let l4s = self.ecn_marking == interceptor::EcnMarking::L4s;
        let remote_cnames = &self.remote_cnames;
        if let Some(stream) = self.outbound_rtp_streams.get_mut(&ssrc) {
            stream.ect_preference = ecn_negotiated.and_then(|n| n.preference);
            stream.sends_ect1 =
                l4s || stream.ect_preference == Some(interceptor::EctPreference::Ect1);
            stream.ccfb_negotiated = negotiated;
            // RFC 8888 reports, or RFC 6679's own ECN reports, carry the marks back.
            stream.ect1_marking = ecn && (negotiated || stream.rfc6679_negotiated);
            // A renegotiation that keeps `ack ccfb` keeps where the stream is in the
            // procedure; one that drops it ends it.
            if !stream.ect1_marking {
                stream.ecn_validation = None;
            } else if stream.ecn_validation.is_none() {
                let mut validation = interceptor::EcnValidation::new(initiation);
                if let Some(first) = remote_cnames.first() {
                    validation = validation.with_receiver_cname(first);
                }
                stream.ecn_validation = Some(Box::new(validation));
            }
        }
    }

    /// Counts an RTP packet that arrived on `ssrc` as it is (not a retransmission that was
    /// taken out of its RTX packet:
    /// [`on_retransmission_received`](Self::on_retransmission_received) counts that):
    /// `overhead_bytes` is its header and padding, `payload_bytes` its payload.
    ///
    /// * On a stream's own SSRC it is a packet of the stream.
    /// * On a stream's FEC SSRC it is a packet of that stream too, and a FEC packet
    ///   (webrtc-stats 7.1: a FEC stream is no object of its own; `fecBytesReceived` is a
    ///   subset of `bytesReceived`).
    /// * On a stream's RTX SSRC, still there because it repeats no packet (padding only, a
    ///   bandwidth probe: RFC 4588 section 4), it is a packet of the stream made of header and
    ///   padding, and not a retransmission.
    ///
    /// Returns whether a stream counted it.
    pub(crate) fn on_rtp_received(
        &mut self,
        ssrc: SSRC,
        overhead_bytes: usize,
        payload_bytes: usize,
        now: Instant,
    ) -> bool {
        if let Some(stream) = self.inbound_rtp_streams.get_mut(&ssrc) {
            stream.on_rtp_received(overhead_bytes, payload_bytes, now);
            return true;
        }
        if let Some(primary_ssrc) = self.fec_ssrc_to_primary.get(&ssrc)
            && let Some(stream) = self.inbound_rtp_streams.get_mut(primary_ssrc)
        {
            stream.on_fec_received(overhead_bytes, payload_bytes, now);
            return true;
        }
        if let Some(primary_ssrc) = self.inbound_rtx_ssrc_to_primary.get(&ssrc)
            && let Some(stream) = self.inbound_rtp_streams.get_mut(primary_ssrc)
        {
            stream.on_rtx_padding_received(overhead_bytes + payload_bytes, now);
            return true;
        }
        false
    }

    /// Counts a FEC packet of the media stream `media_ssrc` that arrived in a FEC session of
    /// its own (RFC 5109 section 14.1, under the media SSRC on another transport): a packet of
    /// the stream and FEC, as one on its FEC SSRC is (webrtc-stats 7.1: "FEC streams do not
    /// show up as separate objects" but count in `packetsReceived`, `bytesReceived`,
    /// `fecPacketsReceived` and `fecBytesReceived`). Returns whether the stream exists.
    pub(crate) fn on_fec_session_received(
        &mut self,
        media_ssrc: SSRC,
        overhead_bytes: usize,
        payload_bytes: usize,
        now: Instant,
    ) -> bool {
        let Some(stream) = self.inbound_rtp_streams.get_mut(&media_ssrc) else {
            return false;
        };
        stream.on_fec_received(overhead_bytes, payload_bytes, now);
        true
    }

    /// What the chain's ULPFEC decoder reported for one of its streams (totals since the
    /// stream was bound, so the latest replaces what was there).
    pub(crate) fn on_ulpfec_receive_stats(&mut self, stats: interceptor::UlpfecReceiveStats) {
        if let Some(stream) = self.inbound_rtp_streams.get_mut(&stats.media_ssrc) {
            stream.ulpfec = Some(stats);
        }
    }

    /// A media packet of `ssrc` that FEC rebuilt left the chain for the application.
    pub(crate) fn on_recovered_by_fec(&mut self, ssrc: SSRC) {
        if let Some(stream) = self.inbound_rtp_streams.get_mut(&ssrc) {
            stream.packets_recovered_by_fec += 1;
        }
    }

    /// FEC for the outbound stream `media_ssrc` left the chain (an `interceptor::FecSent`
    /// mark).
    pub(crate) fn on_fec_sent(&mut self, sent: interceptor::FecSent) {
        if let Some(stream) = self.outbound_rtp_streams.get_mut(&sent.media_ssrc) {
            stream.fec_packets_sent += u64::from(sent.packets);
            stream.fec_bytes_sent += sent.bytes;
        }
    }

    /// The FEC counts webrtc-stats has no member for, per stream that has any.
    pub(crate) fn fec_stats(&self) -> crate::statistics::FecStats {
        let mut stats = crate::statistics::FecStats::default();
        let mut sent: Vec<_> = self
            .outbound_rtp_streams
            .values()
            .filter(|stream| stream.fec_packets_sent > 0)
            .map(|stream| crate::statistics::FecSentStats {
                ssrc: stream.ssrc,
                fec_packets_sent: stream.fec_packets_sent,
                fec_bytes_sent: stream.fec_bytes_sent,
            })
            .collect();
        sent.sort_by_key(|stream| stream.ssrc);
        let mut received: Vec<_> = self
            .inbound_rtp_streams
            .values()
            .filter(|stream| {
                stream.fec_packets_received > 0
                    || stream.ulpfec.is_some()
                    || stream.packets_recovered_by_fec > 0
            })
            .map(|stream| {
                let ulpfec = stream.ulpfec;
                let decoder = ulpfec.map(|ulpfec| ulpfec.decoder).unwrap_or_default();
                crate::statistics::FecReceivedStats {
                    ssrc: stream.ssrc,
                    fec_packets_received: stream.fec_packets_received
                        + ulpfec.map_or(0, |ulpfec| ulpfec.fec_packets_in_red),
                    fec_bytes_received: stream.fec_bytes_received
                        + ulpfec.map_or(0, |ulpfec| ulpfec.fec_bytes_in_red),
                    fec_packets_in_red: ulpfec.map_or(0, |ulpfec| ulpfec.fec_packets_in_red),
                    packets_recovered: stream.packets_recovered_by_fec,
                    fec_packets_discarded: decoder.discarded(),
                    discarded_unneeded: decoder.discarded_unneeded,
                    discarded_expired: decoder.discarded_expired,
                    discarded_rejected: decoder.fec_rejected,
                }
            })
            .collect();
        received.sort_by_key(|stream| stream.ssrc);
        stats.sent = sent;
        stats.received = received;
        stats
    }

    /// Counts a retransmission that arrived in an RTX packet for the stream `primary_ssrc`:
    /// `overhead_bytes` is the RTX packet's header and padding, `payload_bytes` its payload,
    /// which starts with the original sequence number (RFC 4588 section 4).
    ///
    /// It is a packet of the stream (`packetsReceived` includes retransmissions) and one of
    /// its retransmitted packets, whose bytes are the repeated payload; the original sequence
    /// number is header. Returns whether the stream exists.
    pub(crate) fn on_retransmission_received(
        &mut self,
        primary_ssrc: SSRC,
        overhead_bytes: usize,
        payload_bytes: usize,
        now: Instant,
    ) -> bool {
        let Some(stream) = self.inbound_rtp_streams.get_mut(&primary_ssrc) else {
            return false;
        };
        let repeated_bytes = payload_bytes.saturating_sub(RTX_OSN_BYTES);
        stream.on_rtp_received(
            overhead_bytes + (payload_bytes - repeated_bytes),
            repeated_bytes,
            now,
        );
        stream.on_rtx_received(repeated_bytes);
        true
    }

    /// Counts a datagram of `bytes` bytes the application's socket refused to send, on the
    /// candidate pair in use (`packetsDiscardedOnSend`, `bytesDiscardedOnSend`). Returns
    /// `false`, and counts nothing, while no pair is selected.
    pub(crate) fn on_send_discarded(&mut self, bytes: usize) -> bool {
        match self
            .ice_candidate_pairs
            .get_mut(&self.transport.selected_candidate_pair_id)
        {
            Some(pair) => {
                pair.on_packet_discarded(bytes);
                true
            }
            None => false,
        }
    }

    // ========================================================================
    // Application-provided stats updates
    // ========================================================================

    /// Merges application-provided decoder stats into an inbound stream; `false` when no
    /// inbound stream has that SSRC.
    pub(crate) fn update_decoder_stats(&mut self, ssrc: SSRC, stats: DecoderStatsUpdate) -> bool {
        match self.inbound_rtp_streams.get_mut(&ssrc) {
            Some(stream) => {
                stream.decoder_stats.merge(stats);
                true
            }
            None => false,
        }
    }

    /// Merges application-provided encoder stats into an outbound stream; `false` when no
    /// outbound stream has that SSRC.
    pub(crate) fn update_encoder_stats(&mut self, ssrc: SSRC, stats: EncoderStatsUpdate) -> bool {
        match self.outbound_rtp_streams.get_mut(&ssrc) {
            Some(stream) => {
                stream.encoder_stats.merge(stats);
                true
            }
            None => false,
        }
    }

    /// Merges application-provided audio receiver stats into an inbound stream; `false` when
    /// no inbound stream has that SSRC.
    pub(crate) fn update_audio_receiver_stats(
        &mut self,
        ssrc: SSRC,
        stats: AudioReceiverStatsUpdate,
    ) -> bool {
        match self.inbound_rtp_streams.get_mut(&ssrc) {
            Some(stream) => {
                stream.audio_receiver_stats.merge(stats);
                true
            }
            None => false,
        }
    }

    /// Makes the media sources those of `attached`: the (transceiver, track id, kind) of every
    /// sender that has a track.
    ///
    /// webrtc-stats 8.11: a media-source object exists from the time its track is attached to
    /// a sender until it is attached to none. A track newly attached gets an object, which has
    /// the track's id and kind until the application supplies what it captured; the object of
    /// a track no sender has any more is deleted. Each sender's outbound streams name their
    /// track's object (`mediaSourceId`).
    pub(crate) fn sync_media_sources(
        &mut self,
        attached: &[(RTCRtpTransceiverId, String, RtpCodecKind)],
    ) {
        self.media_sources.retain(|track_id, _| {
            attached
                .iter()
                .any(|(_, attached_id, _)| attached_id == track_id)
        });
        for stream in self.outbound_rtp_streams.values_mut() {
            stream.media_source_id.clear();
        }
        for (transceiver_id, track_id, kind) in attached {
            if !matches!(kind, RtpCodecKind::Audio | RtpCodecKind::Video) {
                continue;
            }
            let source = self.get_or_create_media_source(track_id, *kind);
            source.transceiver_id = Some(*transceiver_id);
            self.link_media_source(track_id, *transceiver_id);
        }
    }

    /// Names the media source for `track_id` as the source of the outbound streams of
    /// `transceiver_id` (`mediaSourceId`).
    fn link_media_source(&mut self, track_id: &str, transceiver_id: RTCRtpTransceiverId) {
        let id = media_source_stats_id(track_id);
        for stream in self.outbound_rtp_streams.values_mut() {
            if stream.transceiver_id == transceiver_id {
                stream.media_source_id = id.clone();
            }
        }
    }

    /// Merges application-provided capture stats into the audio media source of the track
    /// `track_id`, which the sender of `transceiver_id` sends.
    pub(crate) fn update_audio_source_stats(
        &mut self,
        track_id: &str,
        transceiver_id: RTCRtpTransceiverId,
        stats: AudioSourceStatsUpdate,
    ) {
        self.link_media_source(track_id, transceiver_id);
        let source = self.get_or_create_media_source(track_id, RtpCodecKind::Audio);
        source.transceiver_id = Some(transceiver_id);
        if stats.audio_level.is_some() {
            source.audio_level = stats.audio_level;
        }
        if stats.total_audio_energy.is_some() {
            source.total_audio_energy = stats.total_audio_energy;
        }
        if stats.total_samples_duration.is_some() {
            source.total_samples_duration = stats.total_samples_duration;
        }
        if stats.echo_return_loss.is_some() {
            source.echo_return_loss = stats.echo_return_loss;
        }
        if stats.echo_return_loss_enhancement.is_some() {
            source.echo_return_loss_enhancement = stats.echo_return_loss_enhancement;
        }
    }

    /// Merges application-provided capture stats into the video media source of the track
    /// `track_id`, which the sender of `transceiver_id` sends.
    pub(crate) fn update_video_source_stats(
        &mut self,
        track_id: &str,
        transceiver_id: RTCRtpTransceiverId,
        stats: VideoSourceStatsUpdate,
    ) {
        self.link_media_source(track_id, transceiver_id);
        let source = self.get_or_create_media_source(track_id, RtpCodecKind::Video);
        source.transceiver_id = Some(transceiver_id);
        if stats.width.is_some() {
            source.width = stats.width;
        }
        if stats.height.is_some() {
            source.height = stats.height;
        }
        if stats.frames.is_some() {
            source.frames = stats.frames;
        }
        if stats.frames_per_second.is_some() {
            source.frames_per_second = stats.frames_per_second;
        }
    }

    /// Merges application-provided playout stats into an audio playout object, creating it on
    /// first use, and names it as the playout of each inbound stream in `inbound_ssrcs`.
    pub(crate) fn update_audio_playout_stats(
        &mut self,
        playout_id: &str,
        inbound_ssrcs: &[SSRC],
        stats: AudioPlayoutStatsUpdate,
    ) {
        let playout = self.get_or_create_audio_playout(playout_id);
        if stats.synthesized_samples_duration.is_some() {
            playout.synthesized_samples_duration = stats.synthesized_samples_duration;
        }
        if stats.synthesized_samples_events.is_some() {
            playout.synthesized_samples_events = stats.synthesized_samples_events;
        }
        if stats.total_samples_duration.is_some() {
            playout.total_samples_duration = stats.total_samples_duration;
        }
        if stats.total_playout_delay.is_some() {
            playout.total_playout_delay = stats.total_playout_delay;
        }
        if stats.total_samples_count.is_some() {
            playout.total_samples_count = stats.total_samples_count;
        }
        for ssrc in inbound_ssrcs {
            if let Some(stream) = self.inbound_rtp_streams.get_mut(ssrc) {
                stream.playout_id = Some(playout_id.to_string());
            }
        }
    }

    /// Syncs the candidate pair stats with the ICE agent's pairs: each pair's STUN transaction
    /// counters, round trip times, state and nomination come from the agent, while the packet
    /// and byte counters are the ones the pipeline counts on the selected pair.
    ///
    /// A pair the agent no longer holds (an ICE restart drops its pairs) is dropped from the
    /// stats too, except the transport's selected pair, whose counters describe the path still
    /// in use until another is selected.
    pub(crate) fn sync_ice_candidate_pairs(&mut self, pairs: &[CandidatePairStats]) {
        let held: std::collections::HashSet<String> = pairs
            .iter()
            .map(|cp| candidate_pair_stats_id(&cp.local_candidate_id, &cp.remote_candidate_id))
            .collect();
        let selected = self.transport.selected_candidate_pair_id.clone();
        // The pairs of the active transport's agent; another transport's are its own.
        let theirs: HashSet<String> = self
            .ice_candidate_pairs
            .iter()
            .filter(|(_, pair)| !self.of_active_transport(&pair.transport_id))
            .map(|(id, _)| id.clone())
            .collect();
        self.ice_candidate_pairs
            .retain(|id, _| theirs.contains(id) || held.contains(id) || *id == selected);

        for cp in pairs {
            let pair =
                self.get_or_create_candidate_pair(&cp.local_candidate_id, &cp.remote_candidate_id);
            pair.requests_sent = cp.requests_sent;
            pair.requests_received = cp.requests_received;
            pair.responses_sent = cp.responses_sent;
            pair.responses_received = cp.responses_received;
            pair.consent_requests_sent = cp.consent_requests_sent;
            pair.total_round_trip_time = cp.total_round_trip_time;
            pair.current_round_trip_time = cp.current_round_trip_time;
            pair.state = cp.state.into();
            pair.nominated = cp.nominated;
        }
    }

    /// Sets the congestion controller's estimate: the target bitrate of the outbound streams
    /// and the selected candidate pair's `availableOutgoingBitrate` (webrtc-stats: the bitrate
    /// the congestion control estimates for all the outgoing RTP streams on the pair).
    pub(crate) fn on_target_bitrate(
        &mut self,
        transport: usize,
        bits_per_second: f64,
        shares: &HashMap<SSRC, f64>,
    ) {
        self.on_target_shares(transport, bits_per_second, shares);
        self.on_outgoing_estimate(transport, bits_per_second);
    }

    /// The outbound streams' shares of transport `transport`'s target, divided again without a
    /// new target from the congestion controller (a flow the circuit breaker ceased or
    /// restarted): the `targetBitrate` of each stream, and nothing else. The estimate is not
    /// this call's to set: while the pacer has the source paused the target divided here is
    /// zero and the estimate is what it was (`on_outgoing_estimate`).
    pub(crate) fn on_target_shares(
        &mut self,
        transport: usize,
        bits_per_second: f64,
        shares: &HashMap<SSRC, f64>,
    ) {
        // The estimate is transport `transport`'s (one congestion controller per transport);
        // each outbound stream on it has its share as `targetBitrate`
        // (`allocate_target_bitrate_on`: by priority, capped at maxBitrate). A stream without a
        // share (not sending now) keeps its last one. Without any share (no allocation made),
        // every stream of the transport is given the estimate, which the report shows only
        // while there is one stream.
        let name = self.transport_name(transport);
        let several = !self.transports_are_one();
        for (ssrc, stream) in self.outbound_rtp_streams.iter_mut() {
            match shares.get(ssrc) {
                Some(&share) => {
                    stream.target_bitrate = share;
                    self.allocated_ssrcs.insert(*ssrc);
                }
                None if shares.is_empty() && (!several || stream.transport_id == name) => {
                    stream.target_bitrate = bits_per_second
                }
                None => {}
            }
        }
    }

    /// The congestion controller's estimate for transport `transport`, where it is not the
    /// target the streams are given: while the pacer tells the source to pause, the target is
    /// zero and the estimate is what it was (`PacerPause`).
    pub(crate) fn on_outgoing_estimate(&mut self, transport: usize, bits_per_second: f64) {
        // webrtc-stats: `availableOutgoingBitrate` is what the congestion control estimates
        // for the outgoing streams on the pair: the transport's own estimate on its selected
        // pair, not another transport's.
        self.outgoing_estimates.insert(transport, bits_per_second);
        let pair_id = self
            .transport_mut(transport)
            .map(|t| t.selected_candidate_pair_id.clone());
        if let Some(pair) = pair_id.and_then(|id| self.ice_candidate_pairs.get_mut(&id)) {
            pair.available_outgoing_bitrate = bits_per_second;
        }
    }

    /// Puts each transport's last congestion estimate on the candidate pair it has selected
    /// (webrtc-stats: `availableOutgoingBitrate` is that of a pair in use), whichever order the
    /// estimate, the selection and the pair's entry came in.
    pub(crate) fn sync_outgoing_estimates(&mut self) {
        let keys: Vec<(usize, f64)> = self
            .outgoing_estimates
            .iter()
            .map(|(key, estimate)| (*key, *estimate))
            .collect();
        let estimates: Vec<(String, f64)> = keys
            .into_iter()
            .filter_map(|(key, estimate)| {
                let pair = self.transport_mut(key)?.selected_candidate_pair_id.clone();
                Some((pair, estimate))
            })
            .collect();
        for (pair_id, estimate) in estimates {
            if let Some(pair) = self.ice_candidate_pairs.get_mut(&pair_id) {
                pair.available_outgoing_bitrate = estimate;
            }
        }
    }

    /// Sets the receive-side estimate the application's congestion control made for the
    /// incoming streams: the selected candidate pair's `availableIncomingBitrate`. Returns
    /// `false`, and sets nothing, while no pair is selected.
    pub(crate) fn on_available_incoming_bitrate(&mut self, bits_per_second: f64) -> bool {
        match self
            .ice_candidate_pairs
            .get_mut(&self.transport.selected_candidate_pair_id)
        {
            Some(pair) => {
                pair.available_incoming_bitrate = bits_per_second;
                true
            }
            None => false,
        }
    }

    /// The transport selected the candidate pair `pair_id` (`None`: it has none any more).
    ///
    /// The pair it leaves no longer carries the streams the bitrate estimates were made for
    /// (webrtc-stats: `availableOutgoingBitrate` / `availableIncomingBitrate` are those of a
    /// pair in use), so it gives them up.
    pub(crate) fn on_selected_candidate_pair(&mut self, pair_id: Option<String>) {
        let previous = self.transport.selected_candidate_pair_id.clone();
        if pair_id.as_deref() == Some(previous.as_str()) {
            return;
        }
        if let Some(pair) = self.ice_candidate_pairs.get_mut(&previous) {
            pair.available_outgoing_bitrate = 0.0;
            pair.available_incoming_bitrate = 0.0;
        }
        match pair_id {
            Some(pair_id) => {
                // The pair now in use carries the transport's estimate.
                if let Some(estimate) = self.outgoing_estimates.get(&self.active_transport())
                    && let Some(pair) = self.ice_candidate_pairs.get_mut(&pair_id)
                {
                    pair.available_outgoing_bitrate = *estimate;
                }
                self.transport.on_selected_candidate_pair_changed(pair_id)
            }
            None => self.transport.on_selected_candidate_pair_lost(),
        }
    }

    // ========================================================================
    // Codec stats methods
    // ========================================================================

    /// Registers the codec `payload_type` means in `direction` on the transport, and returns
    /// the id of its stats object.
    ///
    /// A payload type has one codec object on a transport (webrtc-stats 8.3), which both
    /// directions share. Only when the two directions give it different parameters (another
    /// `sdpFmtpLine`) does the second one registered get an object of its own.
    fn register_codec(
        &mut self,
        direction: CodecDirection,
        codec: &RTCRtpCodec,
        payload_type: PayloadType,
        transport_id: String,
    ) -> String {
        let accumulator = CodecStatsAccumulator {
            transport_id: transport_id.clone(),
            ..CodecStatsAccumulator::from_codec(codec, payload_type)
        };
        let directional_id =
            CodecStatsAccumulator::generate_id(&transport_id, direction, payload_type);
        if self.codecs.contains_key(&directional_id) {
            return directional_id;
        }
        let shared_id = CodecStatsAccumulator::shared_id(&transport_id, payload_type);
        match self.codecs.get(&shared_id) {
            Some(shared) if !shared.same_codec(&accumulator) => {
                self.codecs.insert(directional_id.clone(), accumulator);
                directional_id
            }
            Some(_) => shared_id,
            None => {
                self.codecs.insert(shared_id.clone(), accumulator);
                shared_id
            }
        }
    }

    /// Registers a codec for an inbound RTP stream and sets the codec_id.
    ///
    /// Per W3C spec, codecs are only exposed when referenced by an RTP stream.
    /// This method registers the codec (if not already registered) and links it
    /// to the inbound RTP stream.
    pub(crate) fn register_inbound_codec(
        &mut self,
        ssrc: SSRC,
        codec: &RTCRtpCodec,
        payload_type: PayloadType,
    ) {
        let Some(transport_id) = self
            .inbound_rtp_streams
            .get(&ssrc)
            .map(|s| s.transport_id.clone())
        else {
            return;
        };
        let codec_id =
            self.register_codec(CodecDirection::Receive, codec, payload_type, transport_id);
        // Link the codec to the inbound RTP stream; its clock rate is what the RTCP jitter is
        // counted in
        if let Some(stream) = self.inbound_rtp_streams.get_mut(&ssrc) {
            stream.codec_id = codec_id;
            stream.clock_rate = codec.clock_rate;
        }
    }

    /// Registers a codec for an outbound RTP stream and sets the codec_id.
    ///
    /// Per W3C spec, codecs are only exposed when referenced by an RTP stream.
    /// This method registers the codec (if not already registered) and links it
    /// to the outbound RTP stream.
    pub(crate) fn register_outbound_codec(
        &mut self,
        ssrc: SSRC,
        codec: &RTCRtpCodec,
        payload_type: PayloadType,
    ) {
        let Some(transport_id) = self
            .outbound_rtp_streams
            .get(&ssrc)
            .map(|s| s.transport_id.clone())
        else {
            return;
        };
        let codec_id = self.register_codec(CodecDirection::Send, codec, payload_type, transport_id);
        // Link the codec to the outbound RTP stream; its clock rate is what the RTCP jitter is
        // counted in
        if let Some(stream) = self.outbound_rtp_streams.get_mut(&ssrc) {
            stream.codec_id = codec_id;
            stream.clock_rate = codec.clock_rate;
        }
    }

    /// A transceiver was removed from the peer connection's set of transceivers: the streams
    /// and media sources of the transceivers after it follow their ids down by one. The
    /// removed transceiver's own (stopped) streams keep their stats in the full report but
    /// no longer answer to a sender or receiver selector, which names a live transceiver.
    pub(crate) fn transceiver_removed(&mut self, removed: RTCRtpTransceiverId) {
        let remap = |id: &mut RTCRtpTransceiverId| {
            if *id == removed {
                *id = RTCRtpTransceiverId::MAX;
            } else if *id > removed && *id != RTCRtpTransceiverId::MAX {
                *id -= 1;
            }
        };
        for stream in self.inbound_rtp_streams.values_mut() {
            remap(&mut stream.transceiver_id);
        }
        for stream in self.outbound_rtp_streams.values_mut() {
            remap(&mut stream.transceiver_id);
        }
        for source in self.media_sources.values_mut() {
            if let Some(id) = source.transceiver_id.as_mut() {
                remap(id);
            }
        }
    }

    /// A sender's stream moved from SSRC `old` to `new` after a collision (RFC 3550 section
    /// 8.2): the old stream's stats go, and a new stream with the same identity (kind, mid,
    /// rid, encoding, RTX SSRC, transceiver) starts under `new`. Nothing when `old` has none.
    pub(crate) fn replace_outbound_rtp_stream(&mut self, old: SSRC, new: SSRC) {
        let Some(stream) = self.outbound_rtp_streams.get(&old) else {
            return;
        };
        let (kind, mid, rid, encoding_index, rtx_ssrc, transceiver_id) = (
            stream.kind,
            stream.mid.clone(),
            stream.rid.clone(),
            stream.encoding_index,
            stream.rtx_ssrc,
            stream.transceiver_id,
        );
        self.remove_outbound_rtp_stream(old);
        self.get_or_create_outbound_rtp_streams(
            new,
            kind,
            &mid,
            &rid,
            encoding_index,
            rtx_ssrc,
            transceiver_id,
        );
    }

    /// Removes an outbound stream's stats, its remote-inbound object with them, and its RTX
    /// reverse-lookup entry.
    pub(crate) fn remove_outbound_rtp_stream(&mut self, ssrc: SSRC) {
        if let Some(stream) = self.outbound_rtp_streams.remove(&ssrc) {
            self.streams_retired += 1;
            dissociate(
                &mut self.outbound_rtx_ssrc_to_primary,
                stream.rtx_ssrc,
                ssrc,
            );
        }
    }

    /// Drops the stats of every RTP stream whose SSRC is no longer bound: inbound streams not
    /// in `inbound_live`, outbound streams not in `outbound_live`.
    ///
    /// webrtc-stats ties an RTP stream's stats objects to the SSRC being in use; without this
    /// the per-SSRC maps only ever grew, one entry for every SSRC a peer ever had bound.
    pub(crate) fn retire_rtp_streams(
        &mut self,
        inbound_live: &std::collections::HashSet<SSRC>,
        outbound_live: &std::collections::HashSet<SSRC>,
    ) {
        let retired_inbound: Vec<SSRC> = self
            .inbound_rtp_streams
            .keys()
            .filter(|ssrc| !inbound_live.contains(ssrc))
            .copied()
            .collect();
        for ssrc in retired_inbound {
            self.remove_inbound_rtp_stream(ssrc);
        }
        let retired_outbound: Vec<SSRC> = self
            .outbound_rtp_streams
            .keys()
            .filter(|ssrc| !outbound_live.contains(ssrc))
            .copied()
            .collect();
        for ssrc in retired_outbound {
            self.remove_outbound_rtp_stream(ssrc);
        }
        // And any entry left naming a stream that is not there (an RTX SSRC announced for a
        // stream that never got stats, or one that has gone).
        let inbound = &self.inbound_rtp_streams;
        self.inbound_rtx_ssrc_to_primary
            .retain(|_, primary| inbound.contains_key(primary));
        self.fec_ssrc_to_primary
            .retain(|_, primary| inbound.contains_key(primary));
        let outbound = &self.outbound_rtp_streams;
        self.outbound_rtx_ssrc_to_primary
            .retain(|_, primary| outbound.contains_key(primary));
    }

    /// Removes codecs that are no longer referenced by any RTP stream.
    ///
    /// Per W3C spec, when there is no longer any reference to an RTCCodecStats,
    /// the stats object should be deleted.
    pub(crate) fn cleanup_unreferenced_codecs(&mut self) {
        // Collect all referenced codec IDs
        let mut referenced: std::collections::HashSet<String> = std::collections::HashSet::new();

        for stream in self.inbound_rtp_streams.values() {
            if !stream.codec_id.is_empty() {
                referenced.insert(stream.codec_id.clone());
            }
        }

        for stream in self.outbound_rtp_streams.values() {
            if !stream.codec_id.is_empty() {
                referenced.insert(stream.codec_id.clone());
            }
        }

        // Remove codecs that are not referenced
        self.codecs.retain(|id, _| referenced.contains(id));
    }
}

/// Maps `repair_ssrc` to `primary`, dropping the entry of `previous`, the repair SSRC
/// `primary` had before: a stream has one RTX (or FEC) SSRC at a time, so the map holds no more
/// entries than there are streams.
fn associate(
    map: &mut HashMap<SSRC, SSRC>,
    previous: Option<SSRC>,
    repair_ssrc: SSRC,
    primary: SSRC,
) {
    if let Some(previous) = previous
        && previous != repair_ssrc
    {
        dissociate(map, Some(previous), primary);
    }
    map.insert(repair_ssrc, primary);
}

/// Drops `repair_ssrc`'s entry if it still names `primary`.
fn dissociate(map: &mut HashMap<SSRC, SSRC>, repair_ssrc: Option<SSRC>, primary: SSRC) {
    if let Some(repair_ssrc) = repair_ssrc
        && map.get(&repair_ssrc) == Some(&primary)
    {
        map.remove(&repair_ssrc);
    }
}

/// The two bytes an RTX packet's payload starts with: the original sequence number (RFC 4588
/// section 4).
const RTX_OSN_BYTES: usize = 2;

/// The stats id of the candidate-pair object for the ICE agent's candidates `local_id` and
/// `remote_id`.
pub(crate) fn candidate_pair_stats_id(local_id: &str, remote_id: &str) -> String {
    format!("RTCIceCandidatePair_{local_id}_{remote_id}")
}

/// The stats id of the local-candidate object for the ICE agent's candidate `id`.
pub(crate) fn local_candidate_stats_id(id: &str) -> String {
    format!("RTCLocalIceCandidate_{id}")
}

/// The stats id of the remote-candidate object for the ICE agent's candidate `id`.
pub(crate) fn remote_candidate_stats_id(id: &str) -> String {
    format!("RTCRemoteIceCandidate_{id}")
}