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