moq_ext_player/stats.rs
1//! Snapshots of what a player is doing.
2//!
3//! [`PlaybackStats`] is a plain value. A UI can read it with
4//! `Player::stats()` as often as it draws. Every figure has exactly one
5//! writer: the video task writes the video figures, and the audio task writes
6//! the audio figures.
7//!
8//! Rates are counted over a window instead of derived from the gap between two
9//! events. One late frame in a 30 fps stream reads as 50 by the gap and as 30
10//! by the count.
11
12use std::{
13 collections::VecDeque,
14 time::{Duration, Instant},
15};
16
17use moq_ext_sources::stats::SharedCell;
18
19use crate::NetworkSample;
20
21/// What a [`Player`](crate::Player) is playing.
22#[derive(Debug, Clone, Default, PartialEq)]
23pub struct PlaybackStats {
24 /// The video decoder, while video plays.
25 pub video: Option<VideoPlaybackStats>,
26 /// The audio decoder, while audio plays.
27 pub audio: Option<AudioPlaybackStats>,
28 /// How far behind the live edge playback runs.
29 ///
30 /// This is the playout clock's delay: the latency's minimum, raised by the
31 /// catalog `delay` and `jitter` and by the jitter the audio decoder measures.
32 pub latency: Duration,
33 /// A reading of the link, if the broadcast has network signals.
34 pub network: Option<NetworkSample>,
35}
36
37impl PlaybackStats {
38 /// Returns a one-line summary for a status bar or a log.
39 ///
40 /// It names the rendition on screen with its size and frame rate, then
41 /// the round trip and the playout latency. A figure not known yet shows
42 /// as `-`.
43 #[must_use]
44 pub fn summary(&self) -> String {
45 let video = match &self.video {
46 Some(video) => {
47 let size = video
48 .size
49 .map_or_else(|| "-".to_string(), |size| size.to_string());
50 let fps = video
51 .fps
52 .map_or_else(|| "-".to_string(), |fps| fps.to_string());
53 format!("{} {size} {fps}fps", video.rendition)
54 }
55 None => "no video".to_string(),
56 };
57 let rtt = self
58 .network
59 .and_then(|network| network.rtt)
60 .map_or_else(|| "-".to_string(), |rtt| rtt.as_millis().to_string());
61 format!("{video} | rtt:{rtt}ms lat:{}ms", self.latency.as_millis())
62 }
63}
64
65/// The video decoder.
66///
67/// The running decoder backend is in [`PlayerStatus::decoder`](crate::PlayerStatus::decoder).
68#[derive(Debug, Clone, Default, PartialEq, Eq)]
69pub struct VideoPlaybackStats {
70 /// The rendition on screen.
71 pub rendition: String,
72 /// The decoded picture size.
73 pub size: Option<moq_video::Size>,
74 /// Frames shown per second, over the last second.
75 ///
76 /// `None` before the first second of pictures, and from at most two
77 /// seconds after the last picture shown.
78 pub fps: Option<u32>,
79 /// How long one transport read and decode take together, smoothed.
80 pub decode_time: Option<Duration>,
81 /// Frames shown since the player started.
82 pub frames: u64,
83 /// Access units the decoder refused and skipped.
84 pub skipped: u64,
85}
86
87/// The audio decoder.
88#[derive(Debug, Clone, Default, PartialEq)]
89pub struct AudioPlaybackStats {
90 /// The rendition playing.
91 pub rendition: String,
92 /// How much audio is queued ahead of the speaker.
93 pub buffered: Duration,
94 /// The most recent peak level on a linear `0.0..=1.0` scale, for a meter.
95 ///
96 /// With a speaker, this is the speaker stream's peak after the volume.
97 /// Without one, it is the peak of the audio [`rms`](Self::rms) spans.
98 /// It reads `0.0` once [`rms`](Self::rms) reads `None`.
99 pub peak: f32,
100 /// The RMS level of the last 100 ms of decoded audio, on a linear `0.0..=1.0` scale.
101 ///
102 /// Measured before the speaker's volume, with or without a speaker, so a
103 /// player in `AudioMode::Decode` can drive a level meter or a speaking
104 /// indicator. `None` before the first frame, and after 300 ms without one.
105 pub rms: Option<f32>,
106 /// Frames played since the player started.
107 pub frames: u64,
108}
109
110/// Which medium a [`FrameTiming`] describes.
111#[derive(Debug, Clone, Copy, PartialEq, Eq)]
112pub enum MediaKind {
113 /// A decoded picture.
114 Video,
115 /// A decoded block of samples.
116 Audio,
117}
118
119/// When one frame arrived, left its decoder, and was presented.
120///
121/// Read with [`Player::timeline`](crate::Player::timeline) for a timeline view
122/// of playback, [`Player::video_timing`](crate::Player::video_timing) for one
123/// picture, [`Player::take_latest_video`](crate::Player::take_latest_video)
124/// with the newest picture, or [`VideoBacklog::take`](crate::VideoBacklog::take)
125/// with every picture. From `arrived` to `decoded` is the time in the
126/// decoder, and from `decoded` to `presented` the time the playout clock held
127/// the frame. Pictures and audio with the same timestamp should be presented
128/// together.
129#[derive(Debug, Clone, Copy, PartialEq, Eq)]
130pub struct FrameTiming {
131 /// The medium.
132 pub kind: MediaKind,
133 /// The frame's presentation timestamp on the broadcast clock.
134 ///
135 /// This is the frame's `timestamp` as a [`Duration`], so timings sort and
136 /// subtract. [`Player::video_timing`](crate::Player::video_timing) takes
137 /// the frame's `timestamp` itself.
138 pub pts: Duration,
139 /// When the frame's data was complete on this node, before decoding.
140 ///
141 /// Set for pictures, from the decoder's
142 /// [`arrival`](moq_video::decode::Consumer::arrival). It is `None` for
143 /// audio, and for a picture the decoder could not match to one access
144 /// unit.
145 pub arrived: Option<Instant>,
146 /// When the decoder handed the frame over.
147 pub decoded: Instant,
148 /// When the frame was presented.
149 ///
150 /// A picture is presented when it is handed to the player's frames. Audio
151 /// is presented when it reaches the speaker: when it was written plus the
152 /// audio already queued ahead of it.
153 pub presented: Instant,
154}
155
156impl FrameTiming {
157 /// Returns how long the frame spent in the decoder, from `arrived` to `decoded`.
158 ///
159 /// `None` when the arrival is not known.
160 #[must_use]
161 pub fn decode_time(&self) -> Option<Duration> {
162 self.arrived
163 .map(|arrived| self.decoded.saturating_duration_since(arrived))
164 }
165
166 /// Returns how long the playout clock held the frame, from `decoded` to `presented`.
167 #[must_use]
168 pub fn queued(&self) -> Duration {
169 self.presented.saturating_duration_since(self.decoded)
170 }
171}
172
173/// How many frames a [`FrameLog`] keeps per medium.
174///
175/// That is ten seconds of 50 Hz audio, and more of 30 fps video.
176const TIMELINE_LEN: usize = 512;
177
178/// The last frames of one medium, oldest first, written by the presenting task.
179#[derive(Debug, Clone, Default)]
180pub(crate) struct FrameLog(SharedCell<VecDeque<FrameTiming>>);
181
182impl FrameLog {
183 /// Records one frame, dropping the oldest once full.
184 pub(crate) fn push(&self, timing: FrameTiming) {
185 self.0.update(|frames| {
186 if frames.len() >= TIMELINE_LEN {
187 frames.pop_front();
188 }
189 frames.push_back(timing);
190 });
191 }
192
193 /// Returns a copy of every frame kept, oldest first.
194 pub(crate) fn snapshot(&self) -> VecDeque<FrameTiming> {
195 self.0.get()
196 }
197
198 /// Returns when the newest frame kept left its decoder.
199 pub(crate) fn last_decoded(&self) -> Option<Instant> {
200 let mut decoded = None;
201 self.0
202 .update(|frames| decoded = frames.back().map(|timing| timing.decoded));
203 decoded
204 }
205
206 /// Returns the newest frame kept at `pts`, without copying the log.
207 pub(crate) fn find(&self, pts: Duration) -> Option<FrameTiming> {
208 let mut found = None;
209 self.0.update(|frames| {
210 found = frames
211 .iter()
212 .rev()
213 .find(|timing| timing.pts == pts)
214 .copied();
215 });
216 found
217 }
218}
219
220#[cfg(test)]
221mod tests {
222 use super::*;
223
224 /// The helpers split a frame's time into the decoder's part and the clock's part.
225 #[test]
226 fn a_timing_splits_into_decode_time_and_queued() {
227 let arrived = Instant::now();
228 let mut timing = FrameTiming {
229 kind: MediaKind::Video,
230 pts: Duration::ZERO,
231 arrived: Some(arrived),
232 decoded: arrived + Duration::from_millis(5),
233 presented: arrived + Duration::from_millis(45),
234 };
235 assert_eq!(timing.decode_time(), Some(Duration::from_millis(5)));
236 assert_eq!(timing.queued(), Duration::from_millis(40));
237 timing.arrived = None;
238 assert_eq!(timing.decode_time(), None);
239 }
240
241 /// The summary names what it knows and marks the rest.
242 #[test]
243 fn the_summary_marks_figures_not_known_yet() {
244 let mut stats = PlaybackStats {
245 latency: Duration::from_millis(150),
246 ..Default::default()
247 };
248 assert_eq!(stats.summary(), "no video | rtt:-ms lat:150ms");
249 stats.video = Some(VideoPlaybackStats {
250 rendition: "high".to_string(),
251 size: Some(moq_video::Size::new(1280, 720)),
252 fps: Some(30),
253 ..Default::default()
254 });
255 assert_eq!(stats.summary(), "high 1280x720 30fps | rtt:-ms lat:150ms");
256 }
257}