Skip to main content

moq_ext_publisher/publish/
status.rs

1//! The watched state of a broadcast's slots and renditions.
2
3use std::{
4    collections::BTreeMap,
5    sync::{Arc, Mutex},
6};
7
8use moq_ext_sources::{ByPtr, Error, SlotState, send_if_changed};
9use tokio::sync::watch;
10
11/// Whether one rendition is encoding.
12///
13/// Two `Failed` states are equal only when they hold the same error, as
14/// [`ByPtr`] says.
15#[derive(Debug, Clone, Default, PartialEq, Eq)]
16pub enum RenditionState {
17    /// Advertised, but nobody is watching, so nothing is encoded.
18    #[default]
19    Idle,
20    /// Somebody is watching, and this encoder is running.
21    Encoding {
22        /// The encoder backend, such as `openh264` or `vaapi`.
23        encoder: String,
24    },
25    /// The encoder failed, and so did its fallback if there was one.
26    Failed(ByPtr<Error>),
27}
28
29/// The state of both slots of a broadcast, and of every rendition.
30#[derive(Debug, Clone, Default, PartialEq, Eq)]
31pub struct PublishStatus {
32    /// The video slot.
33    pub video: SlotState,
34    /// The audio slot.
35    pub audio: SlotState,
36    /// The state of each rendition, video and audio alike, keyed by track name.
37    pub renditions: BTreeMap<String, RenditionState>,
38}
39
40/// Which slot a report is about.
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub(crate) enum Medium {
43    /// The video slot.
44    Video,
45    /// The audio slot.
46    Audio,
47}
48
49/// The owner of each slot.
50#[derive(Debug, Default)]
51struct Owners {
52    video: Owner,
53    audio: Owner,
54}
55
56/// The task generation that owns a slot, with its rendition names.
57#[derive(Debug, Default)]
58struct Owner {
59    generation: u64,
60    names: Vec<String>,
61}
62
63impl Owners {
64    /// Returns the owner of `medium`.
65    fn get_mut(&mut self, medium: Medium) -> &mut Owner {
66        match medium {
67            Medium::Video => &mut self.video,
68            Medium::Audio => &mut self.audio,
69        }
70    }
71}
72
73impl PublishStatus {
74    /// Returns the state of the slot of `medium`.
75    fn slot(&mut self, medium: Medium) -> &mut SlotState {
76        match medium {
77            Medium::Video => &mut self.video,
78            Medium::Audio => &mut self.audio,
79        }
80    }
81}
82
83/// The broadcast's status, written only by the task that owns each slot.
84///
85/// A replaced publish task can still be finishing when its replacement starts.
86/// Every write goes through a [`Reporter`] that carries its task's generation.
87/// The write is dropped unless that generation still owns the slot. The owners'
88/// lock is held across the check and the write, so the two are atomic.
89#[derive(Debug, Clone, Default)]
90pub(crate) struct StatusCell {
91    owners: Arc<Mutex<Owners>>,
92    status: watch::Sender<PublishStatus>,
93}
94
95impl StatusCell {
96    /// Returns a receiver of the status.
97    pub(crate) fn subscribe(&self) -> watch::Receiver<PublishStatus> {
98        self.status.subscribe()
99    }
100
101    /// Returns the current status.
102    #[cfg(test)]
103    fn get(&self) -> PublishStatus {
104        self.status.borrow().clone()
105    }
106
107    /// Hands `medium` to the task of `generation` and returns its reporter.
108    ///
109    /// The renditions of the previous owner are removed.
110    pub(crate) fn begin(&self, medium: Medium, generation: u64, names: &[String]) -> Reporter {
111        let mut owners = self.owners.lock().expect("poisoned");
112        let previous = std::mem::replace(
113            owners.get_mut(medium),
114            Owner {
115                generation,
116                names: names.to_vec(),
117            },
118        );
119        send_if_changed(&self.status, |status| {
120            for name in &previous.names {
121                status.renditions.remove(name);
122            }
123            *status.slot(medium) = SlotState::Starting;
124            for name in names {
125                status.renditions.insert(name.clone(), RenditionState::Idle);
126            }
127        });
128        Reporter {
129            cell: self.clone(),
130            medium,
131            generation,
132        }
133    }
134
135    /// Turns `medium` off if the task of `generation` still owns it.
136    pub(crate) fn clear(&self, medium: Medium, generation: u64) {
137        let mut owners = self.owners.lock().expect("poisoned");
138        let owner = owners.get_mut(medium);
139        if owner.generation != generation {
140            return;
141        }
142        let names = std::mem::take(&mut owner.names);
143        send_if_changed(&self.status, |status| {
144            for name in &names {
145                status.renditions.remove(name);
146            }
147            *status.slot(medium) = SlotState::Off;
148        });
149    }
150
151    /// Applies `f` to the status if the task of `generation` still owns `medium`.
152    fn write(&self, medium: Medium, generation: u64, f: impl FnOnce(&mut PublishStatus)) {
153        let mut owners = self.owners.lock().expect("poisoned");
154        if owners.get_mut(medium).generation != generation {
155            return;
156        }
157        send_if_changed(&self.status, f);
158    }
159}
160
161/// A slot task's writer of its own state into a [`StatusCell`].
162#[derive(Debug, Clone)]
163pub(crate) struct Reporter {
164    cell: StatusCell,
165    medium: Medium,
166    generation: u64,
167}
168
169impl Reporter {
170    /// Sets the slot's state.
171    pub(crate) fn slot(&self, state: SlotState) {
172        let medium = self.medium;
173        self.cell.write(medium, self.generation, |status| {
174            *status.slot(medium) = state;
175        });
176    }
177
178    /// Sets one rendition's state.
179    pub(crate) fn rendition(&self, name: &str, state: RenditionState) {
180        self.cell.write(self.medium, self.generation, |status| {
181            status.renditions.insert(name.to_string(), state);
182        });
183    }
184}
185
186#[cfg(test)]
187mod tests {
188    use super::*;
189
190    fn names(names: &[&str]) -> Vec<String> {
191        names.iter().map(|name| name.to_string()).collect()
192    }
193
194    /// A replaced task still finishing cannot overwrite its replacement's state.
195    #[test]
196    fn a_replaced_task_cannot_write() {
197        let cell = StatusCell::default();
198        let old = cell.begin(Medium::Video, 1, &names(&["video"]));
199        let new = cell.begin(Medium::Video, 2, &names(&["video"]));
200        new.slot(SlotState::Running);
201        old.slot(SlotState::Ended);
202        old.rendition(
203            "video",
204            RenditionState::Encoding {
205                encoder: "stale".into(),
206            },
207        );
208        let status = cell.get();
209        assert_eq!(status.video, SlotState::Running);
210        assert_eq!(status.renditions["video"], RenditionState::Idle);
211    }
212
213    #[test]
214    fn a_new_task_replaces_the_old_renditions_only_for_its_medium() {
215        let cell = StatusCell::default();
216        let _audio = cell.begin(Medium::Audio, 1, &names(&["opus"]));
217        let _video = cell.begin(Medium::Video, 1, &names(&["360p", "720p"]));
218        let _video = cell.begin(Medium::Video, 2, &names(&["1080p"]));
219        let status = cell.get();
220        let listed: Vec<&str> = status.renditions.keys().map(String::as_str).collect();
221        assert_eq!(listed, ["1080p", "opus"]);
222        assert_eq!(status.video, SlotState::Starting);
223    }
224
225    #[test]
226    fn clearing_turns_the_slot_off() {
227        let cell = StatusCell::default();
228        let video = names(&["video"]);
229        let reporter = cell.begin(Medium::Video, 1, &video);
230        reporter.slot(SlotState::Running);
231        cell.clear(Medium::Video, 1);
232        let status = cell.get();
233        assert_eq!(status.video, SlotState::Off);
234        assert!(status.renditions.is_empty());
235    }
236
237    #[test]
238    fn failures_compare_by_identity() {
239        let err = ByPtr::new(n0_error::e!(Error::Closed));
240        assert_eq!(SlotState::Failed(err.clone()), SlotState::Failed(err));
241        assert_ne!(
242            SlotState::Failed(ByPtr::new(n0_error::e!(Error::Closed))),
243            SlotState::Failed(ByPtr::new(n0_error::e!(Error::Closed)))
244        );
245    }
246
247    #[test]
248    fn the_watcher_sees_each_change() {
249        let cell = StatusCell::default();
250        let mut status = cell.subscribe();
251        let reporter = cell.begin(Medium::Audio, 1, &names(&["opus"]));
252        assert!(status.has_changed().expect("alive"));
253        assert_eq!(status.borrow_and_update().audio, SlotState::Starting);
254        reporter.slot(SlotState::Running);
255        assert!(status.has_changed().expect("alive"));
256        assert_eq!(status.borrow_and_update().audio, SlotState::Running);
257        reporter.slot(SlotState::Running);
258        assert!(
259            !status.has_changed().expect("alive"),
260            "a repeat woke the receiver"
261        );
262    }
263}