Skip to main content

moq_ext_sources/
status.rs

1//! The slot state a broadcast and a player both report, and a watch helper.
2
3use std::{fmt, ops::Deref, sync::Arc};
4
5use tokio::sync::watch;
6
7use crate::Error;
8
9/// Changes the value in place, and wakes its receivers only if it changed.
10///
11/// The player's selector watches the status it writes, so a write that
12/// changes nothing must not wake it.
13pub fn send_if_changed<T: Clone + PartialEq>(
14    sender: &watch::Sender<T>,
15    change: impl FnOnce(&mut T),
16) {
17    sender.send_if_modified(|value| {
18        let before = value.clone();
19        change(value);
20        *value != before
21    });
22}
23
24/// The state of one media slot, on a broadcast or on a player.
25///
26/// `PublishStatus` and `PlayerStatus` both use it, so a UI reports both the
27/// same way. Two `Failed` states are equal only when they hold the same error,
28/// as [`ByPtr`] says.
29#[derive(Debug, Clone, Default, PartialEq, Eq)]
30pub enum SlotState {
31    /// Nothing is set.
32    #[default]
33    Off,
34    /// Opening, probing encoders, or waiting for a first keyframe.
35    Starting,
36    /// Media is flowing.
37    Running,
38    /// Stopped by an error.
39    ///
40    /// On a broadcast, a failing hardware encoder falls back to software
41    /// before the slot fails, and a failed slot stays failed until its source
42    /// is set again. On a player, video and audio both try again after a pause.
43    Failed(ByPtr<Error>),
44    /// The source ended.
45    Ended,
46}
47
48/// An `Arc` that compares by pointer, so a watcher tells an update from a repeat.
49///
50/// Errors are not `PartialEq`, and a status that holds one must still be
51/// comparable. Two `ByPtr` are equal only when they share one allocation.
52#[derive(Debug)]
53pub struct ByPtr<T>(pub Arc<T>);
54
55impl<T> ByPtr<T> {
56    /// Wraps `value` in a new allocation.
57    #[must_use]
58    pub fn new(value: T) -> Self {
59        Self(Arc::new(value))
60    }
61}
62
63impl<T> Clone for ByPtr<T> {
64    fn clone(&self) -> Self {
65        Self(self.0.clone())
66    }
67}
68
69impl<T> PartialEq for ByPtr<T> {
70    fn eq(&self, other: &Self) -> bool {
71        Arc::ptr_eq(&self.0, &other.0)
72    }
73}
74
75impl<T> Eq for ByPtr<T> {}
76
77impl<T> From<Arc<T>> for ByPtr<T> {
78    fn from(value: Arc<T>) -> Self {
79        Self(value)
80    }
81}
82
83impl<T> Deref for ByPtr<T> {
84    type Target = T;
85
86    fn deref(&self) -> &T {
87        &self.0
88    }
89}
90
91impl<T: fmt::Display> fmt::Display for ByPtr<T> {
92    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93        self.0.fmt(f)
94    }
95}