Skip to main content

moq_ext_publisher/
stats.rs

1//! Snapshots of what a broadcast is sending.
2//!
3//! [`PublishStats`] is a plain value. A UI can read it with
4//! [`LocalBroadcast::stats`](crate::LocalBroadcast::stats) as often as it
5//! draws. Every figure has exactly one writer. Each rendition's encoder writes
6//! its own entry, and the task that reads the source writes the source frame
7//! rate. What each track has sent is the catalog's own count
8//! ([`hang::stats::Rendition`]), read when the snapshot is taken.
9
10use std::{collections::BTreeMap, time::Duration};
11
12use moq_ext_sources::stats::{Rates, SharedCell};
13use moq_net::bandwidth::Rate;
14
15/// What a [`LocalBroadcast`](crate::LocalBroadcast) is sending.
16#[derive(Debug, Clone, Default, PartialEq)]
17pub struct PublishStats {
18    /// Frames per second arriving from the video source, shared by every rendition.
19    ///
20    /// `None` before the first second of frames, once the source ends, and
21    /// from at most two seconds after the last frame.
22    pub source_fps: Option<f32>,
23    /// Each video rendition's encoder, by rendition name.
24    pub renditions: BTreeMap<String, EncodeStats>,
25    /// What each track has sent, by track name, as the catalog counts it.
26    ///
27    /// A rendition's [`EncodeStats::track`] names its entry.
28    pub sent: BTreeMap<String, hang::stats::Rendition>,
29    /// The audio publication, if there is one.
30    pub audio: Option<AudioEncodeStats>,
31}
32
33/// One video rendition's encoder.
34///
35/// The running encoder backend is in the rendition's
36/// [`RenditionState`](crate::RenditionState).
37#[derive(Debug, Clone, Default, PartialEq)]
38pub struct EncodeStats {
39    /// The encoded picture size.
40    pub size: Option<moq_video::Size>,
41    /// Frames encoded per second, over the last second.
42    ///
43    /// `None` before the first second of frames, once the encoder stops, and
44    /// from at most two seconds after the last frame.
45    pub fps: Option<f32>,
46    /// Bits published per second, over the last second.
47    ///
48    /// `None` whenever [`fps`](Self::fps) is.
49    pub bitrate: Option<Rate>,
50    /// How long one encode takes, smoothed.
51    pub encode_time: Option<Duration>,
52    /// The size of the last keyframe in bytes.
53    pub keyframe_bytes: Option<u64>,
54    /// The size of a delta frame in bytes, smoothed.
55    ///
56    /// `None` while every frame is a keyframe.
57    pub delta_bytes: Option<u64>,
58    /// The time between the last two keyframes, by their timestamps.
59    ///
60    /// It shows the keyframe interval the encoder keeps, which a cut for a
61    /// new source or a slower frame rate can move away from the configured
62    /// one.
63    pub keyframe_interval: Option<Duration>,
64    /// The track the rendition writes now, its key in [`PublishStats::sent`].
65    ///
66    /// A keyframe with another decoder identity, such as a new level after a
67    /// switch to a larger source, moves the rendition to a newly named track.
68    pub track: String,
69}
70
71/// One rendition's figures as its encoder writes them.
72///
73/// The rates are kept apart, so a snapshot can drop them once they are stale.
74#[derive(Debug, Clone, Default)]
75pub(crate) struct RenditionEntry {
76    /// Every figure but the rates.
77    pub(crate) stats: EncodeStats,
78    /// The last rates of the meter that counts frames and their bytes.
79    rates: Option<Rates>,
80}
81
82impl RenditionEntry {
83    /// Stores the rates of a meter that counts frames and their bytes, if it reported.
84    pub(crate) fn record(&mut self, rates: Option<Rates>) {
85        if rates.is_some() {
86            self.rates = rates;
87        }
88    }
89
90    /// Forgets the rates of a stopped encoder.
91    pub(crate) fn stopped(&mut self) {
92        self.rates = None;
93    }
94
95    /// Returns the figures, with rates only while they are current.
96    fn snapshot(&self) -> EncodeStats {
97        let rates = self.rates.filter(Rates::is_current);
98        EncodeStats {
99            fps: rates.map(|rates| rates.events as f32),
100            bitrate: rates.map(|rates| Rate::from_bps((rates.amount * 8.0) as u64)),
101            ..self.stats.clone()
102        }
103    }
104}
105
106/// The tracker of one rendition's encoded frame sizes and keyframe spacing.
107///
108/// It fills the frame figures of the rendition's [`EncodeStats`].
109#[derive(Debug, Default)]
110pub(crate) struct FrameSizes {
111    /// The timestamp of the last keyframe.
112    last_keyframe: Option<moq_net::Timestamp>,
113    /// The smoothed delta frame size in bytes.
114    delta: Option<f64>,
115}
116
117impl FrameSizes {
118    /// The weight of a new delta frame in the smoothed size.
119    const ALPHA: f64 = 0.2;
120
121    /// Records an encoded frame of `bytes` at `timestamp` in `stats`.
122    pub(crate) fn record(
123        &mut self,
124        stats: &mut EncodeStats,
125        bytes: usize,
126        keyframe: bool,
127        timestamp: moq_net::Timestamp,
128    ) {
129        let bytes = bytes as u64;
130        if keyframe {
131            stats.keyframe_bytes = Some(bytes);
132            if let Some(last) = self.last_keyframe.replace(timestamp) {
133                let micros =
134                    crate::publish::micros(timestamp).saturating_sub(crate::publish::micros(last));
135                stats.keyframe_interval = Some(Duration::from_micros(micros as u64));
136            }
137        } else {
138            let delta = match self.delta {
139                Some(delta) => Self::ALPHA * bytes as f64 + (1.0 - Self::ALPHA) * delta,
140                None => bytes as f64,
141            };
142            self.delta = Some(delta);
143            stats.delta_bytes = Some(delta.round() as u64);
144        }
145    }
146}
147
148/// The audio publication.
149#[derive(Debug, Clone, Default, PartialEq)]
150pub struct AudioEncodeStats {
151    /// The codec, such as `opus`.
152    pub codec: Option<String>,
153    /// PCM frames written to the encoder.
154    pub frames: u64,
155    /// PCM frames lost because the broadcast fell behind its source.
156    pub dropped: u64,
157}
158
159/// The writers behind [`PublishStats`], one per figure.
160#[derive(Debug, Clone, Default)]
161pub(crate) struct PublishRecorder {
162    source_fps: SharedCell<Option<Rates>>,
163    renditions: SharedCell<BTreeMap<String, SharedCell<RenditionEntry>>>,
164    audio: SharedCell<Option<SharedCell<AudioEncodeStats>>>,
165}
166
167impl PublishRecorder {
168    /// Returns the snapshot, with `sent` from the catalog.
169    pub(crate) fn snapshot(&self, sent: BTreeMap<String, hang::stats::Rendition>) -> PublishStats {
170        PublishStats {
171            source_fps: self
172                .source_fps
173                .get()
174                .filter(Rates::is_current)
175                .map(|rates| rates.events as f32),
176            renditions: self
177                .renditions
178                .get()
179                .into_iter()
180                .map(|(name, writer)| (name, writer.get().snapshot()))
181                .collect(),
182            sent,
183            audio: self.audio.get().map(|cell| cell.get()),
184        }
185    }
186
187    /// Returns the writer of the source frame rate.
188    ///
189    /// A snapshot reads the rate as `None` once it is stale.
190    pub(crate) fn source_fps(&self) -> SharedCell<Option<Rates>> {
191        self.source_fps.clone()
192    }
193
194    /// Starts an entry for rendition `name` and returns its writer.
195    ///
196    /// The entry names the track `name` until the encoder reports another.
197    pub(crate) fn rendition(&self, name: &str) -> SharedCell<RenditionEntry> {
198        let writer = SharedCell::<RenditionEntry>::default();
199        writer.update(|entry| entry.stats.track = name.to_string());
200        self.renditions
201            .update(|renditions| drop(renditions.insert(name.to_string(), writer.clone())));
202        writer
203    }
204
205    /// Drops every video entry when the video slot is cleared.
206    pub(crate) fn clear_video(&self) {
207        self.renditions.update(BTreeMap::clear);
208        self.source_fps.update(|fps| *fps = None);
209    }
210
211    /// Starts the audio entry and returns its writer.
212    pub(crate) fn audio(&self) -> SharedCell<AudioEncodeStats> {
213        let cell = SharedCell::default();
214        self.audio.update(|audio| *audio = Some(cell.clone()));
215        cell
216    }
217
218    /// Drops the audio entry when the audio slot is cleared.
219    pub(crate) fn clear_audio(&self) {
220        self.audio.update(|audio| *audio = None);
221    }
222}
223
224#[cfg(test)]
225mod tests {
226    use moq_ext_sources::stats::RateMeter;
227
228    use super::*;
229
230    /// Each rendition names the track it writes, and a cleared video drops the entries.
231    #[test]
232    fn a_rendition_names_its_track() {
233        let recorder = PublishRecorder::default();
234        let high = recorder.rendition("high");
235        let _low = recorder.rendition("low");
236        let snapshot = recorder.snapshot(BTreeMap::new());
237        assert_eq!(snapshot.renditions["high"].track, "high");
238        assert_eq!(snapshot.renditions["low"].track, "low");
239        // A rendition moved to a new track names that track.
240        high.update(|entry| entry.stats.track = "high.1".to_string());
241        assert_eq!(
242            recorder.snapshot(BTreeMap::new()).renditions["high"].track,
243            "high.1"
244        );
245        recorder.clear_video();
246        assert!(recorder.snapshot(BTreeMap::new()).renditions.is_empty());
247    }
248
249    /// Counts `frames` at 20 per second, writing the rates as the encoder and the source reader do.
250    async fn run_at_20fps(
251        recorder: &PublishRecorder,
252        entry: &SharedCell<RenditionEntry>,
253        frames: u32,
254    ) {
255        let source_fps = recorder.source_fps();
256        let mut source = RateMeter::default();
257        let mut encoded = RateMeter::default();
258        for _ in 0..frames {
259            tokio::time::advance(Duration::from_millis(50)).await;
260            if let Some(rates) = source.tick(0) {
261                source_fps.update(|value| *value = Some(rates));
262            }
263            let rates = encoded.tick(1000);
264            entry.update(|entry| entry.record(rates));
265        }
266    }
267
268    /// The rates read right while frames arrive, and `None` once they stop or the source ends.
269    #[tokio::test(start_paused = true)]
270    async fn rates_go_away_once_frames_stop() {
271        let recorder = PublishRecorder::default();
272        let entry = recorder.rendition("high");
273        run_at_20fps(&recorder, &entry, 30).await;
274        let running = recorder.snapshot(BTreeMap::new());
275        let fps = running.source_fps.expect("a running source has a rate");
276        assert!((19.0..21.0).contains(&fps), "{fps}");
277        let rendition = &running.renditions["high"];
278        let fps = rendition.fps.expect("a running encoder has a rate");
279        assert!((19.0..21.0).contains(&fps), "{fps}");
280        let bitrate = rendition.bitrate.expect("a bitrate").as_bps();
281        assert!((152_000..168_000).contains(&bitrate), "{bitrate}");
282
283        // The source stalls.
284        tokio::time::advance(Duration::from_secs(2)).await;
285        let stalled = recorder.snapshot(BTreeMap::new());
286        assert_eq!(stalled.source_fps, None);
287        assert_eq!(stalled.renditions["high"].fps, None);
288        assert_eq!(stalled.renditions["high"].bitrate, None);
289
290        // It runs again, then ends.
291        run_at_20fps(&recorder, &entry, 30).await;
292        assert!(recorder.snapshot(BTreeMap::new()).source_fps.is_some());
293        recorder.source_fps().update(|value| *value = None);
294        entry.update(RenditionEntry::stopped);
295        let ended = recorder.snapshot(BTreeMap::new());
296        assert_eq!(ended.source_fps, None);
297        assert_eq!(ended.renditions["high"].fps, None);
298    }
299
300    /// Keyframes and delta frames are sized apart, and keyframes are spaced by their timestamps.
301    #[test]
302    fn frame_sizes_follow_keyframes_and_deltas() {
303        let at = |millis: u64| moq_net::Timestamp::from_micros(millis * 1000).expect("in range");
304        let mut sizes = FrameSizes::default();
305        let mut stats = EncodeStats::default();
306        sizes.record(&mut stats, 9000, true, at(0));
307        assert_eq!(stats.keyframe_bytes, Some(9000));
308        assert_eq!(stats.delta_bytes, None);
309        assert_eq!(
310            stats.keyframe_interval, None,
311            "one keyframe has no interval"
312        );
313        sizes.record(&mut stats, 1000, false, at(100));
314        sizes.record(&mut stats, 2000, false, at(200));
315        assert_eq!(
316            stats.delta_bytes,
317            Some(1200),
318            "smoothed: 0.2 * 2000 + 0.8 * 1000"
319        );
320        sizes.record(&mut stats, 8000, true, at(500));
321        assert_eq!(stats.keyframe_bytes, Some(8000));
322        assert_eq!(stats.keyframe_interval, Some(Duration::from_millis(500)));
323    }
324}