Skip to main content

iroh_live/
room.rs

1//! A room member's broadcast as media, followed across its subscriptions.
2
3use std::sync::{Arc, Mutex};
4
5use iroh::EndpointId;
6use iroh_live_node::Subscription;
7use iroh_live_rooms::Room;
8use moq_ext_player::RemoteBroadcast;
9use tracing::{Instrument, debug, info_span};
10
11use crate::network::{sealed, signals};
12
13/// Reads a room member's broadcast as media.
14///
15/// The trait is sealed: only [`Room`] implements it.
16///
17/// # Examples
18///
19/// ```no_run
20/// use iroh_live::media::{PlayerConfig, RoomExt};
21///
22/// # fn run(room: iroh_live::rooms::Room, peer: iroh::EndpointId)
23/// # -> Result<(), Box<dyn std::error::Error>> {
24/// let player = room.watch(peer, "cam").play(PlayerConfig::default())?;
25/// # drop(player);
26/// # Ok(())
27/// # }
28/// ```
29pub trait RoomExt: sealed::Sealed {
30    /// Returns member `peer`'s broadcast `name`, subscribing again while the member lists it.
31    ///
32    /// Follows the member through [`Room::subscriptions`]: subscribes once
33    /// the member lists `name`, however long that takes, and again after
34    /// each end of the subscription while the member still lists it, such
35    /// as when the member restarts its broadcast or the session with it
36    /// fails. Players switch to each new subscription and adapt to the link
37    /// that serves it.
38    ///
39    /// The broadcast closes once the member stops listing `name` after it
40    /// did, the room is left, or the room's last handle drops: the watched
41    /// broadcast does not keep the room joined. A member that never lists
42    /// `name` leaves the broadcast waiting, so bound the wait if that can
43    /// happen. The catalog arrives later: watch [`RemoteBroadcast::catalog`]
44    /// for it.
45    ///
46    /// # Panics
47    ///
48    /// Panics when called outside a Tokio runtime.
49    #[must_use]
50    fn watch(&self, peer: EndpointId, name: &str) -> RemoteBroadcast;
51}
52
53impl RoomExt for Room {
54    fn watch(&self, peer: EndpointId, name: &str) -> RemoteBroadcast {
55        let serving = Arc::new(Mutex::new(None::<Subscription>));
56        let span = info_span!("watch", peer = %peer.fmt_short(), %name);
57        let feed = {
58            let state = (self.subscriptions(peer, name), Serving(serving.clone()));
59            n0_future::stream::unfold(state, move |(mut subscriptions, serving)| {
60                async move {
61                    let Some(subscription) = subscriptions.next().await else {
62                        debug!("the member stopped listing the broadcast, or the room was left");
63                        return None;
64                    };
65                    let broadcast = subscription.broadcast();
66                    serving.set(Some(subscription));
67                    Some((broadcast, (subscriptions, serving)))
68                }
69                .instrument(span.clone())
70            })
71        };
72        let remote = RemoteBroadcast::from_consumers(feed);
73        remote.set_network(signals(move || {
74            let serving = serving.lock().expect("poisoned");
75            serving.as_ref().and_then(Subscription::serving_link)
76        }));
77        remote
78    }
79}
80
81/// The subscription that serves a watched broadcast now, emptied when dropped.
82///
83/// Dropped with the feed once the subscriptions end, so the last one does
84/// not stay open with the remote broadcast.
85struct Serving(Arc<Mutex<Option<Subscription>>>);
86
87impl Serving {
88    /// Replaces the subscription that serves now.
89    fn set(&self, subscription: Option<Subscription>) {
90        *self.0.lock().expect("poisoned") = subscription;
91    }
92}
93
94impl Drop for Serving {
95    fn drop(&mut self) {
96        self.set(None);
97    }
98}