Skip to main content

moq_ext_sources/source/
switch.rs

1//! A video source whose input the application swaps while it is published.
2//!
3//! [`VideoSource::switchable`] returns a source and its [`VideoSwitch`]. The
4//! source is an ordinary [`VideoSource`] over a latest-wins slot, so a broadcast
5//! encodes it once and a preview reads it, and neither sees a switch. The
6//! switch forwards the frames of whichever source is current into that slot,
7//! on one task per source, and passes the demand of its readers back to it.
8
9use 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/// The source that feeds a switch, and which install it belongs to.
28#[derive(Debug, Default)]
29struct Current {
30    /// Bumped by every install, so a superseded task leaves the slot alone.
31    generation: u64,
32    /// The source frames come from.
33    ///
34    /// Held here, not by the task, so a switch drops it at once and its device
35    /// is free for the next open.
36    source: Option<VideoSource>,
37}
38
39/// What a switch's forwarding tasks share with it.
40#[derive(Debug)]
41struct Shared {
42    slot: FrameSlot,
43    current: Mutex<Current>,
44    status: watch::Sender<SlotState>,
45    /// The demand on the switchable source, which the current source receives.
46    demand: Demand,
47    /// Cancelled once every handle to the switchable source is gone.
48    stop: CancellationToken,
49}
50
51impl Shared {
52    /// Runs `f` with the current source and status if install `generation` is still current.
53    ///
54    /// Returns `false` once a later install superseded it.
55    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/// The handle that swaps the input of a [`VideoSource::switchable`] source.
70///
71/// Each call supersedes the one before: [`replace`](Self::replace) and
72/// [`clear`](Self::clear) take effect at once, and [`open`](Self::open)
73/// cancels an open still running. The previous source is dropped before the
74/// next one opens, so the same camera can open again. [`replace`](Self::replace)
75/// and [`open`](Self::open) also drop the previous source's last frame, so no
76/// reader gets a frame of the old source once they return. After
77/// [`clear`](Self::clear) or the end of its source, the switchable source
78/// keeps its last frame. It ends when every switch is dropped. Cheap to clone.
79#[derive(Debug, Clone)]
80pub struct VideoSwitch {
81    shared: Arc<Shared>,
82    task: Arc<Mutex<Option<AbortOnDropHandle<()>>>>,
83}
84
85impl VideoSource {
86    /// Returns a source whose input the returned [`VideoSwitch`] swaps.
87    ///
88    /// Publish the source once, and switch cameras, screens or test patterns
89    /// behind it without touching the broadcast: its encoders keep running, and
90    /// its subscribers keep their tracks. A broadcast anchors each new
91    /// source's timestamps at its clock again and starts a group there, so the
92    /// new picture starts with a keyframe. `format` describes the frames the
93    /// switch carries, as for [`push`](Self::push), and a frame of another size
94    /// is scaled to the rendition's.
95    ///
96    /// The source reports the switch's state in [`VideoSwitch::status`] and
97    /// starts [`Off`](SlotState::Off), with no frames until a source is set.
98    ///
99    /// # Examples
100    ///
101    /// ```no_run
102    /// # async fn example(format: moq_ext_sources::VideoFormat, size: moq_video::Size, rate: moq_video::FrameRate) -> Result<(), moq_ext_sources::Error> {
103    /// use moq_ext_sources::VideoSource;
104    ///
105    /// let (switch, source) = VideoSource::switchable(format);
106    /// // Hand `source` to a broadcast once, then switch behind it.
107    /// switch.replace(VideoSource::test_pattern(size, rate)?);
108    /// switch.open(VideoSource::capture(Default::default()));
109    /// # let _ = source;
110    /// # Ok(())
111    /// # }
112    /// ```
113    #[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    /// Feeds the switchable source from `source`, from its current frame on.
140    ///
141    /// The previous source's last frame is dropped before this returns. The
142    /// status becomes [`Running`](SlotState::Running), and
143    /// [`Ended`](SlotState::Ended) or [`Failed`](SlotState::Failed) when
144    /// `source` stops.
145    ///
146    /// # Panics
147    ///
148    /// Panics when called outside a Tokio runtime.
149    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    /// Opens a source with `open` in the background and feeds the switchable source from it.
155    ///
156    /// The current source is dropped first, so `open` can open the same
157    /// device again. The status reads [`Starting`](SlotState::Starting) while
158    /// `open` runs, then [`Running`](SlotState::Running), or
159    /// [`Failed`](SlotState::Failed) with its error. A later call to any
160    /// method drops `open` unfinished, which for
161    /// [`VideoSource::capture`] releases the device.
162    ///
163    /// # Panics
164    ///
165    /// Panics when called outside a Tokio runtime.
166    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    /// Opens `spec` with `options` behind the switch, or clears it for [`VideoSourceSpec::None`].
198    ///
199    /// The open runs in the background as with [`open`](Self::open), so a
200    /// source picker hands its choice over in one call.
201    ///
202    /// # Panics
203    ///
204    /// Panics when called outside a Tokio runtime.
205    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    /// Stops feeding the switchable source and drops the current source.
218    ///
219    /// The status becomes [`Off`](SlotState::Off). The switchable source keeps
220    /// its last frame and does not end.
221    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    /// Returns a receiver of the switch's state.
229    #[must_use]
230    pub fn status(&self) -> watch::Receiver<SlotState> {
231        self.shared.status.subscribe()
232    }
233
234    /// Starts a new install with `source` and `state`.
235    ///
236    /// Returns the new install's generation and the source it dropped.
237    ///
238    /// The slot is cleared under the same lock the forwarding tasks write
239    /// through, so a superseded task cannot send a frame after it.
240    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    /// Starts a new install with `source` and `state`, and spawns the task `run` returns for it.
257    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        // Dropped before the next open runs, so its device is free.
265        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/// What a new install does with the frame the switchable source shows.
274#[derive(Debug, Clone, Copy, PartialEq, Eq)]
275enum LastFrame {
276    /// Keeps it, for a switch that stops feeding the source.
277    Keep,
278    /// Drops it, for a switch to another source.
279    Drop,
280}
281
282/// Forwards the frames of install `generation`'s source into the switchable source.
283///
284/// Holds demand on the source while the switchable source has some. Returns
285/// once the source ends, a later install supersedes it, or the switchable
286/// source is gone.
287async fn forward(shared: Arc<Shared>, generation: u64) {
288    let mut frames = None;
289    shared.if_current(generation, |current, _| {
290        // Observed, so the input is wanted only while the switchable source is.
291        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    /// No frame of the old source reaches a reader once `replace` returns.
400    #[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    /// An open drops the old frame at once, before the new source has opened.
422    #[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    /// A keyframe request on the current input marks the next frame, and one on a replaced input does not.
449    #[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        // Neither a request the old input never pushed a frame after, nor one
464        // made once it was replaced, reaches the output.
465        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    /// A reader of the switchable source wants the input's frames, and nothing else does.
475    #[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    /// A spec opens at the size the options ask for, and the `none` spec clears the switch.
583    #[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}