1use std::{
10 future::Future,
11 sync::{Arc, Mutex},
12 time::Instant,
13};
14
15use n0_future::task::AbortOnDropHandle;
16use tokio::sync::watch;
17use tokio_util::sync::CancellationToken;
18use tracing::{Instrument, debug, info, info_span, warn};
19
20use super::{Demand, Driver, VideoFormat, VideoSource};
21use crate::{
22 ByPtr, Error, SlotState,
23 frames::FrameSlot,
24 spec::{VideoOpenOptions, VideoSourceSpec},
25};
26
27#[derive(Debug, Default)]
29struct Current {
30 generation: u64,
32 source: Option<VideoSource>,
37}
38
39#[derive(Debug)]
41struct Shared {
42 slot: FrameSlot,
43 current: Mutex<Current>,
44 status: watch::Sender<SlotState>,
45 demand: Demand,
47 stop: CancellationToken,
49}
50
51impl Shared {
52 fn if_current(
56 &self,
57 generation: u64,
58 f: impl FnOnce(&mut Option<VideoSource>, &watch::Sender<SlotState>),
59 ) -> bool {
60 let mut current = self.current.lock().expect("poisoned");
61 if current.generation != generation {
62 return false;
63 }
64 f(&mut current.source, &self.status);
65 true
66 }
67}
68
69#[derive(Debug, Clone)]
80pub struct VideoSwitch {
81 shared: Arc<Shared>,
82 task: Arc<Mutex<Option<AbortOnDropHandle<()>>>>,
83}
84
85impl VideoSource {
86 #[must_use]
114 pub fn switchable(format: VideoFormat) -> (VideoSwitch, Self) {
115 let slot = FrameSlot::new();
116 let stop = CancellationToken::new();
117 let source = Self::new(
118 "switch",
119 format,
120 slot.reader(),
121 stop.clone(),
122 Driver::Pushed,
123 );
124 let switch = VideoSwitch {
125 shared: Arc::new(Shared {
126 slot,
127 current: Mutex::default(),
128 status: watch::Sender::new(SlotState::Off),
129 demand: source.inner.demand.clone(),
130 stop,
131 }),
132 task: Default::default(),
133 };
134 (switch, source)
135 }
136}
137
138impl VideoSwitch {
139 pub fn replace(&self, source: VideoSource) {
150 info!(source = source.label(), "video switch: replaced");
151 self.install(Some(source), SlotState::Running, forward);
152 }
153
154 pub fn open<F>(&self, open: F)
167 where
168 F: Future<Output = Result<VideoSource, Error>> + Send + 'static,
169 {
170 info!("video switch: opening a source");
171 self.install(None, SlotState::Starting, |shared, generation| async move {
172 let opened = tokio::select! {
173 opened = open => opened,
174 () = shared.stop.cancelled() => return,
175 };
176 match opened {
177 Ok(source) => {
178 debug!(source = source.label(), "video switch: opened");
179 let installed = shared.if_current(generation, |current, status| {
180 *current = Some(source);
181 status.send_replace(SlotState::Running);
182 });
183 if installed {
184 forward(shared.clone(), generation).await;
185 }
186 }
187 Err(err) => {
188 warn!(error = format_args!("{err:#}"), "video switch: open failed");
189 shared.if_current(generation, |_, status| {
190 status.send_replace(SlotState::Failed(ByPtr::new(err)));
191 });
192 }
193 }
194 });
195 }
196
197 pub fn open_spec(&self, spec: VideoSourceSpec, options: VideoOpenOptions) {
206 if spec == VideoSourceSpec::None {
207 self.clear();
208 return;
209 }
210 self.open(async move {
211 spec.open(&options)
212 .await?
213 .ok_or_else(|| Error::invalid("no video source to open"))
214 });
215 }
216
217 pub fn clear(&self) {
222 info!("video switch: cleared");
223 let mut task = self.task.lock().expect("poisoned");
224 drop(self.supersede(None, SlotState::Off, LastFrame::Keep).1);
225 *task = None;
226 }
227
228 #[must_use]
230 pub fn status(&self) -> watch::Receiver<SlotState> {
231 self.shared.status.subscribe()
232 }
233
234 fn supersede(
241 &self,
242 source: Option<VideoSource>,
243 state: SlotState,
244 last_frame: LastFrame,
245 ) -> (u64, Option<VideoSource>) {
246 let mut current = self.shared.current.lock().expect("poisoned");
247 current.generation += 1;
248 if last_frame == LastFrame::Drop {
249 self.shared.slot.clear();
250 }
251 self.shared.status.send_replace(state);
252 let previous = std::mem::replace(&mut current.source, source);
253 (current.generation, previous)
254 }
255
256 fn install<R, Fut>(&self, source: Option<VideoSource>, state: SlotState, run: R)
258 where
259 R: FnOnce(Arc<Shared>, u64) -> Fut,
260 Fut: Future<Output = ()> + Send + 'static,
261 {
262 let mut task = self.task.lock().expect("poisoned");
263 let (generation, previous) = self.supersede(source, state, LastFrame::Drop);
264 drop(previous);
266 let future = run(self.shared.clone(), generation);
267 *task = Some(AbortOnDropHandle::new(n0_future::task::spawn(
268 future.instrument(info_span!("video_switch", generation)),
269 )));
270 }
271}
272
273#[derive(Debug, Clone, Copy, PartialEq, Eq)]
275enum LastFrame {
276 Keep,
278 Drop,
280}
281
282async fn forward(shared: Arc<Shared>, generation: u64) {
288 let mut frames = None;
289 shared.if_current(generation, |current, _| {
290 frames = current.as_ref().map(VideoSource::observe);
292 });
293 let Some(mut frames) = frames else {
294 return;
295 };
296 let mut wanted = shared.demand.watch();
297 let mut guard = None;
298 loop {
299 let want = *wanted.borrow_and_update();
300 if want != guard.is_some() {
301 shared.if_current(generation, |current, _| {
302 guard = current.as_ref().filter(|_| want).map(VideoSource::want);
303 });
304 }
305 tokio::select! {
306 frame = frames.next() => {
307 let Some(frame) = frame else { break };
308 let at = frames.sent_at().unwrap_or_else(Instant::now);
309 let keyframe = frames.keyframe_requested();
310 let forwarded = shared.if_current(generation, |_, _| {
311 if keyframe {
312 shared.slot.request_keyframe();
313 }
314 shared.slot.send_at(frame, at);
315 });
316 if !forwarded {
317 return;
318 }
319 }
320 changed = wanted.changed() => if changed.is_err() { return },
321 () = shared.stop.cancelled() => {
322 shared.if_current(generation, |current, _| *current = None);
323 return;
324 }
325 }
326 }
327 drop(guard);
328 shared.if_current(generation, |current, status| {
329 let state = match current.take().and_then(|source| source.failure()) {
330 Some(failure) => SlotState::Failed(failure.into()),
331 None => SlotState::Ended,
332 };
333 debug!(?state, "video switch: the source stopped");
334 status.send_replace(state);
335 });
336}
337
338#[cfg(test)]
339mod tests {
340 use std::time::Duration;
341
342 use super::*;
343 use crate::{FrameSender, video};
344
345 const TIMEOUT: Duration = Duration::from_secs(5);
346
347 fn format() -> VideoFormat {
348 VideoFormat {
349 size: video::Size::new(2, 2),
350 rate: video::FrameRate::new(30, 1).expect("a valid rate"),
351 }
352 }
353
354 fn push(sender: &FrameSender<video::Frame>, micros: u64) {
355 let surface = video::Surface::rgba(&[0; 16], format().size).expect("2x2");
356 let timestamp = moq_net::Timestamp::from_micros(micros).expect("in range");
357 sender
358 .push(video::Frame::new(timestamp, surface))
359 .expect("open");
360 }
361
362 async fn next_micros(frames: &mut crate::VideoFrames) -> u64 {
363 tokio::time::timeout(TIMEOUT, frames.next())
364 .await
365 .expect("a frame in time")
366 .expect("the stream is open")
367 .timestamp
368 .as_micros()
369 .expect("a timed frame") as u64
370 }
371
372 async fn becomes(switch: &VideoSwitch, state: SlotState) {
373 let mut status = switch.status();
374 tokio::time::timeout(TIMEOUT, status.wait_for(|status| *status == state))
375 .await
376 .unwrap_or_else(|_| panic!("the switch never became {state:?}"))
377 .expect("the switch is alive");
378 }
379
380 #[tokio::test]
381 async fn a_replaced_source_takes_over_the_frames() {
382 let (switch, source) = VideoSource::switchable(format());
383 let mut frames = source.frames();
384 assert_eq!(*switch.status().borrow(), SlotState::Off);
385
386 let (first_sender, first) = VideoSource::push(format());
387 switch.replace(first);
388 assert_eq!(*switch.status().borrow(), SlotState::Running);
389 push(&first_sender, 1);
390 assert_eq!(next_micros(&mut frames).await, 1);
391
392 let (second_sender, second) = VideoSource::push(format());
393 switch.replace(second);
394 assert!(first_sender.is_closed(), "the replaced source was dropped");
395 push(&second_sender, 2);
396 assert_eq!(next_micros(&mut frames).await, 2);
397 }
398
399 #[tokio::test]
401 async fn a_replace_drops_the_last_frame_of_the_old_source() {
402 let (switch, source) = VideoSource::switchable(format());
403 let mut frames = source.frames();
404 let (first_sender, first) = VideoSource::push(format());
405 switch.replace(first);
406 push(&first_sender, 1);
407 assert_eq!(next_micros(&mut frames).await, 1);
408
409 let (second_sender, second) = VideoSource::push(format());
410 switch.replace(second);
411 assert!(frames.current().is_none(), "the old frame is still current");
412 assert!(frames.try_next().is_none(), "the old frame was delivered");
413 assert!(
414 source.frames().current().is_none(),
415 "a fresh handle sees the old frame"
416 );
417 push(&second_sender, 2);
418 assert_eq!(next_micros(&mut frames).await, 2);
419 }
420
421 #[tokio::test]
423 async fn an_open_drops_the_last_frame_of_the_old_source() {
424 let (switch, source) = VideoSource::switchable(format());
425 let mut frames = source.frames();
426 let (sender, first) = VideoSource::push(format());
427 switch.replace(first);
428 push(&sender, 1);
429 assert_eq!(next_micros(&mut frames).await, 1);
430 switch.open(std::future::pending());
431 assert!(frames.current().is_none());
432 assert!(frames.try_next().is_none());
433 }
434
435 #[tokio::test]
436 async fn a_forwarded_frame_keeps_its_send_instant() {
437 let (switch, source) = VideoSource::switchable(format());
438 let mut frames = source.frames();
439 let (sender, inner) = VideoSource::push(format());
440 let mut inner_frames = inner.frames();
441 switch.replace(inner);
442 push(&sender, 1);
443 next_micros(&mut inner_frames).await;
444 next_micros(&mut frames).await;
445 assert_eq!(frames.sent_at(), inner_frames.sent_at());
446 }
447
448 #[tokio::test]
450 async fn a_keyframe_request_reaches_only_the_current_input() {
451 let (switch, source) = VideoSource::switchable(format());
452 let mut frames = source.frames();
453 let (first_sender, first) = VideoSource::push(format());
454 switch.replace(first);
455 push(&first_sender, 1);
456 assert_eq!(next_micros(&mut frames).await, 1);
457 assert!(!frames.keyframe_requested());
458 first_sender.request_keyframe();
459 push(&first_sender, 2);
460 assert_eq!(next_micros(&mut frames).await, 2);
461 assert!(frames.keyframe_requested(), "the frame after the request");
462
463 first_sender.request_keyframe();
466 let (second_sender, second) = VideoSource::push(format());
467 switch.replace(second);
468 first_sender.request_keyframe();
469 push(&second_sender, 3);
470 assert_eq!(next_micros(&mut frames).await, 3);
471 assert!(!frames.keyframe_requested(), "a request of the old input");
472 }
473
474 #[tokio::test]
476 async fn the_switchable_source_passes_its_demand_on() {
477 let (switch, source) = VideoSource::switchable(format());
478 let (sender, inner) = VideoSource::push(format());
479 let mut demand = sender.demand();
480 switch.replace(inner);
481 let mut observed = source.observe();
482 push(&sender, 1);
483 assert_eq!(
484 next_micros(&mut observed).await,
485 1,
486 "the input is forwarded"
487 );
488 assert!(!*demand.borrow(), "the forwarding task wants the input");
489 let frames = source.frames();
490 tokio::time::timeout(TIMEOUT, demand.wait_for(|wanted| *wanted))
491 .await
492 .expect("the demand reached the source")
493 .expect("open");
494 drop(frames);
495 tokio::time::timeout(TIMEOUT, demand.wait_for(|wanted| !*wanted))
496 .await
497 .expect("the demand left the source")
498 .expect("open");
499 }
500
501 #[tokio::test]
502 async fn an_open_reports_starting_then_running() {
503 let (switch, source) = VideoSource::switchable(format());
504 let mut frames = source.frames();
505 let (opened_tx, opened_rx) = tokio::sync::oneshot::channel();
506 switch.open(async move { Ok(opened_rx.await.expect("sent")) });
507 becomes(&switch, SlotState::Starting).await;
508 let (sender, inner) = VideoSource::push(format());
509 opened_tx.send(inner).expect("the open waits");
510 becomes(&switch, SlotState::Running).await;
511 push(&sender, 3);
512 assert_eq!(next_micros(&mut frames).await, 3);
513 }
514
515 #[tokio::test]
516 async fn a_failed_open_reports_why() {
517 let (switch, _source) = VideoSource::switchable(format());
518 switch.open(async { Err(Error::device_msg("no such camera")) });
519 let mut status = switch.status();
520 let state = tokio::time::timeout(
521 TIMEOUT,
522 status.wait_for(|state| matches!(state, SlotState::Failed(_))),
523 )
524 .await
525 .expect("the open failed in time")
526 .expect("alive")
527 .clone();
528 let SlotState::Failed(err) = state else {
529 unreachable!()
530 };
531 assert!(matches!(*err, Error::Device { .. }));
532 }
533
534 #[tokio::test]
535 async fn a_newer_switch_drops_an_open_still_running() {
536 let (switch, _source) = VideoSource::switchable(format());
537 let (dropped_tx, dropped_rx) = tokio::sync::oneshot::channel::<()>();
538 switch.open(async move {
539 let _dropped = dropped_tx;
540 std::future::pending().await
541 });
542 becomes(&switch, SlotState::Starting).await;
543 let (_sender, inner) = VideoSource::push(format());
544 switch.replace(inner);
545 assert_eq!(*switch.status().borrow(), SlotState::Running);
546 tokio::time::timeout(TIMEOUT, dropped_rx)
547 .await
548 .expect("the open was dropped")
549 .expect_err("the open never finished");
550 switch.clear();
551 assert_eq!(*switch.status().borrow(), SlotState::Off);
552 }
553
554 #[tokio::test]
555 async fn a_source_that_ends_leaves_the_stream_open() {
556 let (switch, source) = VideoSource::switchable(format());
557 let mut frames = source.frames();
558 let (sender, inner) = VideoSource::push(format());
559 switch.replace(inner);
560 push(&sender, 1);
561 assert_eq!(next_micros(&mut frames).await, 1);
562 drop(sender);
563 becomes(&switch, SlotState::Ended).await;
564 assert_eq!(
565 frames.current().map(|frame| frame.timestamp.as_micros()),
566 Some(Ok(1)),
567 "the last frame stays"
568 );
569
570 let (sender, inner) = VideoSource::push(format());
571 switch.replace(inner);
572 push(&sender, 2);
573 assert_eq!(next_micros(&mut frames).await, 2);
574
575 drop(switch);
576 let ended =
577 tokio::time::timeout(TIMEOUT, async { while frames.next().await.is_some() {} }).await;
578 assert!(ended.is_ok(), "the stream outlived its switch");
579 assert!(sender.is_closed(), "the last source was dropped");
580 }
581
582 #[cfg(feature = "pattern")]
584 #[tokio::test]
585 async fn a_spec_opens_with_its_options_and_none_clears() {
586 let (switch, source) = VideoSource::switchable(format());
587 let mut frames = source.frames();
588 let options = VideoOpenOptions::default()
589 .with_size(video::Size::new(64, 48))
590 .with_framerate(video::FrameRate::new(30, 1).expect("a valid rate"));
591 switch.open_spec("test".parse().expect("a valid spec"), options.clone());
592 becomes(&switch, SlotState::Running).await;
593 let frame = tokio::time::timeout(TIMEOUT, frames.next())
594 .await
595 .expect("a frame in time")
596 .expect("the stream is open");
597 assert_eq!(frame.size(), video::Size::new(64, 48));
598
599 switch.open_spec(VideoSourceSpec::None, options);
600 assert_eq!(*switch.status().borrow(), SlotState::Off);
601 }
602}