Skip to main content

rtc/statistics/
report.rs

1//! WebRTC Statistics Report types.
2//!
3//! This module provides the `RTCStatsReport` type which is the return value
4//! of `getStats()` and contains a collection of statistics objects.
5
6use crate::statistics::stats::RTCStatsType;
7use crate::statistics::stats::certificate::RTCCertificateStats;
8use crate::statistics::stats::codec::RTCCodecStats;
9use crate::statistics::stats::data_channel::RTCDataChannelStats;
10use crate::statistics::stats::ice_candidate::RTCIceCandidateStats;
11use crate::statistics::stats::ice_candidate_pair::RTCIceCandidatePairStats;
12use crate::statistics::stats::media::audio_playout::RTCAudioPlayoutStats;
13use crate::statistics::stats::media::audio_source::RTCAudioSourceStats;
14use crate::statistics::stats::media::video_source::RTCVideoSourceStats;
15use crate::statistics::stats::peer_connection::RTCPeerConnectionStats;
16use crate::statistics::stats::rtp_stream::received::inbound::RTCInboundRtpStreamStats;
17use crate::statistics::stats::rtp_stream::received::remote_inbound::RTCRemoteInboundRtpStreamStats;
18use crate::statistics::stats::rtp_stream::sent::outbound::RTCOutboundRtpStreamStats;
19use crate::statistics::stats::rtp_stream::sent::remote_outbound::RTCRemoteOutboundRtpStreamStats;
20use crate::statistics::stats::transport::RTCTransportStats;
21use std::collections::HashMap;
22
23/// An entry in the stats report representing a single statistics object.
24///
25/// Each variant corresponds to a different W3C WebRTC stats dictionary type.
26#[derive(Debug)]
27pub enum RTCStatsReportEntry {
28    /// Peer connection level statistics.
29    PeerConnection(RTCPeerConnectionStats),
30    /// Transport statistics.
31    Transport(RTCTransportStats),
32    /// ICE candidate pair statistics.
33    IceCandidatePair(RTCIceCandidatePairStats),
34    /// Local ICE candidate statistics.
35    LocalCandidate(RTCIceCandidateStats),
36    /// Remote ICE candidate statistics.
37    RemoteCandidate(RTCIceCandidateStats),
38    /// Certificate statistics.
39    Certificate(RTCCertificateStats),
40    /// Codec statistics.
41    Codec(RTCCodecStats),
42    /// Data channel statistics.
43    DataChannel(RTCDataChannelStats),
44    /// Inbound RTP stream statistics.
45    InboundRtp(RTCInboundRtpStreamStats),
46    /// Outbound RTP stream statistics.
47    OutboundRtp(RTCOutboundRtpStreamStats),
48    /// Remote inbound RTP stream statistics (from RTCP RR).
49    RemoteInboundRtp(RTCRemoteInboundRtpStreamStats),
50    /// Remote outbound RTP stream statistics (from RTCP SR).
51    RemoteOutboundRtp(RTCRemoteOutboundRtpStreamStats),
52    /// Audio source statistics.
53    AudioSource(RTCAudioSourceStats),
54    /// Video source statistics.
55    VideoSource(RTCVideoSourceStats),
56    /// Audio playout statistics.
57    AudioPlayout(RTCAudioPlayoutStats),
58}
59
60impl RTCStatsReportEntry {
61    /// Returns the stats type for this entry.
62    pub fn stats_type(&self) -> RTCStatsType {
63        match self {
64            RTCStatsReportEntry::PeerConnection(_) => RTCStatsType::PeerConnection,
65            RTCStatsReportEntry::Transport(_) => RTCStatsType::Transport,
66            RTCStatsReportEntry::IceCandidatePair(_) => RTCStatsType::CandidatePair,
67            RTCStatsReportEntry::LocalCandidate(_) => RTCStatsType::LocalCandidate,
68            RTCStatsReportEntry::RemoteCandidate(_) => RTCStatsType::RemoteCandidate,
69            RTCStatsReportEntry::Certificate(_) => RTCStatsType::Certificate,
70            RTCStatsReportEntry::Codec(_) => RTCStatsType::Codec,
71            RTCStatsReportEntry::DataChannel(_) => RTCStatsType::DataChannel,
72            RTCStatsReportEntry::InboundRtp(_) => RTCStatsType::InboundRTP,
73            RTCStatsReportEntry::OutboundRtp(_) => RTCStatsType::OutboundRTP,
74            RTCStatsReportEntry::RemoteInboundRtp(_) => RTCStatsType::RemoteInboundRTP,
75            RTCStatsReportEntry::RemoteOutboundRtp(_) => RTCStatsType::RemoteOutboundRTP,
76            RTCStatsReportEntry::AudioSource(_) => RTCStatsType::MediaSource,
77            RTCStatsReportEntry::VideoSource(_) => RTCStatsType::MediaSource,
78            RTCStatsReportEntry::AudioPlayout(_) => RTCStatsType::MediaPlayout,
79        }
80    }
81
82    /// Returns the unique ID for this stats entry.
83    pub fn id(&self) -> &str {
84        match self {
85            RTCStatsReportEntry::PeerConnection(s) => &s.stats.id,
86            RTCStatsReportEntry::Transport(s) => &s.stats.id,
87            RTCStatsReportEntry::IceCandidatePair(s) => &s.stats.id,
88            RTCStatsReportEntry::LocalCandidate(s) => &s.stats.id,
89            RTCStatsReportEntry::RemoteCandidate(s) => &s.stats.id,
90            RTCStatsReportEntry::Certificate(s) => &s.stats.id,
91            RTCStatsReportEntry::Codec(s) => &s.stats.id,
92            RTCStatsReportEntry::DataChannel(s) => &s.stats.id,
93            RTCStatsReportEntry::InboundRtp(s) => {
94                &s.received_rtp_stream_stats.rtp_stream_stats.stats.id
95            }
96            RTCStatsReportEntry::OutboundRtp(s) => {
97                &s.sent_rtp_stream_stats.rtp_stream_stats.stats.id
98            }
99            RTCStatsReportEntry::RemoteInboundRtp(s) => {
100                &s.received_rtp_stream_stats.rtp_stream_stats.stats.id
101            }
102            RTCStatsReportEntry::RemoteOutboundRtp(s) => {
103                &s.sent_rtp_stream_stats.rtp_stream_stats.stats.id
104            }
105            RTCStatsReportEntry::AudioSource(s) => &s.media_source_stats.stats.id,
106            RTCStatsReportEntry::VideoSource(s) => &s.media_source_stats.stats.id,
107            RTCStatsReportEntry::AudioPlayout(s) => &s.stats.id,
108        }
109    }
110}
111
112/// A collection of statistics objects returned by `getStats()`.
113///
114/// This type implements the W3C RTCStatsReport interface, providing
115/// map-like access to statistics objects keyed by their unique IDs.
116///
117/// # Example
118///
119/// ```ignore
120/// use rtc::statistics::StatsSelector;
121///
122/// let report = peer_connection.get_stats(Instant::now(), StatsSelector::None);
123///
124/// // Iterate over all stats
125/// for entry in report.iter() {
126///     println!("{:?}: {:?}", entry.stats_type(), entry.id());
127/// }
128///
129/// // Get a specific stat by ID
130/// if let Some(entry) = report.get("RTCPeerConnection") {
131///     println!("Found peer connection stats");
132/// }
133///
134/// // Filter by type
135/// for inbound in report.iter_by_type(RTCStatsType::InboundRTP) {
136///     println!("Inbound RTP: {:?}", inbound.id());
137/// }
138/// ```
139#[derive(Debug, Default)]
140pub struct RTCStatsReport {
141    /// The stats entries indexed by their unique ID.
142    entries: HashMap<String, RTCStatsReportEntry>,
143    /// Ordered list of entry IDs for iteration.
144    order: Vec<String>,
145}
146
147impl RTCStatsReport {
148    /// Creates a new stats report from a list of entries.
149    pub(crate) fn new(entries: Vec<RTCStatsReportEntry>) -> Self {
150        let mut map = HashMap::new();
151        let mut order = Vec::with_capacity(entries.len());
152
153        for entry in entries {
154            let id = entry.id().to_string();
155            order.push(id.clone());
156            map.insert(id, entry);
157        }
158
159        Self {
160            entries: map,
161            order,
162        }
163    }
164
165    /// Returns the number of stats entries in the report.
166    pub fn len(&self) -> usize {
167        self.entries.len()
168    }
169
170    /// Returns true if the report contains no entries.
171    pub fn is_empty(&self) -> bool {
172        self.entries.is_empty()
173    }
174
175    /// Gets a stats entry by its unique ID.
176    pub fn get(&self, id: &str) -> Option<&RTCStatsReportEntry> {
177        self.entries.get(id)
178    }
179
180    /// Returns true if the report contains an entry with the given ID.
181    pub fn contains(&self, id: &str) -> bool {
182        self.entries.contains_key(id)
183    }
184
185    /// Returns an iterator over all stats entries.
186    pub fn iter(&self) -> impl Iterator<Item = &RTCStatsReportEntry> {
187        self.order.iter().filter_map(|id| self.entries.get(id))
188    }
189
190    /// Returns an iterator over stats entries of a specific type.
191    pub fn iter_by_type(&self, typ: RTCStatsType) -> impl Iterator<Item = &RTCStatsReportEntry> {
192        self.iter().filter(move |e| e.stats_type() == typ)
193    }
194
195    /// Returns an iterator over all entry IDs.
196    pub fn ids(&self) -> impl Iterator<Item = &str> {
197        self.order.iter().map(|s| s.as_str())
198    }
199
200    // ========================================================================
201    // Convenience accessors for specific stats types
202    // ========================================================================
203
204    /// Returns the peer connection stats if present.
205    pub fn peer_connection(&self) -> Option<&RTCPeerConnectionStats> {
206        self.get("RTCPeerConnection").and_then(|e| match e {
207            RTCStatsReportEntry::PeerConnection(s) => Some(s),
208            _ => None,
209        })
210    }
211
212    /// Returns the transport stats if present.
213    pub fn transport(&self) -> Option<&RTCTransportStats> {
214        // Try both "transport" and empty transport_id
215        self.entries.values().find_map(|e| match e {
216            RTCStatsReportEntry::Transport(s) => Some(s),
217            _ => None,
218        })
219    }
220
221    /// Returns an iterator over all inbound RTP stream stats.
222    pub fn inbound_rtp_streams(&self) -> impl Iterator<Item = &RTCInboundRtpStreamStats> {
223        self.iter().filter_map(|e| match e {
224            RTCStatsReportEntry::InboundRtp(s) => Some(s),
225            _ => None,
226        })
227    }
228
229    /// Returns an iterator over all outbound RTP stream stats.
230    pub fn outbound_rtp_streams(&self) -> impl Iterator<Item = &RTCOutboundRtpStreamStats> {
231        self.iter().filter_map(|e| match e {
232            RTCStatsReportEntry::OutboundRtp(s) => Some(s),
233            _ => None,
234        })
235    }
236
237    /// Returns an iterator over all data channel stats.
238    pub fn data_channels(&self) -> impl Iterator<Item = &RTCDataChannelStats> {
239        self.iter().filter_map(|e| match e {
240            RTCStatsReportEntry::DataChannel(s) => Some(s),
241            _ => None,
242        })
243    }
244
245    /// Returns an iterator over all ICE candidate pair stats.
246    pub fn candidate_pairs(&self) -> impl Iterator<Item = &RTCIceCandidatePairStats> {
247        self.iter().filter_map(|e| match e {
248            RTCStatsReportEntry::IceCandidatePair(s) => Some(s),
249            _ => None,
250        })
251    }
252}