Skip to main content

moq_ext_player/
remote.rs

1//! Remote broadcasts: a catalog and a subscription, not yet playing.
2
3use std::{
4    sync::{Arc, Mutex},
5    time::Duration,
6};
7
8use hang::catalog::Catalog;
9use moq_ext_sources::Error;
10use moq_mux::catalog::Stream as _;
11use n0_future::{Stream, StreamExt as _, task::AbortOnDropHandle};
12use tokio::sync::watch;
13use tokio_util::sync::CancellationToken;
14use tracing::{Instrument, Span, debug, info, info_span, trace, warn};
15
16use crate::{
17    NetworkSample, Player, PlayerConfig, clean_close::CleanClose as _, network::NetworkSignals,
18};
19
20/// How long to look for an ended broadcast again before it counts as gone.
21///
22/// After a change of route, the next request finds the broadcast at once. A
23/// longer wait means the publisher left.
24const REROUTE_PATIENCE: Duration = Duration::from_secs(3);
25
26/// The first wait before asking again for a catalog track that is not there yet.
27///
28/// Doubles per attempt, up to [`CATALOG_RETRY_MAX`].
29const CATALOG_RETRY: Duration = Duration::from_millis(50);
30
31/// The longest wait between two requests for a catalog track that is not there yet.
32const CATALOG_RETRY_MAX: Duration = Duration::from_secs(2);
33
34/// The broadcast consumer a player reads, and how many times it has changed.
35#[derive(derive_more::Debug, Clone, Default)]
36pub(crate) struct Epoch {
37    /// Counts the consumers handed out so far, so a reader sees a new route.
38    pub(crate) generation: u64,
39    /// The consumer to read, or `None` while waiting for a route and after the end.
40    #[debug(skip)]
41    pub(crate) consumer: Option<moq_net::broadcast::Consumer>,
42}
43
44/// The consumers a [`RemoteBroadcast::from_consumers`] reads, in turn.
45type Feed = n0_future::boxed::BoxStream<moq_net::broadcast::Consumer>;
46
47/// Where a remote broadcast comes from.
48#[derive(Clone)]
49enum Origin {
50    /// Consumers handed in, one or a [`Feed`] of them, with no route table to ask.
51    Consumer,
52    /// A path in a route table, requested again when a change of route ends it.
53    Routed {
54        /// Boxed: a route table consumer is large.
55        origin: Box<moq_net::origin::Consumer>,
56        path: moq_net::Path,
57    },
58}
59
60/// The state every clone of a [`RemoteBroadcast`] shares.
61#[derive(derive_more::Debug)]
62struct Shared {
63    #[debug(skip)]
64    #[cfg_attr(
65        not(feature = "record"),
66        allow(dead_code, reason = "only a moq-mux source asks for the route table")
67    )]
68    origin: Origin,
69    /// The empty route table of a moq-mux source over a bare consumer.
70    #[cfg(feature = "record")]
71    #[debug(skip)]
72    local: std::sync::OnceLock<LocalOrigin>,
73    #[debug("{:?}", epoch.borrow())]
74    epoch: watch::Sender<Epoch>,
75    #[debug(skip)]
76    catalog: watch::Sender<Option<Arc<Catalog>>>,
77    /// Whether the publisher answered that it has no catalog track.
78    #[debug(skip)]
79    catalog_missing: watch::Sender<bool>,
80    closed: CancellationToken,
81    #[debug(skip)]
82    network: Mutex<Option<NetworkSignals>>,
83    span: Span,
84    #[debug(skip)]
85    _task: AbortOnDropHandle<()>,
86}
87
88/// A broadcast being read.
89///
90/// Cheap to clone. Holding it keeps the broadcast subscription open, and any
91/// number of [`Player`]s and recordings can read it. Constructing one spawns a
92/// task, so it must happen inside a Tokio runtime.
93#[derive(Debug, Clone)]
94pub struct RemoteBroadcast {
95    shared: Arc<Shared>,
96}
97
98impl RemoteBroadcast {
99    /// Starts reading the catalog of `broadcast`.
100    ///
101    /// The remote broadcast ends when `broadcast` ends. A broadcast published
102    /// in the same process reads through [`from_local`](Self::from_local).
103    ///
104    /// # Panics
105    ///
106    /// Panics when called outside a Tokio runtime.
107    #[must_use]
108    pub fn from_consumer(broadcast: moq_net::broadcast::Consumer) -> Self {
109        let span = info_span!("remote");
110        Self::spawn(Origin::Consumer, Some(broadcast), None, span)
111    }
112
113    /// Starts reading the catalog of `broadcast`, published in this process.
114    ///
115    /// Plays what an application sends, without a transport, such as a
116    /// preview of its own camera with sound. Takes anything that hands out
117    /// consumers of its broadcast, such as a `LocalBroadcast` of
118    /// moq-ext-publisher. The remote broadcast ends when `broadcast` closes.
119    /// The same as [`from_consumer`](Self::from_consumer) with
120    /// [`consume`](moq_net::Consume::consume).
121    ///
122    /// # Panics
123    ///
124    /// Panics when called outside a Tokio runtime.
125    #[must_use]
126    pub fn from_local(broadcast: &impl moq_net::Consume<moq_net::broadcast::Consumer>) -> Self {
127        Self::from_consumer(broadcast.consume())
128    }
129
130    /// Reads each broadcast `consumers` yields, in turn.
131    ///
132    /// Players switch to each new consumer as it arrives, and wait through
133    /// the gap after one ends, so a transport can hand in what serves the
134    /// broadcast now, such as a new subscription after a restarted publisher
135    /// or a failed session. The remote broadcast closes once `consumers` ends.
136    ///
137    /// # Panics
138    ///
139    /// Panics when called outside a Tokio runtime.
140    #[must_use]
141    pub fn from_consumers(
142        consumers: impl Stream<Item = moq_net::broadcast::Consumer> + Send + 'static,
143    ) -> Self {
144        let span = info_span!("remote");
145        Self::spawn(Origin::Consumer, None, Some(Box::pin(consumers)), span)
146    }
147
148    /// Follows `path` in a route table, starting from a resolved `broadcast`.
149    ///
150    /// When a change of route ends the broadcast, it is requested again through
151    /// the next route, and players see a switch instead of an end.
152    /// [`closed`](Self::closed) explains when a publisher counts as gone.
153    /// `iroh-live` uses this on subscribe.
154    ///
155    /// # Panics
156    ///
157    /// Panics when called outside a Tokio runtime.
158    #[must_use]
159    pub fn from_resolved(
160        origin: moq_net::origin::Consumer,
161        path: moq_net::Path,
162        broadcast: moq_net::broadcast::Consumer,
163    ) -> Self {
164        Self::routed_to(origin, path, Some(broadcast))
165    }
166
167    /// Follows `path` in a route table, from `first` if given.
168    ///
169    /// Without `first`, the first request waits without limit.
170    fn routed_to(
171        origin: moq_net::origin::Consumer,
172        path: moq_net::Path,
173        first: Option<moq_net::broadcast::Consumer>,
174    ) -> Self {
175        let span = info_span!("remote", path = %path);
176        Self::spawn(
177            Origin::Routed {
178                origin: Box::new(origin),
179                path,
180            },
181            first,
182            None,
183            span,
184        )
185    }
186
187    /// Attaches network signals for automatic rendition selection.
188    ///
189    /// `signals` returns the link as it is now. Players call it a few times a
190    /// second and on every [`Player::stats`], so it must not block. The
191    /// signals belong to the broadcast: every clone sees them, and attaching
192    /// again replaces them. Players started afterwards use them.
193    pub fn set_network(&self, signals: impl Fn() -> NetworkSample + Send + Sync + 'static) {
194        *self.shared.network.lock().expect("poisoned") = Some(Arc::new(signals));
195    }
196
197    /// Returns a receiver for the catalog, `None` until the first arrives.
198    ///
199    /// A publisher may announce its broadcast before it creates the catalog
200    /// track. The catalog is then asked for again, with a growing wait, until
201    /// it appears or the broadcast closes.
202    ///
203    /// A borrow of the receiver blocks the next catalog update, so keep it
204    /// short.
205    #[must_use]
206    pub fn catalog(&self) -> watch::Receiver<Option<Arc<Catalog>>> {
207        self.shared.catalog.subscribe()
208    }
209
210    /// Returns a receiver that is `true` while the publisher answers that it has no catalog track.
211    ///
212    /// Such a broadcast carries no media, for example one that holds only
213    /// JSON values. The catalog is still asked for again, since a publisher
214    /// may create the track after it announced the broadcast, and the
215    /// receiver turns `false` once the track appears or another consumer
216    /// takes the broadcast over.
217    #[must_use]
218    pub fn catalog_missing(&self) -> watch::Receiver<bool> {
219        self.shared.catalog_missing.subscribe()
220    }
221
222    /// Waits for the first catalog, at most `timeout`.
223    ///
224    /// Cancellation safe.
225    ///
226    /// # Errors
227    ///
228    /// Fails with [`Error::Closed`] if the broadcast closes first, and with
229    /// [`Error::Catalog`] if no catalog this build can read arrives in time.
230    pub async fn catalog_within(&self, timeout: Duration) -> Result<Arc<Catalog>, Error> {
231        let mut catalog = self.catalog();
232        let first = async {
233            // A broadcast that closes sends no catalog update to wake on.
234            tokio::select! {
235                catalog = catalog.wait_for(Option::is_some) => catalog.ok().and_then(|catalog| catalog.clone()),
236                () = self.closed() => None,
237            }
238        };
239        match tokio::time::timeout(timeout, first).await {
240            Ok(Some(catalog)) => Ok(catalog),
241            Ok(None) => Err(n0_error::e!(Error::Closed)),
242            Err(_) => Err(Error::catalog_msg(format!(
243                "the broadcast sent no catalog within {}s, or sent one this build could not read",
244                timeout.as_secs()
245            ))),
246        }
247    }
248
249    /// Starts one playback of the broadcast.
250    ///
251    /// # Errors
252    ///
253    /// Fails for an invalid config: a latency whose minimum is above its
254    /// maximum.
255    pub fn play(&self, config: PlayerConfig) -> Result<Player, Error> {
256        Player::start(self.clone(), config)
257    }
258
259    /// Returns a [`moq_mux::Source`] of the current route, for a moq-mux export.
260    ///
261    /// Waits until the broadcast has a route and a catalog, since an exporter's
262    /// catalog reader does not ask again for a catalog track that is not there
263    /// yet. The source reads one route, so a change of route ends the exports
264    /// that read it. One of a broadcast from [`from_resolved`](Self::from_resolved)
265    /// resolves sibling broadcasts through the route table.
266    ///
267    /// Recording composes this with moq-mux's fragmented MP4 or Matroska
268    /// export, which remuxes without decoding:
269    ///
270    /// ```no_run
271    /// # async fn example(
272    /// #     broadcast: moq_ext_player::RemoteBroadcast,
273    /// # ) -> Result<(), Box<dyn std::error::Error>> {
274    /// use moq_mux::{catalog::Stream as _, container::fmp4};
275    /// use tokio::io::AsyncWriteExt as _;
276    ///
277    /// let source = broadcast.mux_source().await?;
278    /// let catalog = moq_mux::catalog::Consumer::<()>::new(&source.broadcast(), Default::default())
279    ///     .await?
280    ///     .select(moq_mux::select::Broadcast::default());
281    /// let mut export = fmp4::Export::new(source, catalog);
282    /// let mut file = tokio::fs::File::create("out.mp4").await?;
283    /// while let Some(chunk) = export.next().await? {
284    ///     file.write_all(&chunk).await?;
285    /// }
286    /// # Ok(())
287    /// # }
288    /// ```
289    ///
290    /// Cancellation safe.
291    ///
292    /// # Errors
293    ///
294    /// Fails with [`Error::Closed`] if the broadcast closes first.
295    #[cfg(feature = "record")]
296    pub async fn mux_source(&self) -> Result<moq_mux::Source, Error> {
297        // The broadcast held here keeps the watch senders alive, so only
298        // `closed` ends a wait on a broadcast that is gone.
299        let mut epoch = self.epoch();
300        let consumer = tokio::select! {
301            epoch = epoch.wait_for(|epoch| epoch.consumer.is_some()) => {
302                epoch.ok().and_then(|epoch| epoch.consumer.clone())
303            }
304            () = self.closed() => None,
305        };
306        let consumer = consumer.ok_or_else(|| n0_error::e!(Error::Closed))?;
307        let mut catalog = self.catalog();
308        let known = tokio::select! {
309            seen = catalog.wait_for(Option::is_some) => seen.is_ok(),
310            () = self.closed() => false,
311        };
312        if !known {
313            return Err(n0_error::e!(Error::Closed));
314        }
315        let origin = match &self.shared.origin {
316            Origin::Routed { origin, .. } => origin.as_ref().clone(),
317            Origin::Consumer => self.shared.local.get_or_init(LocalOrigin::new).consume(),
318        };
319        Ok(moq_mux::Source::new(origin, consumer))
320    }
321
322    /// Waits until the broadcast has closed.
323    ///
324    /// A broadcast read with [`from_consumer`](Self::from_consumer) closes when
325    /// its consumer does. One that follows a route table, from
326    /// [`from_resolved`](Self::from_resolved), cannot tell a publisher that
327    /// left from a change of route. It asks the table again and closes once no
328    /// route has answered for three seconds. So a hang-up shows here about
329    /// three seconds late.
330    ///
331    /// Cancellation safe.
332    pub async fn closed(&self) {
333        self.shared.closed.cancelled().await;
334    }
335
336    /// Reports whether the broadcast has closed.
337    ///
338    /// Lags a routed publisher's hang-up by the same three seconds as
339    /// [`closed`](Self::closed).
340    #[must_use]
341    pub fn is_closed(&self) -> bool {
342        self.shared.closed.is_cancelled()
343    }
344
345    /// Returns a receiver for the consumer players read, and its generation.
346    pub(crate) fn epoch(&self) -> watch::Receiver<Epoch> {
347        self.shared.epoch.subscribe()
348    }
349
350    /// Returns the network signals, if a transport attached any.
351    pub(crate) fn network(&self) -> Option<NetworkSignals> {
352        self.shared.network.lock().expect("poisoned").clone()
353    }
354
355    /// Returns the span everything reading this broadcast logs under.
356    pub(crate) fn span(&self) -> &Span {
357        &self.shared.span
358    }
359
360    fn spawn(
361        origin: Origin,
362        first: Option<moq_net::broadcast::Consumer>,
363        feed: Option<Feed>,
364        span: Span,
365    ) -> Self {
366        let epoch = watch::Sender::new(Epoch::default());
367        let catalog = watch::Sender::new(None);
368        let catalog_missing = watch::Sender::new(false);
369        let closed = CancellationToken::new();
370        let task = {
371            let origin = origin.clone();
372            let epoch = epoch.clone();
373            let catalogs = Catalogs {
374                catalog: catalog.clone(),
375                missing: catalog_missing.clone(),
376            };
377            let closed = closed.clone();
378            n0_future::task::spawn(
379                follow(origin, first, feed, epoch, catalogs, closed).instrument(span.clone()),
380            )
381        };
382        Self {
383            shared: Arc::new(Shared {
384                origin,
385                epoch,
386                catalog,
387                catalog_missing,
388                closed,
389                #[cfg(feature = "record")]
390                local: std::sync::OnceLock::new(),
391                network: Mutex::new(None),
392                span,
393                _task: AbortOnDropHandle::new(task),
394            }),
395        }
396    }
397}
398
399/// An empty route table with the task that drives it.
400///
401/// A moq-mux source resolves sibling broadcasts through a route table, and a
402/// bare consumer has none.
403#[cfg(feature = "record")]
404struct LocalOrigin {
405    origin: moq_net::origin::Producer,
406    _driver: AbortOnDropHandle<()>,
407}
408
409#[cfg(feature = "record")]
410impl LocalOrigin {
411    fn new() -> Self {
412        let (origin, driver) = moq_net::origin::Producer::new(moq_net::origin::Config::default());
413        let driver = n0_future::task::spawn(async move {
414            let err = moq_net::time::run(driver).await;
415            debug!(error = %err, "the moq-mux source's route table stopped");
416        });
417        Self {
418            origin,
419            _driver: AbortOnDropHandle::new(driver),
420        }
421    }
422
423    fn consume(&self) -> moq_net::origin::Consumer {
424        self.origin.consume()
425    }
426}
427
428/// Reads the broadcast, requesting it again when a change of route ends it.
429///
430/// With a `feed`, reads each consumer it yields instead, and ends with it.
431async fn follow(
432    origin: Origin,
433    first: Option<moq_net::broadcast::Consumer>,
434    mut feed: Option<Feed>,
435    epoch: watch::Sender<Epoch>,
436    catalogs: Catalogs,
437    closed: CancellationToken,
438) {
439    let mut generation = 0u64;
440    let mut next = first;
441    let mut routes = match &origin {
442        Origin::Consumer => None,
443        Origin::Routed { origin, path } => match origin.follow(path.clone(), None) {
444            Ok(routes) => Some(routes),
445            Err(err) => {
446                info!(error = %err, "the broadcast cannot be followed");
447                None
448            }
449        },
450    };
451    if let (Some(_), Some(routes)) = (&next, &mut routes) {
452        // The caller resolved the first broadcast already, and the table's first
453        // answer names it again. Take that answer here, so it does not count as
454        // a change of route.
455        let _ = tokio::time::timeout(REROUTE_PATIENCE, routes.available()).await;
456    }
457    loop {
458        let consumer = match next.take() {
459            Some(consumer) => consumer,
460            None => match (&mut routes, &mut feed) {
461                (None, None) => break,
462                (None, Some(feed)) => match feed.next().await {
463                    Some(consumer) => consumer,
464                    None => {
465                        debug!("the feed of consumers ended");
466                        break;
467                    }
468                },
469                (Some(routes), _) => {
470                    // The publisher may not have announced yet, so only a
471                    // failover has a time limit.
472                    let resolved = match generation {
473                        0 => routes.available().await,
474                        _ => match tokio::time::timeout(REROUTE_PATIENCE, routes.available()).await
475                        {
476                            Ok(resolved) => resolved,
477                            Err(_) => {
478                                info!("no route serves the broadcast any more");
479                                break;
480                            }
481                        },
482                    };
483                    match resolved {
484                        Ok(Some(consumer)) => consumer,
485                        // The path went offline: wait for whatever serves it next.
486                        Ok(None) => continue,
487                        Err(err) => {
488                            info!(error = %err, "the broadcast cannot be resolved");
489                            break;
490                        }
491                    }
492                }
493            },
494        };
495        generation += 1;
496        if generation > 1 {
497            info!(generation, "the broadcast came back through another route");
498        }
499        epoch.send_replace(Epoch {
500            generation,
501            consumer: Some(consumer.clone()),
502        });
503        // When another instance takes the path over, this broadcast stays open
504        // until its own routes go, and its stream may already be dead to the
505        // publisher. Switch as soon as the table names the new instance. An error,
506        // or `None` for a path that went offline, disables this arm, and the
507        // broadcast's own end drives the loop. A feed switches to each consumer
508        // it yields, and its end, `Some(None)` here, ends the broadcast.
509        let taken_over = async {
510            match (&mut routes, &mut feed) {
511                (Some(routes), _) => routes.available().await.ok().flatten().map(Some),
512                (None, Some(feed)) => Some(feed.next().await),
513                (None, None) => std::future::pending().await,
514            }
515        };
516        tokio::select! {
517            Some(taken) = taken_over => match taken {
518                Some(taken) => {
519                    debug!("another consumer took the broadcast over");
520                    next = Some(taken);
521                }
522                None => {
523                    debug!("the feed of consumers ended");
524                    break;
525                }
526            },
527            _ = async {
528                read_catalog(&consumer, &catalogs).await;
529                consumer.closed().await;
530            } => debug!("the broadcast ended"),
531        }
532    }
533    epoch.send_replace(Epoch {
534        generation: generation + 1,
535        consumer: None,
536    });
537    closed.cancel();
538}
539
540/// Where [`read_catalog`] reports what it finds.
541struct Catalogs {
542    /// The newest catalog.
543    catalog: watch::Sender<Option<Arc<Catalog>>>,
544    /// Whether the publisher answered that it has no catalog track.
545    missing: watch::Sender<bool>,
546}
547
548/// Reads catalog updates into `catalogs` until the catalog track ends, and reports a missing one.
549///
550/// Asks again for a catalog track that is not there yet, as
551/// [`RemoteBroadcast::catalog`] describes. Cancellation safe.
552async fn read_catalog(consumer: &moq_net::broadcast::Consumer, catalogs: &Catalogs) {
553    let Catalogs { catalog, missing } = catalogs;
554    missing.send_if_modified(|missing| std::mem::replace(missing, false));
555    let mut retry = CATALOG_RETRY;
556    let mut reader = loop {
557        match moq_mux::catalog::Consumer::<()>::new(consumer, Default::default()).await {
558            Ok(reader) => {
559                missing.send_if_modified(|missing| std::mem::replace(missing, false));
560                break reader;
561            }
562            // A local origin answers `NotFound`. A peer's answer arrives as a
563            // stream error.
564            Err(moq_mux::Error::Moq(
565                moq_net::Error::NotFound | moq_net::Error::Stream(moq_net::StreamError::NotFound),
566            )) => {
567                debug!(?retry, "no catalog track yet, asking again");
568                missing.send_if_modified(|missing| !std::mem::replace(missing, true));
569                tokio::select! {
570                    () = tokio::time::sleep(retry) => {}
571                    () = consumer.closed() => {
572                        debug!("the broadcast closed before its catalog appeared");
573                        return;
574                    }
575                }
576                retry = (retry * 2).min(CATALOG_RETRY_MAX);
577            }
578            Err(err) if err.is_clean_close() => {
579                debug!(error = %err, "the catalog track closed before it was read");
580                return;
581            }
582            Err(err) => {
583                warn!(error = %err, "the catalog track could not be read");
584                return;
585            }
586        }
587    };
588    loop {
589        match reader.next().await {
590            Ok(Some(next)) => {
591                trace!(catalog = ?next.value, "catalog updated");
592                catalog.send_replace(Some(Arc::new(next.value)));
593            }
594            Ok(None) => {
595                debug!("catalog track ended");
596                return;
597            }
598            Err(err) if err.is_clean_close() => {
599                debug!(error = %err, "catalog track closed");
600                return;
601            }
602            Err(err) => {
603                warn!(error = %err, "catalog track failed");
604                return;
605            }
606        }
607    }
608}
609
610#[cfg(test)]
611mod tests {
612    use moq_net::{Identity, origin::RouteOptions};
613
614    use super::*;
615
616    /// A broadcast that closes before it has a catalog ends the wait for a moq-mux source.
617    #[cfg(feature = "record")]
618    #[tokio::test]
619    async fn a_close_before_the_catalog_ends_the_mux_source_wait() {
620        let producer = moq_net::broadcast::Info::new().produce();
621        let remote = RemoteBroadcast::from_consumer(producer.consume());
622        let source = remote.mux_source();
623        let close = async {
624            // Long enough for the source to wait on the catalog.
625            tokio::time::sleep(Duration::from_millis(200)).await;
626            producer.close();
627        };
628        let (result, ()) = tokio::time::timeout(Duration::from_secs(5), async {
629            tokio::join!(source, close)
630        })
631        .await
632        .expect("the wait ended with the broadcast");
633        assert!(matches!(result, Err(Error::Closed { .. })));
634    }
635
636    #[tokio::test]
637    async fn a_catalog_wait_ends_on_timeout_and_on_close() {
638        let producer = moq_net::broadcast::Info::new().produce();
639        let remote = RemoteBroadcast::from_consumer(producer.consume());
640        let waited = remote.catalog_within(Duration::from_millis(100)).await;
641        assert!(matches!(waited, Err(Error::Catalog { .. })), "{waited:?}");
642        drop(producer);
643        let closed = remote.catalog_within(Duration::from_secs(10)).await;
644        assert!(matches!(closed, Err(Error::Closed { .. })), "{closed:?}");
645    }
646
647    /// A broadcast that describes itself ends the wait with its catalog.
648    #[tokio::test]
649    async fn a_catalog_wait_returns_the_first_catalog() {
650        let broadcast = moq_ext_publisher::LocalBroadcast::new();
651        let remote = RemoteBroadcast::from_local(&broadcast);
652        broadcast
653            .set_video(
654                moq_ext_sources::VideoSource::test_pattern(
655                    moq_video::Size::new(320, 180),
656                    moq_video::FrameRate::new(30, 1).expect("a valid rate"),
657                )
658                .expect("the pattern thread starts"),
659                crate::test_util::single(None),
660            )
661            .expect("a valid encoding");
662        let catalog = remote
663            .catalog_within(Duration::from_secs(10))
664            .await
665            .expect("a catalog");
666        assert!(
667            catalog.video.renditions.contains_key("video"),
668            "{catalog:?}"
669        );
670        // A later wait returns at once with what the remote holds.
671        let again = remote
672            .catalog_within(Duration::from_millis(1))
673            .await
674            .expect("the catalog is held");
675        assert!(again.video.renditions.contains_key("video"));
676    }
677
678    /// A catalog track created after the broadcast is read is still found, and counts as missing until then.
679    #[tokio::test]
680    async fn a_catalog_created_late_is_read() {
681        let producer = moq_net::broadcast::Info::new().produce();
682        let remote = RemoteBroadcast::from_consumer(producer.consume());
683        // Long enough for the first request to find no catalog.
684        tokio::time::sleep(Duration::from_millis(200)).await;
685        assert!(remote.catalog().borrow().is_none());
686        let mut missing = remote.catalog_missing();
687        assert!(
688            *missing.borrow(),
689            "the missing catalog track was not reported"
690        );
691
692        let broadcast =
693            moq_ext_publisher::LocalBroadcast::new_in(producer).expect("no catalog yet");
694        // An empty catalog is written once there is media to describe.
695        broadcast
696            .set_video(
697                moq_ext_sources::VideoSource::test_pattern(
698                    moq_video::Size::new(320, 180),
699                    moq_video::FrameRate::new(30, 1).expect("a valid rate"),
700                )
701                .expect("the pattern thread starts"),
702                crate::test_util::single(None),
703            )
704            .expect("a valid encoding");
705        let mut catalog = remote.catalog();
706        tokio::time::timeout(Duration::from_secs(5), catalog.wait_for(Option::is_some))
707            .await
708            .expect("the late catalog was read")
709            .expect("the remote is alive");
710        assert!(
711            !*missing.borrow_and_update(),
712            "the catalog still counts as missing"
713        );
714    }
715
716    /// A broadcast that closes while its catalog is awaited closes its remote.
717    #[tokio::test]
718    async fn a_broadcast_closed_before_its_catalog_closes_its_remote() {
719        let producer = moq_net::broadcast::Info::new().produce();
720        let remote = RemoteBroadcast::from_consumer(producer.consume());
721        tokio::time::sleep(Duration::from_millis(200)).await;
722        producer.close();
723        tokio::time::timeout(Duration::from_secs(5), remote.closed())
724            .await
725            .expect("the remote saw the close");
726    }
727
728    #[tokio::test]
729    async fn a_closed_local_broadcast_closes_its_remote() {
730        let broadcast = moq_ext_publisher::LocalBroadcast::new();
731        let remote = RemoteBroadcast::from_local(&broadcast);
732        broadcast.close();
733        tokio::time::timeout(Duration::from_secs(5), remote.closed())
734            .await
735            .expect("the remote saw the close");
736        assert!(remote.is_closed());
737    }
738
739    /// A resolved broadcast closes once its publisher is gone.
740    #[tokio::test]
741    async fn a_resolved_broadcast_closes_once_its_route_is_gone() {
742        let (origin, driver) = moq_net::origin::Producer::new(Default::default());
743        let _driver = AbortOnDropHandle::new(n0_future::task::spawn(moq_net::time::run(driver)));
744        let published = origin
745            .route("live/cam", RouteOptions::default())
746            .expect("published");
747        let consumer = origin
748            .consume()
749            .request("live/cam", None)
750            .await
751            .expect("resolved");
752        // The publisher leaves before the remote broadcast starts.
753        drop(published);
754        let remote = RemoteBroadcast::from_resolved(
755            origin.consume(),
756            moq_net::Path::new("live/cam").expect("a valid path"),
757            consumer,
758        );
759        tokio::time::timeout(REROUTE_PATIENCE + Duration::from_secs(5), remote.closed())
760            .await
761            .expect("the remote closed within its re-resolve window");
762    }
763
764    /// A new instance taking the path over switches players at once.
765    ///
766    /// The old instance still serves its readers meanwhile.
767    #[tokio::test]
768    async fn a_takeover_switches_while_the_old_instance_lives() {
769        let (origin, driver) = moq_net::origin::Producer::new(Default::default());
770        let _driver = AbortOnDropHandle::new(n0_future::task::spawn(moq_net::time::run(driver)));
771        let _first = origin
772            .route(
773                "live/cam",
774                RouteOptions::default().with_identity(Identity::random(), 1),
775            )
776            .expect("published");
777        let remote = RemoteBroadcast::routed_to(
778            origin.consume(),
779            moq_net::Path::new("live/cam").expect("a valid path"),
780            None,
781        );
782        let mut epoch = remote.epoch();
783        let seen = tokio::time::timeout(
784            Duration::from_secs(5),
785            epoch.wait_for(|epoch| epoch.consumer.is_some()),
786        )
787        .await
788        .expect("the broadcast resolved")
789        .expect("epochs keep coming")
790        .generation;
791
792        let _second = origin
793            .route(
794                "live/cam",
795                RouteOptions::default().with_identity(Identity::random(), 2),
796            )
797            .expect("published again");
798        tokio::time::timeout(
799            Duration::from_secs(5),
800            epoch.wait_for(|epoch| epoch.generation > seen && epoch.consumer.is_some()),
801        )
802        .await
803        .expect("players switched to the new instance")
804        .expect("epochs keep coming");
805        assert!(!remote.is_closed());
806    }
807
808    /// A change of route gives players a new epoch instead of a close.
809    #[tokio::test]
810    async fn a_routed_broadcast_survives_a_change_of_route() {
811        let (origin, driver) = moq_net::origin::Producer::new(Default::default());
812        let _driver = AbortOnDropHandle::new(n0_future::task::spawn(moq_net::time::run(driver)));
813        let first = origin
814            .route("live/cam", RouteOptions::default())
815            .expect("published");
816        let remote = RemoteBroadcast::routed_to(
817            origin.consume(),
818            moq_net::Path::new("live/cam").expect("a valid path"),
819            None,
820        );
821        let mut epoch = remote.epoch();
822        let seen = tokio::time::timeout(
823            Duration::from_secs(5),
824            epoch.wait_for(|epoch| epoch.consumer.is_some()),
825        )
826        .await
827        .expect("the broadcast resolved")
828        .expect("epochs keep coming")
829        .generation;
830
831        // The first route goes, and another takes the path.
832        drop(first);
833        let _second = origin
834            .route("live/cam", RouteOptions::default())
835            .expect("published again");
836        let next = tokio::time::timeout(
837            Duration::from_secs(5),
838            epoch.wait_for(|epoch| epoch.generation > seen && epoch.consumer.is_some()),
839        )
840        .await
841        .expect("the broadcast was requested again")
842        .expect("epochs keep coming")
843        .generation;
844        assert!(next > seen);
845        assert!(!remote.is_closed());
846    }
847
848    /// A fed broadcast waits through the gap after a consumer ends, and closes with its feed.
849    #[tokio::test]
850    async fn a_fed_broadcast_switches_consumers_and_closes_with_the_feed() {
851        let (feed, consumers) = tokio::sync::mpsc::channel(1);
852        let remote = RemoteBroadcast::from_consumers(n0_future::stream::unfold(
853            consumers,
854            |mut consumers| async move { Some((consumers.recv().await?, consumers)) },
855        ));
856        let first = moq_net::broadcast::Info::new().produce();
857        feed.send(first.consume()).await.expect("the remote reads");
858        let mut epoch = remote.epoch();
859        let seen = tokio::time::timeout(
860            Duration::from_secs(5),
861            epoch.wait_for(|epoch| epoch.consumer.is_some()),
862        )
863        .await
864        .expect("the first consumer was read")
865        .expect("epochs keep coming")
866        .generation;
867
868        // The first consumer ends, and the remote waits for the next.
869        first.close();
870        tokio::time::sleep(Duration::from_millis(200)).await;
871        assert!(!remote.is_closed());
872        let second = moq_net::broadcast::Info::new().produce();
873        feed.send(second.consume()).await.expect("the remote reads");
874        tokio::time::timeout(
875            Duration::from_secs(5),
876            epoch.wait_for(|epoch| epoch.generation > seen && epoch.consumer.is_some()),
877        )
878        .await
879        .expect("players switched to the second consumer")
880        .expect("epochs keep coming");
881
882        // The feed ends while the second consumer still lives.
883        drop(feed);
884        tokio::time::timeout(Duration::from_secs(5), remote.closed())
885            .await
886            .expect("the remote closed with its feed");
887    }
888
889    /// Dropping a fed broadcast drops its feed, which stops whatever fills it.
890    #[tokio::test]
891    async fn a_dropped_fed_broadcast_drops_its_feed() {
892        let dropped = CancellationToken::new();
893        let guard = dropped.clone().drop_guard();
894        let remote =
895            RemoteBroadcast::from_consumers(n0_future::stream::unfold(guard, |guard| async move {
896                std::future::pending::<()>().await;
897                Some((moq_net::broadcast::Info::new().produce().consume(), guard))
898            }));
899        let clone = remote.clone();
900        drop(remote);
901        tokio::time::sleep(Duration::from_millis(100)).await;
902        assert!(!dropped.is_cancelled(), "a clone still reads the feed");
903        drop(clone);
904        tokio::time::timeout(Duration::from_secs(5), dropped.cancelled())
905            .await
906            .expect("the feed was dropped");
907    }
908}