Skip to main content

moq_ext_player/player/
backlog.rs

1//! A queue of every presented picture with its timing.
2
3use std::{
4    collections::VecDeque,
5    fmt,
6    sync::{Arc, Mutex, Weak},
7};
8
9use crate::stats::FrameTiming;
10
11/// The pictures one [`VideoBacklog`] holds until its next take, oldest first.
12struct Ring {
13    pictures: VecDeque<(Arc<moq_video::Frame>, FrameTiming)>,
14    capacity: usize,
15}
16
17impl Ring {
18    /// Keeps `picture`, dropping the oldest once full.
19    fn push(&mut self, picture: (Arc<moq_video::Frame>, FrameTiming)) {
20        if self.pictures.len() == self.capacity {
21            self.pictures.pop_front();
22        }
23        self.pictures.push_back(picture);
24    }
25}
26
27/// The live [`VideoBacklog`] handles of one player, which the video task writes as it presents.
28#[derive(Clone, Default)]
29pub(crate) struct VideoBacklogs(Arc<Mutex<Vec<Weak<Mutex<Ring>>>>>);
30
31impl fmt::Debug for VideoBacklogs {
32    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33        let handles = self.0.lock().expect("poisoned").len();
34        f.debug_struct("VideoBacklogs")
35            .field("handles", &handles)
36            .finish()
37    }
38}
39
40impl VideoBacklogs {
41    /// Returns a new handle that keeps up to `capacity` pictures, at least one.
42    pub(crate) fn open(&self, capacity: usize) -> VideoBacklog {
43        let capacity = capacity.max(1);
44        let ring = Arc::new(Mutex::new(Ring {
45            pictures: VecDeque::new(),
46            capacity,
47        }));
48        let mut backlogs = self.0.lock().expect("poisoned");
49        // `record` only prunes while pictures are presented.
50        backlogs.retain(|ring| ring.strong_count() > 0);
51        backlogs.push(Arc::downgrade(&ring));
52        VideoBacklog { ring }
53    }
54
55    /// Hands a presented picture to every live handle, and forgets the dropped ones.
56    pub(crate) fn record(&self, frame: &Arc<moq_video::Frame>, timing: FrameTiming) {
57        let mut backlogs = self.0.lock().expect("poisoned");
58        if backlogs.is_empty() {
59            return;
60        }
61        backlogs.retain(|ring| {
62            let Some(ring) = ring.upgrade() else {
63                return false;
64            };
65            ring.lock().expect("poisoned").push((frame.clone(), timing));
66            true
67        });
68    }
69}
70
71/// A queue of the pictures a [`Player`](crate::Player) presents, with their timing.
72///
73/// Returned by [`Player::video_backlog`](crate::Player::video_backlog). Unlike
74/// [`VideoFrames`](crate::VideoFrames), it does not coalesce: each picture is
75/// queued until [`take`](Self::take) hands it out, up to the capacity. Each
76/// handle records from its creation on, and dropping it stops the recording.
77///
78/// The backlog does not signal the end of playback, where [`take`](Self::take)
79/// returns an empty list as during a stall. Watch
80/// [`Player::status`](crate::Player::status) for it.
81pub struct VideoBacklog {
82    ring: Arc<Mutex<Ring>>,
83}
84
85impl fmt::Debug for VideoBacklog {
86    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87        let ring = self.ring.lock().expect("poisoned");
88        f.debug_struct("VideoBacklog")
89            .field("held", &ring.pictures.len())
90            .field("capacity", &ring.capacity)
91            .finish()
92    }
93}
94
95impl VideoBacklog {
96    /// Takes every picture presented since the last take, oldest first, with its timing.
97    ///
98    /// The backlog is empty afterwards.
99    #[must_use]
100    pub fn take(&self) -> Vec<(Arc<moq_video::Frame>, FrameTiming)> {
101        // Moves the queue out so the copy happens outside the lock.
102        let pictures = std::mem::take(&mut self.ring.lock().expect("poisoned").pictures);
103        pictures.into()
104    }
105}
106
107#[cfg(test)]
108mod tests {
109    use std::time::{Duration, Instant};
110
111    use super::*;
112    use crate::stats::MediaKind;
113
114    /// Returns a picture stamped `ms`, with its timing.
115    fn picture(ms: u64) -> (Arc<moq_video::Frame>, FrameTiming) {
116        let timestamp = moq_net::Timestamp::from_micros(ms * 1000).expect("a valid timestamp");
117        let i420 =
118            moq_video::I420::new(moq_video::Size::new(2, 2), vec![0; 6]).expect("a 2x2 I420");
119        let frame = Arc::new(moq_video::Frame::new(
120            timestamp,
121            moq_video::Surface::I420(i420),
122        ));
123        let now = Instant::now();
124        let timing = FrameTiming {
125            kind: MediaKind::Video,
126            pts: Duration::from_millis(ms),
127            arrived: None,
128            decoded: now,
129            presented: now,
130        };
131        (frame, timing)
132    }
133
134    /// Returns the timestamps of `pictures` in ms.
135    fn stamps(pictures: &[(Arc<moq_video::Frame>, FrameTiming)]) -> Vec<u128> {
136        pictures
137            .iter()
138            .map(|(_, timing)| timing.pts.as_millis())
139            .collect()
140    }
141
142    fn record(backlogs: &VideoBacklogs, ms: u64) {
143        let (frame, timing) = picture(ms);
144        backlogs.record(&frame, timing);
145    }
146
147    #[test]
148    fn every_picture_between_two_takes_comes_out_once_in_order() {
149        let backlogs = VideoBacklogs::default();
150        let backlog = backlogs.open(8);
151        assert!(backlog.take().is_empty(), "nothing presented yet");
152        for ms in [0, 33, 66] {
153            record(&backlogs, ms);
154        }
155        assert_eq!(stamps(&backlog.take()), [0, 33, 66]);
156        assert!(backlog.take().is_empty(), "nothing new");
157        record(&backlogs, 100);
158        assert_eq!(stamps(&backlog.take()), [100]);
159    }
160
161    #[test]
162    fn a_full_backlog_drops_the_oldest() {
163        let backlogs = VideoBacklogs::default();
164        let backlog = backlogs.open(2);
165        for ms in [0, 33, 66] {
166            record(&backlogs, ms);
167        }
168        assert_eq!(stamps(&backlog.take()), [33, 66]);
169        let one = backlogs.open(0);
170        record(&backlogs, 100);
171        record(&backlogs, 133);
172        assert_eq!(stamps(&one.take()), [133], "a capacity of 0 keeps one");
173    }
174
175    #[test]
176    fn each_handle_keeps_its_own_pictures_from_its_creation_on() {
177        let backlogs = VideoBacklogs::default();
178        let first = backlogs.open(8);
179        record(&backlogs, 0);
180        let second = backlogs.open(8);
181        record(&backlogs, 33);
182        assert_eq!(stamps(&first.take()), [0, 33]);
183        assert_eq!(stamps(&second.take()), [33]);
184        drop(first);
185        record(&backlogs, 66);
186        assert_eq!(backlogs.0.lock().expect("poisoned").len(), 1);
187        assert_eq!(stamps(&second.take()), [66]);
188    }
189
190    #[test]
191    fn dropped_handles_are_forgotten_without_presented_pictures() {
192        let backlogs = VideoBacklogs::default();
193        let kept = backlogs.open(8);
194        for _ in 0..10 {
195            drop(backlogs.open(8));
196        }
197        // The kept handle and the last one dropped, which the next open forgets.
198        assert_eq!(backlogs.0.lock().expect("poisoned").len(), 2);
199        drop(kept);
200    }
201}