Skip to main content

moq_ext_sources/
frames.rs

1//! Latest-frame-wins video frames, with a cursor per handle.
2//!
3//! Players and sources both hand out this type, and every renderer reads it.
4//! It wraps a `tokio::sync::watch` channel. The producer overwrites one value,
5//! so a reader that falls behind skips to the newest picture instead of
6//! draining a backlog. Each frame keeps the instant it was sent, which a
7//! reader gets from [`VideoFrames::sent_at`].
8//!
9//! A frame also carries how many keyframes its producer had asked for when it
10//! was sent. The count only grows, so a request survives the frames a reader
11//! skips: the next frame the reader gets reports it through
12//! [`VideoFrames::keyframe_requested`].
13
14use std::{
15    sync::{
16        Arc, OnceLock,
17        atomic::{AtomicU64, Ordering},
18    },
19    time::Instant,
20};
21
22use tokio::sync::watch;
23
24use crate::{DemandGuard, Error, video};
25
26/// The value of a slot: the current frame, if any, and the keyframe requests made before it.
27#[derive(Clone, Default)]
28struct Sent {
29    /// The current frame and the instant it was sent.
30    frame: Option<(Arc<video::Frame>, Instant)>,
31    /// The keyframe requests made before the last frame sent, kept when the frame is cleared.
32    keyframes: u64,
33}
34
35/// The producing end of a frame stream.
36///
37/// Dropping the last clone ends the stream: every reader's
38/// [`next`](VideoFrames::next) returns the last frame, then `None`.
39#[derive(derive_more::Debug, Clone)]
40pub struct FrameSlot {
41    #[debug(skip)]
42    tx: watch::Sender<Sent>,
43    failure: Arc<OnceLock<Arc<Error>>>,
44    /// How many keyframes the producer asked for, stamped on each frame sent.
45    keyframes: Arc<AtomicU64>,
46}
47
48impl Default for FrameSlot {
49    fn default() -> Self {
50        Self::new()
51    }
52}
53
54impl FrameSlot {
55    /// Creates an empty slot.
56    #[must_use]
57    pub fn new() -> Self {
58        Self {
59            tx: watch::Sender::new(Sent::default()),
60            failure: Default::default(),
61            keyframes: Default::default(),
62        }
63    }
64
65    /// Replaces the current frame, waking every reader.
66    ///
67    /// Stamps the frame with the current instant, for [`VideoFrames::sent_at`].
68    pub fn send(&self, frame: Arc<video::Frame>) {
69        self.send_at(frame, Instant::now());
70    }
71
72    /// Replaces the current frame with one sent at `at`, for a stream that forwards another.
73    pub(crate) fn send_at(&self, frame: Arc<video::Frame>, at: Instant) {
74        let keyframes = self.keyframes.load(Ordering::Relaxed);
75        self.tx.send_replace(Sent {
76            frame: Some((frame, at)),
77            keyframes,
78        });
79    }
80
81    /// Asks for a keyframe at the next frame sent, which every reader reports once.
82    ///
83    /// See [`VideoFrames::keyframe_requested`].
84    pub(crate) fn request_keyframe(&self) {
85        self.keyframes.fetch_add(1, Ordering::Relaxed);
86    }
87
88    /// Drops the current frame, so no reader gets it from now on.
89    ///
90    /// A reader waiting in [`next`](VideoFrames::next) keeps waiting for the
91    /// next frame sent.
92    ///
93    /// Keeps the keyframe requests of the last frame, so a reader that opens
94    /// afterwards does not report a request made before that frame.
95    pub(crate) fn clear(&self) {
96        self.tx.send_modify(|sent| sent.frame = None);
97    }
98
99    /// Records why the stream is about to end, for [`FrameReader::failure`].
100    ///
101    /// The first failure wins.
102    pub(crate) fn fail(&self, failure: Arc<Error>) {
103        let _ = self.failure.set(failure);
104    }
105
106    /// Returns a reader starting at the current frame.
107    #[must_use]
108    pub fn frames(&self) -> VideoFrames {
109        VideoFrames::new(self.tx.subscribe())
110    }
111
112    /// Returns a handle that reads the slot without keeping it open.
113    pub(crate) fn reader(&self) -> FrameReader {
114        FrameReader {
115            rx: self.tx.subscribe(),
116            failure: self.failure.clone(),
117        }
118    }
119}
120
121/// A reader of a slot that does not hold it open.
122///
123/// A source keeps this, so its stream ends when the frames stop even while
124/// handles to the source remain.
125#[derive(derive_more::Debug, Clone)]
126pub(crate) struct FrameReader {
127    #[debug(skip)]
128    rx: watch::Receiver<Sent>,
129    failure: Arc<OnceLock<Arc<Error>>>,
130}
131
132impl FrameReader {
133    /// Returns a reader starting at the current frame.
134    pub(crate) fn frames(&self) -> VideoFrames {
135        VideoFrames::new(self.rx.clone())
136    }
137
138    /// Returns why the stream ended, if it failed.
139    pub(crate) fn failure(&self) -> Option<Arc<Error>> {
140        self.failure.get().cloned()
141    }
142}
143
144/// Latest-frame-wins video frames.
145///
146/// [`VideoSource::frames`](crate::VideoSource::frames) returns it for a local
147/// preview, and a player returns it for playback. Each clone keeps its own
148/// cursor. A frame comes as an `Arc` because upstream frames are not `Clone`:
149/// a GPU surface is shared, not copied.
150///
151/// On a fresh handle, the first [`next`](Self::next) returns at once if a
152/// picture is already there.
153///
154/// A handle from [`VideoSource::frames`](crate::VideoSource::frames) wants
155/// the source's frames until it and every clone of it are dropped.
156#[derive(derive_more::Debug, Clone)]
157pub struct VideoFrames {
158    #[debug(skip)]
159    rx: watch::Receiver<Sent>,
160    /// When the frame this handle last returned was sent.
161    sent_at: Option<Instant>,
162    /// The keyframe requests made before the frame this handle last returned.
163    keyframes: u64,
164    /// Whether that frame is the first this handle returned after a new request.
165    keyframe_requested: bool,
166    /// The demand this handle and its clones hold on their source, if any.
167    demand: Option<Arc<DemandGuard>>,
168}
169
170impl VideoFrames {
171    /// Creates a handle whose first [`next`](Self::next) returns the current frame.
172    ///
173    /// Requests made before the current frame was sent are not reported.
174    fn new(mut rx: watch::Receiver<Sent>) -> Self {
175        rx.mark_changed();
176        let keyframes = rx.borrow().keyframes;
177        Self {
178            rx,
179            sent_at: None,
180            keyframes,
181            keyframe_requested: false,
182            demand: None,
183        }
184    }
185
186    /// Records the instant and the keyframe requests of the frame this handle returns.
187    fn returned(&mut self, at: Instant, keyframes: u64) {
188        self.sent_at = Some(at);
189        self.keyframe_requested = keyframes > self.keyframes;
190        self.keyframes = self.keyframes.max(keyframes);
191    }
192
193    /// Holds `demand` for as long as this handle or a clone of it lives.
194    pub(crate) fn wanting(mut self, demand: DemandGuard) -> Self {
195        self.demand = Some(Arc::new(demand));
196        self
197    }
198
199    /// Returns the newest frame, seen or not, without moving the cursor.
200    ///
201    /// For render loops that redraw every vsync.
202    #[must_use]
203    pub fn current(&self) -> Option<Arc<video::Frame>> {
204        self.rx
205            .borrow()
206            .frame
207            .as_ref()
208            .map(|(frame, _)| frame.clone())
209    }
210
211    /// Waits for a frame newer than the last this handle returned.
212    ///
213    /// Frames that arrive faster than the handle reads them coalesce: only the
214    /// newest is returned. Returns `None` once the producer is gone and this
215    /// handle has seen its last frame.
216    ///
217    /// Cancellation safe.
218    pub async fn next(&mut self) -> Option<Arc<video::Frame>> {
219        loop {
220            self.rx.changed().await.ok()?;
221            let sent = self.rx.borrow_and_update().clone();
222            if let Some((frame, at)) = sent.frame {
223                self.returned(at, sent.keyframes);
224                return Some(frame);
225            }
226        }
227    }
228
229    /// Returns a newer frame without waiting, if there is one.
230    ///
231    /// For a render loop that draws only when the picture changed.
232    #[must_use]
233    pub fn try_next(&mut self) -> Option<Arc<video::Frame>> {
234        let sent = self.rx.borrow_and_update();
235        if !sent.has_changed() {
236            return None;
237        }
238        let (frame, at) = sent.frame.clone()?;
239        let keyframes = sent.keyframes;
240        drop(sent);
241        self.returned(at, keyframes);
242        Some(frame)
243    }
244
245    /// Returns when the last frame this handle returned entered the stream.
246    ///
247    /// That frame is the one [`next`](Self::next) or
248    /// [`try_next`](Self::try_next) returned last. For a source, that is when
249    /// the application pushed the frame or the capture thread handed it over,
250    /// before any encoder saw it. For a player, it is when the picture was
251    /// presented. Returns `None` before the first frame.
252    #[must_use]
253    pub fn sent_at(&self) -> Option<Instant> {
254        self.sent_at
255    }
256
257    /// Returns whether the producer asked for a keyframe at the last frame this handle returned.
258    ///
259    /// Meant for encoders. Returns true for the first frame the handle returned
260    /// after a call to
261    /// [`FrameSender::request_keyframe`](crate::FrameSender::request_keyframe),
262    /// even if the frame the request preceded was skipped. Each handle reports
263    /// a request once, independently of its clones and of other handles.
264    #[must_use]
265    pub fn keyframe_requested(&self) -> bool {
266        self.keyframe_requested
267    }
268
269    /// Waits until the producer is gone.
270    ///
271    /// Cancellation safe.
272    pub async fn closed(&self) {
273        let mut rx = self.rx.clone();
274        while rx.changed().await.is_ok() {}
275    }
276}
277
278#[cfg(test)]
279mod tests {
280    use std::time::Duration;
281
282    use super::*;
283    use crate::video::{Size, Surface};
284
285    fn frame(micros: u64) -> Arc<video::Frame> {
286        let size = Size::new(2, 2);
287        let surface = Surface::rgba(&[0u8; 16], size).expect("a 2x2 picture");
288        let timestamp = moq_net::Timestamp::from_micros(micros).expect("in range");
289        Arc::new(video::Frame::new(timestamp, surface))
290    }
291
292    fn micros(frame: &video::Frame) -> u64 {
293        frame.timestamp.as_micros().expect("a timed frame") as u64
294    }
295
296    #[tokio::test]
297    async fn every_handle_keeps_its_own_cursor() {
298        let slot = FrameSlot::new();
299        let mut first = slot.frames();
300        let mut second = slot.frames();
301        slot.send(frame(1));
302        assert_eq!(first.next().await.as_deref().map(micros), Some(1));
303        assert_eq!(second.next().await.as_deref().map(micros), Some(1));
304    }
305
306    #[tokio::test]
307    async fn frames_that_outrun_a_reader_coalesce() {
308        let slot = FrameSlot::new();
309        let mut frames = slot.frames();
310        slot.send(frame(1));
311        slot.send(frame(2));
312        slot.send(frame(3));
313        assert_eq!(frames.next().await.as_deref().map(micros), Some(3));
314        assert!(
315            tokio::time::timeout(Duration::from_millis(50), frames.next())
316                .await
317                .is_err(),
318            "three sends before one read are one frame",
319        );
320    }
321
322    #[test]
323    fn try_next_takes_only_what_is_new() {
324        let slot = FrameSlot::new();
325        let mut frames = slot.frames();
326        assert!(frames.try_next().is_none());
327        slot.send(frame(4));
328        assert_eq!(frames.current().as_deref().map(micros), Some(4));
329        assert_eq!(frames.try_next().as_deref().map(micros), Some(4));
330        assert!(frames.try_next().is_none(), "the same frame twice");
331    }
332
333    #[tokio::test]
334    async fn a_frame_keeps_the_instant_it_was_sent() {
335        let slot = FrameSlot::new();
336        let mut frames = slot.frames();
337        assert_eq!(frames.sent_at(), None);
338        let before = Instant::now();
339        slot.send(frame(1));
340        let after = Instant::now();
341        frames.next().await.expect("a frame");
342        let sent = frames.sent_at().expect("stamped");
343        assert!(before <= sent && sent <= after, "{sent:?}");
344        let earlier = before - Duration::from_millis(5);
345        slot.send_at(frame(2), earlier);
346        assert!(
347            frames.current().is_some(),
348            "current leaves the cursor alone"
349        );
350        assert_eq!(frames.sent_at(), Some(sent));
351        frames.try_next().expect("a newer frame");
352        assert_eq!(
353            frames.sent_at(),
354            Some(earlier),
355            "a forwarded frame keeps its instant"
356        );
357    }
358
359    #[tokio::test]
360    async fn a_fresh_handle_sees_the_current_frame() {
361        let slot = FrameSlot::new();
362        slot.send(frame(5));
363        let mut frames = slot.frames();
364        assert_eq!(frames.next().await.as_deref().map(micros), Some(5));
365    }
366
367    #[tokio::test]
368    async fn the_last_frame_is_read_before_the_close() {
369        let slot = FrameSlot::new();
370        let mut frames = slot.frames();
371        slot.send(frame(9));
372        drop(slot);
373        assert_eq!(frames.next().await.as_deref().map(micros), Some(9));
374        assert!(frames.next().await.is_none());
375    }
376
377    /// A request reaches every handle once, on the first frame each reads after it.
378    #[tokio::test]
379    async fn every_handle_reports_a_keyframe_request_once() {
380        let slot = FrameSlot::new();
381        let mut first = slot.frames();
382        let mut second = slot.frames();
383        slot.send(frame(1));
384        first.next().await.expect("a frame");
385        assert!(!first.keyframe_requested());
386        slot.request_keyframe();
387        slot.request_keyframe();
388        slot.send(frame(2));
389        first.next().await.expect("a frame");
390        assert!(first.keyframe_requested(), "the frame after the request");
391        assert_eq!(second.next().await.as_deref().map(micros), Some(2));
392        assert!(second.keyframe_requested(), "each handle sees the request");
393        slot.send(frame(3));
394        first.next().await.expect("a frame");
395        assert!(
396            !first.keyframe_requested(),
397            "two requests before one frame are one"
398        );
399    }
400
401    /// A request carries over to the newest frame when a reader skips the frame it preceded.
402    #[tokio::test]
403    async fn a_keyframe_request_survives_a_skipped_frame() {
404        let slot = FrameSlot::new();
405        let mut frames = slot.frames();
406        slot.request_keyframe();
407        slot.send(frame(1));
408        slot.send(frame(2));
409        assert_eq!(frames.next().await.as_deref().map(micros), Some(2));
410        assert!(frames.keyframe_requested());
411    }
412
413    /// A handle opened after a request does not report it for the frame already sent.
414    #[test]
415    fn a_fresh_handle_skips_earlier_requests() {
416        let slot = FrameSlot::new();
417        slot.request_keyframe();
418        slot.send(frame(1));
419        let mut frames = slot.frames();
420        assert!(frames.try_next().is_some());
421        assert!(!frames.keyframe_requested());
422    }
423
424    /// A handle opened on a cleared slot does not report requests made before its last frame.
425    #[test]
426    fn a_handle_on_a_cleared_slot_skips_earlier_requests() {
427        let slot = FrameSlot::new();
428        slot.request_keyframe();
429        slot.send(frame(1));
430        slot.clear();
431        let mut frames = slot.frames();
432        slot.send(frame(2));
433        assert!(frames.try_next().is_some());
434        assert!(!frames.keyframe_requested());
435    }
436
437    #[tokio::test]
438    async fn a_reader_does_not_hold_the_slot_open() {
439        let slot = FrameSlot::new();
440        let reader = slot.reader();
441        slot.fail(Arc::new(n0_error::e!(Error::Closed)));
442        drop(slot);
443        assert!(reader.frames().next().await.is_none());
444        assert!(reader.failure().is_some());
445    }
446}