moq_ext_publisher/publish/
status.rs1use 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#[derive(Debug, Clone, Default, PartialEq, Eq)]
16pub enum RenditionState {
17 #[default]
19 Idle,
20 Encoding {
22 encoder: String,
24 },
25 Failed(ByPtr<Error>),
27}
28
29#[derive(Debug, Clone, Default, PartialEq, Eq)]
31pub struct PublishStatus {
32 pub video: SlotState,
34 pub audio: SlotState,
36 pub renditions: BTreeMap<String, RenditionState>,
38}
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub(crate) enum Medium {
43 Video,
45 Audio,
47}
48
49#[derive(Debug, Default)]
51struct Owners {
52 video: Owner,
53 audio: Owner,
54}
55
56#[derive(Debug, Default)]
58struct Owner {
59 generation: u64,
60 names: Vec<String>,
61}
62
63impl Owners {
64 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 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#[derive(Debug, Clone, Default)]
90pub(crate) struct StatusCell {
91 owners: Arc<Mutex<Owners>>,
92 status: watch::Sender<PublishStatus>,
93}
94
95impl StatusCell {
96 pub(crate) fn subscribe(&self) -> watch::Receiver<PublishStatus> {
98 self.status.subscribe()
99 }
100
101 #[cfg(test)]
103 fn get(&self) -> PublishStatus {
104 self.status.borrow().clone()
105 }
106
107 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 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 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#[derive(Debug, Clone)]
163pub(crate) struct Reporter {
164 cell: StatusCell,
165 medium: Medium,
166 generation: u64,
167}
168
169impl Reporter {
170 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 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 #[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}