Skip to main content

iroh_live/
network.rs

1//! A subscription's link, in the media crate's terms.
2
3use std::sync::Mutex;
4
5use iroh_live_node::{LinkId, ServingLink, Subscription};
6use moq_ext_player::{NetworkSample, RemoteBroadcast};
7
8/// Reads a [`Subscription`] as media.
9///
10/// The trait is sealed: only [`Subscription`] implements it.
11///
12/// # Examples
13///
14/// ```no_run
15/// use iroh_live::{
16///     BroadcastTicket, Node,
17///     media::{PlayerConfig, SubscriptionExt},
18/// };
19///
20/// # async fn run(node: Node, ticket: BroadcastTicket) -> Result<(), Box<dyn std::error::Error>> {
21/// let subscription = node.subscribe_ticket(&ticket).await?;
22/// let player = subscription.remote_broadcast().play(PlayerConfig::default())?;
23/// # drop(player);
24/// # Ok(())
25/// # }
26/// ```
27pub trait SubscriptionExt: sealed::Sealed {
28    /// Returns the media of this subscription.
29    ///
30    /// The broadcast follows the subscription's path through the route table
31    /// it was resolved in, so a change of route does not end it, and its
32    /// players adapt to the link that serves it. A subscription on one
33    /// session re-resolves through that session only. The catalog arrives
34    /// later: watch [`RemoteBroadcast::catalog`] for it.
35    #[must_use]
36    fn remote_broadcast(&self) -> RemoteBroadcast;
37}
38
39pub(crate) mod sealed {
40    /// Keeps the extension traits to the types implemented here.
41    // Sealed: not nameable on purpose.
42    #[allow(unnameable_types, reason = "a sealed trait is unnameable on purpose")]
43    pub trait Sealed {}
44
45    impl Sealed for iroh_live_node::Subscription {}
46
47    #[cfg(feature = "rooms")]
48    impl Sealed for iroh_live_rooms::Room {}
49}
50
51impl SubscriptionExt for Subscription {
52    fn remote_broadcast(&self) -> RemoteBroadcast {
53        let remote =
54            RemoteBroadcast::from_resolved(self.origin(), self.path().clone(), self.broadcast());
55        let subscription = self.clone();
56        remote.set_network(signals(move || subscription.serving_link()));
57        remote
58    }
59}
60
61/// Returns the network signals of the link `serving` names.
62///
63/// Each sample reads whichever link serves the broadcast at that moment.
64/// The path generation also counts changes of the serving link, so
65/// adaptation never compares one link's history with another's.
66pub(crate) fn signals(
67    serving: impl Fn() -> Option<ServingLink> + Send + Sync + 'static,
68) -> impl Fn() -> NetworkSample + Send + Sync + 'static {
69    // The serving link and path generation at the last sample, and how often
70    // that pair changed.
71    let last = Mutex::new((None::<(LinkId, u64)>, 0));
72    move || {
73        let link = serving();
74        let mut last = last.lock().expect("poisoned");
75        let serving = link
76            .as_ref()
77            .map(|link| (link.id, link.sample.path_generation));
78        if last.0 != serving {
79            *last = (serving, last.1 + 1);
80        }
81        let mut sample = link.map(|link| link.sample).unwrap_or_default();
82        sample.path_generation = last.1;
83        sample
84    }
85}