webrtc/lib.rs
1#![doc(
2 html_logo_url = "https://raw.githubusercontent.com/webrtc-rs/webrtc-rs.github.io/master/res/webrtc.rs.png"
3)]
4#![warn(rust_2018_idioms)]
5#![warn(missing_docs)]
6#![allow(dead_code)]
7
8//! # Async WebRTC
9//!
10//! `webrtc` is an async-friendly, runtime-agnostic WebRTC implementation in Rust.
11//! It is built as a thin async layer on top of the battle-tested Sans-I/O [`rtc`](https://docs.rs/rtc) protocol core.
12//!
13//! ## Architecture
14//!
15//! The crate separates protocol state from I/O using a driver-based architecture:
16//!
17//! * **`PeerConnection`**: The user-facing API handle. All operations (e.g., creating offers, adding tracks,
18//! creating data channels) are asynchronous and communicate with a background driver.
19//! * **`PeerConnectionDriver`**: An internal background event loop spawned automatically. It coordinates network
20//! sockets (UDP/TCP), handles timeouts, drives the underlying Sans-I/O `rtc` core, and dispatches events.
21//! * **`Runtime`**: A trait abstracting async operations (timers, spawning, sockets). This allows the crate to
22//! be completely runtime-agnostic.
23//!
24//! ## Async Runtime Support
25//!
26//! The library supports multiple async runtimes through Cargo features:
27//!
28//! | Feature | Default | Description |
29//! |---------|---------|-------------|
30//! | `runtime-tokio` | ✅ | Timers, task spawning and sockets via Tokio |
31//! | `runtime-smol` | | The same, via smol |
32//!
33//! The two are mutually exclusive in practice, so selecting smol means turning the default
34//! off — otherwise both runtimes are compiled in:
35//!
36//! ```toml
37//! [dependencies]
38//! webrtc = { version = "0.21", default-features = false, features = ["runtime-smol"] }
39//! ```
40//!
41//! Additional runtimes (async-std, embassy) are on the roadmap behind the same
42//! [`Runtime`](crate::runtime::Runtime) abstraction.
43//!
44//! ## Where to Start
45//!
46//! | Module | What lives there |
47//! |--------|------------------|
48//! | [`peer_connection`] | [`PeerConnectionBuilder`](crate::peer_connection::PeerConnectionBuilder), the [`PeerConnection`](crate::peer_connection::PeerConnection) trait, and the [`PeerConnectionEventHandler`](crate::peer_connection::PeerConnectionEventHandler) you implement — start here |
49//! | [`data_channel`] | The [`DataChannel`](crate::data_channel::DataChannel) trait: `send`, `try_send`, and send-buffer back-pressure |
50//! | [`media_stream`] | Local and remote tracks. Sending encoded frames? [`TrackLocalStaticSample`](crate::media_stream::track_local::static_sample::TrackLocalStaticSample). Forwarding RTP? [`TrackLocalStaticRTP`](crate::media_stream::track_local::static_rtp::TrackLocalStaticRTP) |
51//! | [`rtp_transceiver`] | The [`RtpSender`](crate::rtp_transceiver::RtpSender) / [`RtpReceiver`](crate::rtp_transceiver::RtpReceiver) traits and per-stream statistics |
52//! | [`runtime`] | The [`Runtime`](crate::runtime::Runtime) trait, for supplying your own executor |
53//! | [`error`] | [`Error`](crate::error::Error) and [`Result`](crate::error::Result), re-exported so you never import from `rtc-shared` directly |
54//!
55//! Beyond the Quick Start below, the repository ships [39 runnable
56//! examples](https://github.com/webrtc-rs/webrtc/tree/master/examples) covering data
57//! channels, media playback and recording, simulcast, ICE restart, and insertable streams.
58//!
59//! ## Quick Start
60//!
61//! Below is a simple example showing how to build a [`PeerConnection`](crate::peer_connection::PeerConnection)
62//! and initiate an SDP offer.
63//!
64//! ```no_run
65//! use webrtc::peer_connection::{
66//! PeerConnection, PeerConnectionBuilder, PeerConnectionEventHandler,
67//! RTCConfigurationBuilder, RTCIceServer, RTCPeerConnectionIceEvent,
68//! };
69//! use std::sync::Arc;
70//!
71//! // 1. Implement the PeerConnectionEventHandler trait to handle events
72//! #[derive(Clone)]
73//! struct MyHandler;
74//!
75//! #[async_trait::async_trait]
76//! impl PeerConnectionEventHandler for MyHandler {
77//! async fn on_ice_candidate(&self, event: RTCPeerConnectionIceEvent) {
78//! println!("New local ICE candidate gathered: {}", event.candidate);
79//! }
80//! }
81//!
82//! # #[cfg(feature = "runtime-tokio")]
83//! #[tokio::main]
84//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
85//! // 2. Configure the peer connection
86//! let config = RTCConfigurationBuilder::default()
87//! .with_ice_servers(vec![RTCIceServer {
88//! urls: vec!["stun:stun.l.google.com:19302".to_owned()],
89//! ..Default::default()
90//! }])
91//! .build();
92//!
93//! // 3. Build the PeerConnection
94//! let pc = PeerConnectionBuilder::new()
95//! .with_configuration(config)
96//! .with_handler(Arc::new(MyHandler))
97//! .with_udp_addrs(vec!["0.0.0.0:0"])
98//! .build()
99//! .await?;
100//!
101//! // 4. Create an SDP offer and set it as local description
102//! let offer = pc.create_offer(None).await?;
103//! pc.set_local_description(offer).await?;
104//!
105//! println!("Local description set successfully!");
106//! Ok(())
107//! }
108//! # #[cfg(not(feature = "runtime-tokio"))]
109//! # fn main() {}
110//! ```
111
112pub mod data_channel;
113pub mod media_stream;
114pub mod peer_connection;
115pub mod rtp_transceiver;
116pub mod runtime;
117
118/// Private supertrait used to seal the traits this library alone implements.
119///
120/// [`PeerConnection`](peer_connection::PeerConnection),
121/// [`DataChannel`](data_channel::DataChannel), [`RtpSender`](rtp_transceiver::RtpSender),
122/// [`RtpReceiver`](rtp_transceiver::RtpReceiver) and
123/// [`RtpTransceiver`](rtp_transceiver::RtpTransceiver) describe objects that only `webrtc`
124/// can construct, so downstream implementations would be meaningless. Sealing them lets us
125/// add methods in a minor release instead of a major one — see `docs/semver.md`.
126///
127/// Extension points deliberately left open — [`Runtime`](runtime::Runtime), the socket and
128/// timer traits, [`PeerConnectionEventHandler`](peer_connection::PeerConnectionEventHandler)
129/// and the application-provided track traits — do not have this supertrait.
130pub(crate) mod sealed {
131 /// Implemented only by this crate's concrete types.
132 pub trait Sealed {}
133}
134
135/// Error and Result types
136///
137/// Re-exports [`error::Error`] and [`error::Result`] from `rtc-shared` so that
138/// callers only need to import from `webrtc::error` rather than reaching into
139/// the lower-level crate directly.
140pub mod error {
141 pub use rtc::shared::error::{Error, Result};
142}