Skip to main content

iroh_live/
lib.rs

1//! Live audio and video over iroh.
2//!
3//! A [`Node`] publishes and subscribes to broadcasts at paths, over a direct
4//! session with a peer or an attached media relay. [`node`] re-exports
5//! iroh-live-node, the layer under the facade, and [`moq_net`] the moq-net it
6//! builds on. `media` and `rooms` gather the media and rooms crates, each behind
7//! its feature.
8//!
9//! The moq crates are pinned to a git rev of moq-dev/moq `main`, so this crate
10//! is not on crates.io yet.
11//!
12//! The node takes any path. iroh-live ships one convention,
13//! [`layout::LiveLayout`], which publishes a peer's broadcasts at
14//! `<root>/<peer>/<name>` (the root is `live` by default) and lets each peer
15//! publish only under its own id. An application with its own scheme passes
16//! its own paths and policy, see [`NodeConfig::with_policy`].
17//!
18//! A [`BroadcastTicket`] names a peer and the path it publishes at, whatever
19//! the layout. [`Node::subscribe_ticket`] grants the ticket's publisher that
20//! one path while the subscription lives, so a viewer needs no layout.
21#![cfg_attr(
22    all(feature = "player", feature = "publisher"),
23    doc = r#"
24This publishes a test pattern and plays someone else's broadcast:
25
26```no_run
27use iroh::protocol::Router;
28use iroh_live::{
29    BroadcastTicket, EndpointConfig, Node,
30    layout::LiveLayout,
31    media::{
32        LocalBroadcast, PlayerConfig, SubscriptionExt, VideoEncoding, VideoRendition,
33        VideoSource, video,
34    },
35};
36
37# async fn run(ticket: BroadcastTicket) -> Result<(), Box<dyn std::error::Error>> {
38let layout = LiveLayout::default();
39let endpoint = EndpointConfig::from_env()?.bind().await?;
40let node = Node::new(endpoint.clone(), layout.config());
41// Accepts the peers that read the broadcast. Keep the router alive.
42let router = node.mount(Router::builder(endpoint)).spawn();
43
44// Created in the node's route table: peers read it without a copy.
45let broadcast: LocalBroadcast = layout.publish(&node, "studio")?;
46let source = VideoSource::test_pattern(
47    video::Size::new(1280, 720),
48    video::FrameRate::new(30, 1).expect("a valid rate"),
49)?;
50broadcast.set_video(
51    source,
52    VideoEncoding::ladder([VideoRendition::p360(), VideoRendition::p720()]),
53)?;
54println!("share {}", layout.ticket(node.id(), "studio")?);
55
56let subscription = node.subscribe_ticket(&ticket).await?;
57let player = subscription.remote_broadcast().play(PlayerConfig::default())?;
58let mut frames = player.video_frames();
59while let Some(frame) = frames.next().await {
60    // hand `frame` to a renderer
61#   drop(frame);
62}
63
64// Shuts the node down and every mounted service, then closes the endpoint.
65router.shutdown().await?;
66# Ok(())
67# }
68```
69"#
70)]
71//!
72//! [`EndpointConfig::apply`] composes with your own endpoint builder, and
73//! [`calls::Calls`] places and answers one-to-one calls over a layout.
74//!
75//! The main types:
76//!
77//! - [`Node`]: the node, mounted on the application's router with
78//!   [`Node::mount`].
79//! - [`layout::LiveLayout`]: the `<root>/<peer>/<name>` path convention.
80//! - [`BroadcastTicket`]: a publisher's endpoint id and the path of a broadcast.
81//! - [`calls::Calls`]: one-to-one calls.
82#![cfg_attr(
83    feature = "rooms",
84    doc = "- [`RoomsNode`]: a node that serves live broadcasts and rooms, bound in one call."
85)]
86#![cfg_attr(
87    feature = "publisher",
88    doc = "- [`LocalBroadcast`](media::LocalBroadcast): a broadcast this node publishes, from [`media`]."
89)]
90#![cfg_attr(
91    feature = "player",
92    doc = "- [`RemoteBroadcast`](media::RemoteBroadcast): a broadcast this node plays, from [`media`]."
93)]
94//!
95//! The futures differ in what dropping them leaves behind:
96//!
97//! | Future | Cancellation safe | Dropping it |
98//! |---|---|---|
99//! | [`EndpointConfig::bind`] | yes | nothing is bound |
100//! | [`Node::subscribe`], [`Node::subscribe_ticket`] | yes | abandons the wait, and a dial it started continues for other callers |
101//! | [`calls::Calls::call`], [`calls::Calls::answer`] | yes | hangs up |
102//! | [`EndpointConfig::apply`] | yes | the builder is lost, nothing is bound |
103//! | [`Node::shutdown`] | no, idempotent | call again to finish |
104//!
105//! [`Node::shutdown`] does not close the endpoint. Whoever binds it closes
106//! it, directly or through `Router::shutdown`.
107//!
108//! `media`, [`node`] and `rooms` list their own futures.
109//! No public call takes a deadline. Bound a wait with `tokio::time::timeout`.
110//!
111//! Each call returns the error of the crate that runs it: [`node::Error`] from
112//! the node and the layout, [`EndpointError`] from [`EndpointConfig`],
113//! `media::Error` from sources, publishing and playback, `rooms::Error` from
114//! rooms, and [`calls::Error`] from calls. Each one converts into [`Error`], so
115//! `?` works in a function that returns it.
116//!
117//! Only `crypto-aws-lc-rs` is on by default. `crypto-rind`, `crypto-ring` and
118//! `crypto-aws-lc-rs` pick the rustls backend that iroh and moq share, see
119//! [`crypto_provider`]. With more than one on, ring wins over aws-lc-rs and
120//! both over rind, so `crypto-rind` needs default features off. The default
121//! moves to `crypto-rind` once rind releases per-path QUIC keys.
122//!
123//! `player` builds the receive side of `media`, `publisher` the send side,
124//! and `media` both. Device features turn on their side: `capture`, `file`
125//! and `rpicam` imply `publisher`, `playback`, `render` and `record` imply
126//! `player`. `pipewire`, `pulseaudio` and the hardware codecs apply to
127//! whichever side is on; `pipewire` with `publisher` also builds device
128//! capture.
129//! `full` is the usual app set, and `rooms` re-exports `iroh-live-rooms`
130//! and adds `RoomsNode`.
131//! Without a side the crate is the node, the layout, calls and endpoint
132//! setup.
133
134#![forbid(unsafe_code)]
135
136pub mod calls;
137mod error;
138#[cfg(feature = "player")]
139mod network;
140#[cfg(all(feature = "player", feature = "rooms"))]
141mod room;
142#[cfg(feature = "rooms")]
143mod rooms_node;
144
145/// Sources, broadcasts and players, with the codec stacks they sit on.
146///
147/// The `player` feature brings the player and the decoders, `publisher` the
148/// publisher, the encoders and the sources. `media` turns on both.
149#[cfg(any(feature = "player", feature = "publisher"))]
150pub mod media {
151    pub use moq_audio as audio;
152    #[cfg(feature = "player")]
153    pub use moq_ext_player::{
154        Adaptation, AudioFrame, AudioFrames, AudioMode, AudioPlaybackStats, Catalog,
155        DEFAULT_LATENCY, Delay, FrameTiming, IMMEDIATE_LATENCY, MediaKind, NetworkSample,
156        PlaybackStats, Player, PlayerConfig, PlayerStatus, RemoteBroadcast, RenditionMode,
157        VideoBacklog, VideoPlaybackStats, video_rendition,
158    };
159    #[cfg(feature = "publisher")]
160    pub use moq_ext_publisher::{
161        AudioEncodeStats, AudioEncoding, EncodeStats, LocalBroadcast, MediaEncoding, PublishStats,
162        PublishStatus, RenditionState, VideoEncoding, VideoRendition, audio_encoding,
163    };
164    #[cfg(all(target_os = "linux", feature = "pipewire", feature = "publisher"))]
165    pub use moq_ext_sources::PortalGrant;
166    #[cfg(any(feature = "capture", all(feature = "pipewire", feature = "publisher")))]
167    pub use moq_ext_sources::screen_source;
168    pub use moq_ext_sources::{
169        AudioFormat, Backend, Error, SlotState, SourceClosed, UnknownBackend, VideoFormat,
170        VideoFrames,
171    };
172    #[cfg(feature = "file")]
173    pub use moq_ext_sources::{AudioInfo, MediaFile, MediaInfo, VideoFileConfig, VideoInfo};
174    #[cfg(feature = "publisher")]
175    pub use moq_ext_sources::{
176        AudioSource, BouncePattern, EncodedAudio, EncodedFrame, EncodedVideo, FileEnd, FrameSender,
177        VideoSource, VideoSwitch, spec,
178    };
179    #[cfg(all(target_os = "linux", feature = "rpicam"))]
180    pub use moq_ext_sources::{RpicamConfig, rpicam_h264};
181    pub use moq_net::bandwidth::Rate;
182    pub use moq_video as video;
183    /// The `wgpu` crate that [`video::render`] draws with.
184    ///
185    /// Name `wgpu` types through it, so they always match the renderer's
186    /// version, instead of depending on `wgpu` directly.
187    #[cfg(feature = "render")]
188    pub use wgpu;
189
190    #[cfg(feature = "player")]
191    pub use crate::network::SubscriptionExt;
192    #[cfg(all(feature = "player", feature = "rooms"))]
193    pub use crate::room::RoomExt;
194}
195pub use iroh_live_node as node;
196/// The moq-net this crate builds against.
197pub use iroh_live_node::moq_net;
198// A type that a top-level item's method takes or returns is top-level too,
199// so a caller never has to guess which path holds it.
200#[cfg(feature = "rooms")]
201pub use self::rooms_node::RoomsNode;
202pub use iroh_live_node::{
203    Audience, BroadcastTicket, Congestion, ConnectOptions, EndpointConfig, EndpointError, Grant,
204    LinkKind, Mdns, MinimalPreset, MoqPreset, NetworkPath, NetworkPathKind, NetworkSample, Node,
205    NodeConfig, Publication, Reach, RelayConfig, RelayLink, RelayStatus, ServingLink, Session,
206    Subscription, UnpublishOnDrop, ValueError, ValueReader, ValueWriter, crypto_provider, layout,
207    load_or_create_secret_key,
208};
209#[cfg(feature = "rooms")]
210pub use iroh_live_rooms as rooms;
211/// Typed JSON tracks over moq-net, including a latest-value track.
212///
213/// [`snapshot`](json::snapshot) is the latest-value track, for state such
214/// as a setting. [`Consumer::latest`](json::snapshot::Consumer::latest) skips
215/// to the newest value. A track keeps its newest group, so a late reader gets
216/// the current value at once without the writer repeating it.
217/// [`stream`](json::stream) is the lossless log, for records that must all
218/// arrive.
219///
220/// [`Node::publish_value`] publishes a broadcast with one latest-value track,
221/// and [`Subscription::value_track`] reads it with a [`ValueReader`] that
222/// follows the subscription to a restarted publisher. In a room,
223/// `Room::publish_value` publishes one to the members, and
224/// `Room::read_values` reads it from each of them. A track next to media
225/// goes through `LocalBroadcast::value_track`, and any other through
226/// [`ValueWriter::new`] on a track of your own. The track counts
227/// milliseconds, and the [`ValueWriter`] stamps each update with the time it
228/// is made. This publishes a latency in milliseconds and reads it back:
229///
230/// ```no_run
231/// use iroh_live::{Audience, Node, Reach, layout::LiveLayout};
232///
233/// # async fn run(node: Node, other: Node) -> Result<(), Box<dyn std::error::Error>> {
234/// let path = LiveLayout::default().path(node.id(), "control")?;
235/// let (_publication, latency) =
236///     node.publish_value::<u64>(path.clone(), Audience::Granted, "latency")?;
237/// latency.update(&150)?;
238///
239/// // On another node.
240/// let subscription = other.subscribe(&path, Reach::Direct(node.id())).await?;
241/// let mut latency = subscription.value_track::<u64>("latency")?;
242/// while let Some(newest) = latency.latest().await? {
243///     println!("latency {} ms", newest.value);
244/// }
245/// # Ok(())
246/// # }
247/// ```
248pub use moq_json as json;
249
250pub use self::error::Error;