Skip to main content

moq_ext_player/
player.rs

1//! Playback: one player over a remote broadcast.
2//!
3//! A [`Player`] owns its decoders, its playout clock, its rendition choice and
4//! its statistics, so two players of one broadcast do not interfere.
5//!
6//! Three tasks run underneath. The selector turns the rendition mode, the
7//! catalog and the network into the rendition that should play. The video
8//! supervisor keeps one decoder playing and at most one replacement warming
9//! up, and hands over once the replacement has caught up
10//! (`moq_ext_adaptive::Switcher`). The audio task decodes into the output and
11//! reports how much it has buffered. The video waits on that figure.
12
13use std::{
14    sync::{Arc, Mutex},
15    time::Duration,
16};
17
18use moq_ext_sources::{
19    ByPtr, Error, SlotState, send_if_changed,
20    stats::{Rates, SharedCell},
21};
22use moq_mux::container::Delay;
23use n0_future::task::AbortOnDropHandle;
24use tokio::sync::{broadcast, mpsc, watch};
25use tracing::{Instrument, debug_span, info, info_span};
26
27use crate::{
28    RemoteBroadcast,
29    frames::{FrameSlot, VideoFrames},
30    stats::{AudioPlaybackStats, FrameLog, FrameTiming, PlaybackStats, VideoPlaybackStats},
31};
32
33mod audio;
34mod backlog;
35mod clock;
36mod select;
37mod video_task;
38
39pub use moq_ext_adaptive::{Adaptation, RenditionMode};
40
41pub use self::{
42    audio::{AudioFrame, AudioFrames},
43    backlog::VideoBacklog,
44};
45pub(crate) use self::{backlog::VideoBacklogs, clock::PlayoutClock};
46
47/// The latency of [`PlayerConfig::default`]: held for at least 100 ms, and skipped past 150 ms.
48pub const DEFAULT_LATENCY: Delay = Delay {
49    min: Some(Duration::from_millis(100)),
50    max: Some(Duration::from_millis(150)),
51};
52
53/// No buffer and no pacing: a frame presents as soon as it decodes.
54///
55/// Media older than 150 ms is still skipped: a player without a buffer wants
56/// the live edge.
57pub const IMMEDIATE_LATENCY: Delay = Delay {
58    min: Some(Duration::ZERO),
59    max: Some(Duration::from_millis(150)),
60};
61
62/// How far below the latency's maximum a track's target may raise the playout delay: a frame at 30 fps.
63const JITTER_HEADROOM: Duration = Duration::from_millis(33);
64
65/// Reports whether a player at `latency` holds frames for the clock.
66pub(crate) fn paced(latency: &Delay) -> bool {
67    latency.min.is_some_and(|min| !min.is_zero())
68}
69
70/// Returns how far behind the live edge one track asks the playout clock to run, at `latency`.
71///
72/// This is hang's rule: a track holds its catalog `delay` plus its jitter
73/// allowance. The allowance is `jitter`, the catalog's figure for video and
74/// the audio decoder's measured target for audio, and never less than the
75/// latency's minimum. The clock runs at the largest target of its tracks.
76///
77/// A target stays [`JITTER_HEADROOM`] below the latency's maximum, the age at
78/// which the transport skips media, so a frame that arrives a little late is
79/// not past it before it is due. It never drops below the minimum. An unpaced
80/// latency holds nothing.
81pub(crate) fn track_target(
82    latency: &Delay,
83    delay: Option<Duration>,
84    jitter: Option<Duration>,
85) -> Duration {
86    if !paced(latency) {
87        return Duration::ZERO;
88    }
89    let min = latency.min.unwrap_or_default();
90    let ceiling = latency
91        .max
92        .map_or(Duration::MAX, |max| max.saturating_sub(JITTER_HEADROOM));
93    let wanted = delay
94        .unwrap_or_default()
95        .saturating_add(min.max(jitter.unwrap_or_default()));
96    min.max(wanted.min(ceiling))
97}
98
99/// Returns an [`Error::InvalidConfig`] if the latency's minimum is above its maximum.
100fn validate(latency: &Delay) -> Result<(), Error> {
101    match (latency.min, latency.max) {
102        (Some(min), Some(max)) if min > max => Err(Error::invalid(format!(
103            "a latency's minimum ({min:?}) is above its maximum ({max:?})"
104        ))),
105        _ => Ok(()),
106    }
107}
108
109/// What a player does with the broadcast's audio.
110#[derive(derive_more::Debug, Clone, Default)]
111pub enum AudioMode {
112    /// Leaves the audio alone, without subscribing to it.
113    #[default]
114    Off,
115    /// Decodes the audio for [`Player::audio_frames`] without playing it.
116    ///
117    /// Nothing is queued ahead of a device, so the audio is not paced, and
118    /// its measured jitter does not hold the video back.
119    Decode,
120    /// Decodes the audio and plays it on this speaker engine.
121    ///
122    /// Every player writing to one engine is mixed into one device stream.
123    /// The decoded audio also goes to [`Player::audio_frames`]. The jitter
124    /// the audio decoder measures raises the playout delay of the video too.
125    #[cfg(feature = "playback")]
126    Play(#[debug(skip)] moq_audio::playback::Engine),
127}
128
129impl AudioMode {
130    /// Returns [`Play`](Self::Play) on `speaker` if there is one, and [`Decode`](Self::Decode) otherwise.
131    ///
132    /// For an application whose speaker may fail to open: its players
133    /// still decode the audio without one.
134    #[cfg(feature = "playback")]
135    #[must_use]
136    pub fn play_or_decode(speaker: Option<moq_audio::playback::Engine>) -> Self {
137        speaker.map_or(Self::Decode, Self::Play)
138    }
139}
140
141/// How a player plays.
142#[derive(Debug, Clone)]
143#[non_exhaustive]
144pub struct PlayerConfig {
145    /// How to choose the video rendition.
146    pub rendition: RenditionMode,
147    /// How far behind live to run, as the media reader's [`Delay`].
148    ///
149    /// The playout clock runs at least `min` behind the live edge. Each track
150    /// asks for more when it needs it: video for its catalog `delay` plus its
151    /// catalog `jitter`, and audio for its catalog `delay` plus the jitter its
152    /// decoder measures as packets arrive. The clock follows the largest ask,
153    /// up to a frame below `max`, so the delay rises on a jittery link and
154    /// returns to `min` on a clean one. While audio plays, pictures show when
155    /// their sound does. Media later than `max` is skipped. Both reach the
156    /// transport, so media relays and the publisher see them too. Setting
157    /// `min == max` gives a fixed latency, and an unset `min` counts as zero.
158    /// [`DEFAULT_LATENCY`] by default.
159    pub latency: Delay,
160    /// What to do with the audio, [`AudioMode::Off`] by default.
161    pub audio: AudioMode,
162    /// The decoder backend to open, `Auto` by default.
163    pub decoder: moq_video::decode::Backend,
164    /// How automatic selection follows the link.
165    pub adaptation: Adaptation,
166}
167
168impl Default for PlayerConfig {
169    fn default() -> Self {
170        Self {
171            rendition: RenditionMode::default(),
172            latency: DEFAULT_LATENCY,
173            audio: AudioMode::Off,
174            decoder: moq_video::decode::Backend::default(),
175            adaptation: Adaptation::default(),
176        }
177    }
178}
179
180impl PlayerConfig {
181    /// Returns this config with `rendition` choosing the video rendition.
182    #[must_use]
183    pub fn with_rendition(mut self, rendition: RenditionMode) -> Self {
184        self.rendition = rendition;
185        self
186    }
187
188    /// Returns this config with `latency` as how far behind live to run.
189    #[must_use]
190    pub fn with_latency(mut self, latency: Delay) -> Self {
191        self.latency = latency;
192        self
193    }
194
195    /// Returns this config with `audio` as what to do with the audio.
196    #[must_use]
197    pub fn with_audio(mut self, audio: AudioMode) -> Self {
198        self.audio = audio;
199        self
200    }
201
202    /// Returns this config with `decoder` as the decoder backend to open.
203    #[must_use]
204    pub fn with_decoder(mut self, decoder: moq_video::decode::Backend) -> Self {
205        self.decoder = decoder;
206        self
207    }
208
209    /// Returns this config with `adaptation` as how automatic selection follows the link.
210    #[must_use]
211    pub fn with_adaptation(mut self, adaptation: Adaptation) -> Self {
212        self.adaptation = adaptation;
213        self
214    }
215}
216
217/// The state of a player.
218#[derive(Debug, Clone, Default, PartialEq)]
219pub struct PlayerStatus {
220    /// The video slot.
221    pub video: SlotState,
222    /// The audio slot.
223    pub audio: SlotState,
224    /// The rendition mode asked for.
225    pub mode: RenditionMode,
226    /// The rendition on screen.
227    pub rendition: Option<String>,
228    /// A rendition whose decoder is warming up to take over.
229    pub switching_to: Option<String>,
230    /// Why the last switch or pin could not be honoured.
231    pub switch_error: Option<ByPtr<Error>>,
232    /// The decoder backend running, such as `vaapi`.
233    pub decoder: Option<String>,
234}
235
236impl PlayerStatus {
237    /// Sets the video slot to `state` with nothing on screen or on its way.
238    pub(crate) fn clear_video(&mut self, state: SlotState) {
239        self.video = state;
240        self.rendition = None;
241        self.switching_to = None;
242        self.decoder = None;
243    }
244}
245
246/// The writers behind [`PlaybackStats`].
247#[derive(Debug, Clone, Default)]
248pub(crate) struct PlaybackRecorder {
249    pub(crate) video: SharedCell<Option<VideoPlaybackStats>>,
250    /// The last rates of shown pictures, which fill [`VideoPlaybackStats::fps`] while current.
251    pub(crate) video_rate: SharedCell<Option<Rates>>,
252    pub(crate) audio: SharedCell<Option<AudioPlaybackStats>>,
253    /// Written by the video task as it presents pictures.
254    pub(crate) video_log: FrameLog,
255    /// Handed every picture the video task presents.
256    pub(crate) video_backlogs: VideoBacklogs,
257    /// Written by the audio task as it writes to the output.
258    pub(crate) audio_log: FrameLog,
259}
260
261/// What the player's controls ask for, shared with its tasks.
262#[derive(Debug)]
263pub(crate) struct Controls {
264    pub(crate) mode: watch::Sender<RenditionMode>,
265    pub(crate) latency: watch::Sender<Delay>,
266    pub(crate) decoder: watch::Sender<moq_video::decode::Backend>,
267    pub(crate) volume: watch::Sender<f32>,
268}
269
270/// One playback: video into [`VideoFrames`], audio into the speaker and [`AudioFrames`].
271///
272/// Dropping it aborts its tasks and returns at once: decoders stop at their
273/// next await point and are not waited for, so a decoder thread may outlive
274/// the player briefly. A second view of the broadcast is a second player.
275#[derive(Debug)]
276pub struct Player {
277    broadcast: RemoteBroadcast,
278    frames: VideoFrames,
279    /// The cursor of [`Player::take_latest_video`].
280    latest: Mutex<VideoFrames>,
281    audio_frames: broadcast::Sender<AudioFrame>,
282    status: watch::Sender<PlayerStatus>,
283    controls: Arc<Controls>,
284    clock: PlayoutClock,
285    stats: PlaybackRecorder,
286    _tasks: Vec<AbortOnDropHandle<()>>,
287}
288
289impl Drop for Player {
290    fn drop(&mut self) {
291        self.clock.close();
292    }
293}
294
295impl Player {
296    /// Starts playing `broadcast`, for [`RemoteBroadcast::play`].
297    pub(crate) fn start(broadcast: RemoteBroadcast, config: PlayerConfig) -> Result<Self, Error> {
298        validate(&config.latency)?;
299        let span = info_span!(parent: broadcast.span(), "player");
300        let status = watch::Sender::new(PlayerStatus {
301            mode: config.rendition.clone(),
302            video: match config.rendition {
303                RenditionMode::Off => SlotState::Off,
304                _ => SlotState::Starting,
305            },
306            audio: match config.audio {
307                AudioMode::Off => SlotState::Off,
308                _ => SlotState::Starting,
309            },
310            ..PlayerStatus::default()
311        });
312        let controls = Arc::new(Controls {
313            mode: watch::Sender::new(config.rendition.clone()),
314            latency: watch::Sender::new(config.latency),
315            decoder: watch::Sender::new(config.decoder.clone()),
316            volume: watch::Sender::new(1.0),
317        });
318        let (audio_frames, _) = broadcast::channel(audio::AUDIO_FRAMES_BACKLOG);
319        let clock = PlayoutClock::new(config.latency.min.unwrap_or_default());
320        let stats = PlaybackRecorder::default();
321        let slot = FrameSlot::new();
322        let frames = slot.frames();
323        // The supervisor reports failed and ended renditions, and the selector
324        // backs off from them. Only a selector eight reports behind fills the
325        // channel, and a report dropped then costs at most one early retry.
326        let (reports_tx, reports_rx) = mpsc::channel(8);
327        let (desired_tx, desired_rx) = watch::channel(None);
328        // The exact target on screen. Once something plays, the selector stops
329        // asking again for video that ended.
330        let (playing_tx, playing_rx) = watch::channel(None);
331
332        let mut tasks = Vec::new();
333        tasks.push(AbortOnDropHandle::new(n0_future::task::spawn(
334            select::run(select::Inputs {
335                broadcast: broadcast.clone(),
336                controls: controls.clone(),
337                status: status.clone(),
338                reports: reports_rx,
339                playing: playing_rx,
340                desired: desired_tx,
341                clock: clock.clone(),
342                adaptation: config.adaptation,
343            })
344            .instrument(debug_span!(parent: &span, "select")),
345        )));
346        tasks.push(AbortOnDropHandle::new(n0_future::task::spawn(
347            video_task::run(video_task::Inputs {
348                desired: desired_rx,
349                frames: slot,
350                controls: controls.clone(),
351                status: status.clone(),
352                reports: reports_tx,
353                playing: playing_tx,
354                clock: clock.clone(),
355                stats: stats.clone(),
356            })
357            .instrument(info_span!(parent: &span, "video")),
358        )));
359        if !matches!(config.audio, AudioMode::Off) {
360            #[cfg(feature = "playback")]
361            let speaker = match config.audio {
362                AudioMode::Play(engine) => Some(engine),
363                _ => None,
364            };
365            tasks.push(AbortOnDropHandle::new(n0_future::task::spawn(
366                audio::run(audio::Inputs {
367                    broadcast: broadcast.clone(),
368                    #[cfg(feature = "playback")]
369                    speaker,
370                    frames: audio_frames.clone(),
371                    controls: controls.clone(),
372                    status: status.clone(),
373                    clock: clock.clone(),
374                    stats: stats.clone(),
375                })
376                .instrument(info_span!(parent: &span, "audio")),
377            )));
378        }
379        info!(parent: &span, mode = ?config.rendition, latency = ?config.latency, "player started");
380
381        Ok(Self {
382            broadcast,
383            latest: Mutex::new(frames.clone()),
384            frames,
385            audio_frames,
386            status,
387            controls,
388            clock,
389            stats,
390            _tasks: tasks,
391        })
392    }
393
394    /// Returns the decoded video frames.
395    ///
396    /// Every call returns a handle onto the same stream, and each handle keeps
397    /// its own cursor. The stream survives rendition switches and decoder
398    /// changes. It ends when the broadcast closes or the player is dropped.
399    #[must_use]
400    pub fn video_frames(&self) -> VideoFrames {
401        self.frames.clone()
402    }
403
404    /// Returns the decoded audio, as PCM with its timestamps.
405    ///
406    /// The frames flow only while [`PlayerConfig::audio`] is not
407    /// [`AudioMode::Off`], with or without a speaker. Without one, the audio is
408    /// decoded without playing it, for analysis. Each call returns a new handle
409    /// that starts at the next decoded frame and ends when the player is
410    /// dropped.
411    ///
412    /// # Examples
413    ///
414    /// ```no_run
415    /// # async fn example(broadcast: moq_ext_player::RemoteBroadcast) -> Result<(), moq_ext_player::Error> {
416    /// use moq_ext_player::{AudioMode, PlayerConfig};
417    ///
418    /// let player = broadcast.play(PlayerConfig::default().with_audio(AudioMode::Decode))?;
419    /// let mut audio = player.audio_frames();
420    /// while let Some(frame) = audio.next().await {
421    ///     let peak = frame.samples.iter().fold(0f32, |peak, s| peak.max(s.abs()));
422    ///     println!("{:?}: peak {peak}", frame.timestamp);
423    /// }
424    /// # Ok(())
425    /// # }
426    /// ```
427    #[must_use]
428    pub fn audio_frames(&self) -> AudioFrames {
429        AudioFrames::new(&self.audio_frames)
430    }
431
432    /// Returns the broadcast this player plays.
433    #[must_use]
434    pub fn broadcast(&self) -> &RemoteBroadcast {
435        &self.broadcast
436    }
437
438    /// Chooses how the video rendition is picked.
439    pub fn set_rendition(&self, mode: RenditionMode) {
440        send_if_changed(&self.status, |status| status.mode = mode.clone());
441        self.controls.mode.send_replace(mode);
442    }
443
444    /// Changes how far behind live the player runs, without a gap in the picture.
445    ///
446    /// The playout clock starts over at the new delay, so the schedule moves
447    /// once: the next video frame or audio write anchors it again. The latency
448    /// is the subscription's [`Delay`]. A new `max` alone moves the video's
449    /// subscription in place. A new `min`, or a change to or from no `max`,
450    /// rebuilds the video decoder behind the picture with the new range: the
451    /// new decoder takes over once it has caught up, as in a switch, and the
452    /// current picture stays up until then. Audio keeps its old range until it
453    /// next opens, because a rebuild would be audible.
454    ///
455    /// This does not block or await, so there is nothing to cancel: the change
456    /// is recorded before it returns, and the player's tasks apply it on their
457    /// next pass. Setting the latency already in force changes nothing.
458    ///
459    /// # Errors
460    ///
461    /// Returns [`Error::InvalidConfig`] if `latency.min` is above
462    /// `latency.max`, and leaves the latency unchanged.
463    pub fn set_latency(&self, latency: Delay) -> Result<(), Error> {
464        validate(&latency)?;
465        self.controls.latency.send_if_modified(|current| {
466            let changed = *current != latency;
467            *current = latency;
468            changed
469        });
470        Ok(())
471    }
472
473    /// Changes the video decoder backend.
474    ///
475    /// The replacement opens behind the picture and takes over once it has
476    /// caught up. A backend that fails to open leaves the incumbent playing and
477    /// says so in [`PlayerStatus::switch_error`]. Automatic rendition switches
478    /// also open under the failing backend, so they fail until the next
479    /// `set_decoder`.
480    pub fn set_decoder(&self, decoder: moq_video::decode::Backend) {
481        self.controls.decoder.send_replace(decoder);
482    }
483
484    /// Sets the audio volume, where 1.0 is unattenuated.
485    pub fn set_volume(&self, volume: f32) {
486        self.controls.volume.send_replace(volume.max(0.0));
487    }
488
489    /// Returns the player's state.
490    ///
491    /// A borrow of the receiver blocks the player's writes, so keep it short
492    /// and do not hold it across a call into the player.
493    #[must_use]
494    pub fn status(&self) -> watch::Receiver<PlayerStatus> {
495        self.status.subscribe()
496    }
497
498    /// Returns the player's playback statistics.
499    #[must_use]
500    pub fn stats(&self) -> PlaybackStats {
501        let mut audio_stats = self.stats.audio.get();
502        if let Some(stats) = audio_stats.as_mut() {
503            // The audio task writes the level only as frames arrive.
504            let decoded = self.stats.audio_log.last_decoded();
505            if decoded.is_none_or(|at| at.elapsed() > audio::LEVEL_STALE) {
506                stats.rms = None;
507                stats.peak = 0.0;
508            }
509        }
510        let mut video_stats = self.stats.video.get();
511        if let Some(stats) = video_stats.as_mut() {
512            // The video task writes the rate only as pictures are shown.
513            let rate = self.stats.video_rate.get().filter(Rates::is_current);
514            stats.fps = rate.map(|rate| rate.events.round() as u32);
515        }
516        PlaybackStats {
517            video: video_stats,
518            audio: audio_stats,
519            latency: self.clock.delay(),
520            network: self.broadcast.network().map(|signals| signals()),
521        }
522    }
523
524    /// Returns the last presented video and audio frames, in presentation order.
525    ///
526    /// Keeps a few hundred frames of each medium, about ten seconds at usual
527    /// rates. It is meant for a debugging view of pacing and A/V sync. Read it
528    /// once per redraw of that view, not per frame.
529    #[must_use]
530    pub fn timeline(&self) -> Vec<FrameTiming> {
531        let mut frames: Vec<FrameTiming> = self
532            .stats
533            .video_log
534            .snapshot()
535            .into_iter()
536            .chain(self.stats.audio_log.snapshot())
537            .collect();
538        frames.sort_by_key(|timing| timing.presented);
539        frames
540    }
541
542    /// Returns the timing of the presented picture at `timestamp`, or `None` once it left the timeline.
543    ///
544    /// `timestamp` is the `timestamp` of a frame from
545    /// [`video_frames`](Self::video_frames). Its `arrived`, `decoded` and
546    /// `presented` tell the time on the network from the time in the decoder
547    /// and in the playout clock. Look a frame up soon after it is handed out.
548    /// Also `None` for a timestamp without a timescale, which no presented
549    /// picture has.
550    ///
551    /// # Examples
552    ///
553    /// ```no_run
554    /// # async fn run(player: moq_ext_player::Player) {
555    /// let mut frames = player.video_frames();
556    /// while let Some(frame) = frames.next().await {
557    ///     let Some(timing) = player.video_timing(frame.timestamp) else {
558    ///         continue;
559    ///     };
560    ///     if let Some(arrived) = timing.arrived {
561    ///         println!("{:?} since its data arrived", arrived.elapsed());
562    ///     }
563    ///     println!("{:?} in the decoder", timing.decode_time());
564    /// }
565    /// # }
566    /// ```
567    #[must_use]
568    pub fn video_timing(&self, timestamp: moq_net::Timestamp) -> Option<FrameTiming> {
569        let pts = Duration::try_from(timestamp).ok()?;
570        self.stats.video_log.find(pts)
571    }
572
573    /// Returns a queue of every picture presented from now on, with its timing.
574    ///
575    /// Unlike [`video_frames`](Self::video_frames), which skips pictures a
576    /// slow reader missed, [`VideoBacklog::take`] returns each picture once.
577    /// The backlog holds at most `capacity` pictures, at least one, and drops
578    /// the oldest beyond it.
579    ///
580    /// A held picture keeps its decoded buffer alive, which may come from a
581    /// hardware decoder's fixed pool, so a large capacity or a backlog no
582    /// longer taken can stall hardware decoding. Drop it when you stop taking.
583    ///
584    /// # Examples
585    ///
586    /// ```no_run
587    /// # async fn run(player: moq_ext_player::Player) {
588    /// let backlog = player.video_backlog(16);
589    /// let mut tick = tokio::time::interval(std::time::Duration::from_millis(100));
590    /// loop {
591    ///     tick.tick().await;
592    ///     for (frame, timing) in backlog.take() {
593    ///         println!("{:?}: in the decoder for {:?}", frame.timestamp, timing.decode_time());
594    ///     }
595    /// }
596    /// # }
597    /// ```
598    #[must_use]
599    pub fn video_backlog(&self, capacity: usize) -> VideoBacklog {
600        self.stats.video_backlogs.open(capacity)
601    }
602
603    /// Returns the newest presented picture since the last call, with its timing.
604    ///
605    /// For a consumer that samples the video at its own rate, such as an
606    /// analysis loop or a thumbnailer, instead of reading every picture from
607    /// [`video_frames`](Self::video_frames). Pictures presented between two
608    /// calls are skipped. Returns `None` if nothing was presented since the
609    /// last call. The player keeps one cursor for this method, so two callers
610    /// take turns at the same pictures. A reader that needs its own cursor
611    /// can use a [`video_backlog`](Self::video_backlog) of capacity 1.
612    ///
613    /// [`FrameTiming::arrived`] tells the time on the network from the time
614    /// in the decoder. It is `None` for a picture the decoder could not match
615    /// to one access unit, and then `decoded` is the earliest instant the
616    /// player knows of.
617    ///
618    /// # Examples
619    ///
620    /// ```no_run
621    /// # async fn run(player: moq_ext_player::Player) {
622    /// let mut tick = tokio::time::interval(std::time::Duration::from_millis(100));
623    /// loop {
624    ///     tick.tick().await;
625    ///     if let Some((frame, timing)) = player.take_latest_video() {
626    ///         let age = timing.presented.elapsed();
627    ///         println!("{} picture, presented {age:?} ago", frame.size());
628    ///     }
629    /// }
630    /// # }
631    /// ```
632    #[must_use]
633    pub fn take_latest_video(&self) -> Option<(Arc<moq_video::Frame>, FrameTiming)> {
634        let frame = self.latest.lock().expect("poisoned").try_next()?;
635        // A picture's timing is logged before the picture is handed out.
636        let timing = self
637            .stats
638            .video_log
639            .find(crate::duration(frame.timestamp))?;
640        Some((frame, timing))
641    }
642}
643
644#[cfg(test)]
645mod tests {
646    use super::*;
647
648    const fn ms(millis: u64) -> Duration {
649        Duration::from_millis(millis)
650    }
651
652    #[cfg(feature = "playback")]
653    #[test]
654    fn no_speaker_decodes_the_audio() {
655        assert!(matches!(AudioMode::play_or_decode(None), AudioMode::Decode));
656    }
657
658    #[test]
659    fn a_track_target_follows_a_larger_jitter_up_to_the_maximum() {
660        let latency = Delay {
661            min: Some(ms(100)),
662            max: Some(ms(400)),
663        };
664        assert_eq!(track_target(&latency, None, None), ms(100));
665        assert_eq!(track_target(&latency, None, Some(ms(40))), ms(100));
666        assert_eq!(track_target(&latency, None, Some(ms(250))), ms(250));
667        assert_eq!(
668            track_target(&latency, None, Some(ms(2000))),
669            ms(400) - JITTER_HEADROOM,
670            "a frame's worth of headroom stays below the skip threshold"
671        );
672        // The default keeps headroom at its maximum, and stays at or above its minimum.
673        let delay = track_target(&DEFAULT_LATENCY, None, Some(ms(150)));
674        assert!(delay < ms(150) && delay >= ms(100), "{delay:?}");
675        let tight = Delay {
676            min: Some(ms(150)),
677            max: Some(ms(150)),
678        };
679        assert_eq!(track_target(&tight, None, Some(ms(400))), ms(150));
680        assert_eq!(
681            track_target(&IMMEDIATE_LATENCY, Some(ms(50)), Some(ms(250))),
682            Duration::ZERO
683        );
684    }
685
686    /// The catalog `delay` adds to the jitter allowance, as hang asks a consumer to.
687    #[test]
688    fn a_track_target_adds_the_catalog_delay() {
689        let latency = Delay {
690            min: Some(ms(100)),
691            max: Some(ms(400)),
692        };
693        assert_eq!(track_target(&latency, Some(ms(50)), None), ms(150));
694        assert_eq!(track_target(&latency, Some(ms(50)), Some(ms(200))), ms(250));
695        assert_eq!(
696            track_target(&latency, Some(ms(300)), Some(ms(200))),
697            ms(400) - JITTER_HEADROOM,
698            "the sum is capped like the jitter alone"
699        );
700        assert_eq!(track_target(&latency, Some(Duration::ZERO), None), ms(100));
701    }
702
703    #[test]
704    fn an_unset_bound_is_no_bound() {
705        let open = Delay {
706            min: None,
707            max: None,
708        };
709        assert!(!paced(&open));
710        assert_eq!(track_target(&open, None, Some(ms(250))), Duration::ZERO);
711        let unbounded = Delay {
712            min: Some(ms(100)),
713            max: None,
714        };
715        assert_eq!(track_target(&unbounded, None, Some(ms(2000))), ms(2000));
716        assert!(validate(&unbounded).is_ok());
717        assert!(
718            validate(&Delay {
719                min: Some(ms(200)),
720                max: Some(ms(100)),
721            })
722            .is_err()
723        );
724    }
725}