rtci/lib.rs
1//! # RTC - Sans-I/O WebRTC Implementation
2//!
3//! A Rust implementation of the [WebRTC specification](https://www.w3.org/TR/webrtc/) using a
4//! **sans-I/O architecture**. This crate provides full WebRTC functionality while giving you
5//! complete control over networking, threading, and async runtime integration.
6//!
7//! ## What is Sans-I/O?
8//!
9//! Sans-I/O (without I/O) is a design pattern that separates protocol logic from I/O operations.
10//! Instead of the library performing network reads and writes directly, **you** provide the
11//! network data and handle the output. This gives you:
12//!
13//! - **Runtime Independence**: Works with tokio, async-std, smol, or blocking I/O
14//! - **Full Control**: You control threading, scheduling, and I/O multiplexing
15//! - **Testability**: Protocol logic can be tested without real network I/O
16//! - **Flexibility**: Easy integration with existing networking code
17//!
18//! ## Quick Start
19//!
20//! ```no_run
21//! # use std::time::Instant;
22//! use rtci::peer_connection::RTCPeerConnectionBuilder;
23//! use rtci::peer_connection::configuration::RTCConfigurationBuilder;
24//! use rtci::peer_connection::transport::RTCIceServer;
25//! use rtci::peer_connection::sdp::RTCSessionDescription;
26//! use rtci::peer_connection::transport::{CandidateConfig, CandidateHostConfig, RTCIceCandidate};
27//!
28//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
29//! // 1. Create a peer connection with ICE servers
30//! let mut pc = RTCPeerConnectionBuilder::new()
31//! .with_configuration(
32//! RTCConfigurationBuilder::new()
33//! .with_ice_servers(vec![RTCIceServer {
34//! urls: vec!["stun:stun.l.google.com:19302".to_string()],
35//! ..Default::default()
36//! }])
37//! .build()
38//! )
39//! .build(Instant::now())?;
40//!
41//! // 2. Create an offer
42//! let offer = pc.create_offer(None)?;
43//! pc.set_local_description(Instant::now(), offer.clone())?;
44//!
45//! // Send offer to remote peer via your signaling channel
46//! // signaling.send(offer.sdp)?;
47//!
48//! // 3. Receive answer from remote peer
49//! // let answer_sdp = signaling.receive()?;
50//! # let answer_sdp = String::new();
51//! let answer = RTCSessionDescription::answer(answer_sdp)?;
52//! pc.set_remote_description(Instant::now(), answer)?;
53//!
54//! // 4. Add local ICE candidate
55//! # use std::net::{IpAddr, Ipv4Addr};
56//! let candidate = CandidateHostConfig {
57//! base_config: CandidateConfig {
58//! network: "udp".to_owned(),
59//! address: "192.168.1.100".to_string(),
60//! port: 8080,
61//! component: 1,
62//! ..Default::default()
63//! },
64//! ..Default::default()
65//! }
66//! .new_candidate_host()?;
67//! let local_candidate_init = RTCIceCandidate::from(&candidate).to_json()?;
68//! pc.add_local_candidate(local_candidate_init)?;
69//!
70//! // 5. Event loop - see complete example below
71//! # Ok(())
72//! # }
73//! ```
74//!
75//! ## Complete Event Loop with All API Calls
76//!
77//! This example demonstrates the full sans-I/O event loop pattern with all key API methods:
78//!
79//! ```no_run
80//! use rtci::peer_connection::RTCPeerConnectionBuilder;
81//! use rtci::peer_connection::configuration::{RTCConfigurationBuilder, media_engine::MediaEngine};
82//! use rtci::peer_connection::transport::RTCIceServer;
83//! use rtci::peer_connection::event::{RTCPeerConnectionEvent, RTCTrackEvent};
84//! use rtci::peer_connection::state::{RTCPeerConnectionState, RTCIceConnectionState};
85//! use rtci::peer_connection::message::{RTCMessage, TaggedRTCMessage};
86//! use rtci::shared::{TaggedBytesMut, TransportContext, TransportProtocol};
87//! use rtci::sansio::Protocol;
88//! use std::time::{Duration, Instant};
89//! use tokio::net::UdpSocket;
90//! use bytes::BytesMut;
91//!
92//! # #[tokio::main]
93//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
94//! // Configure media codecs
95//! let media_engine = MediaEngine::default();
96//!
97//! // Create peer connection
98//! let mut pc = RTCPeerConnectionBuilder::new()
99//! .with_configuration(
100//! RTCConfigurationBuilder::new()
101//! .with_ice_servers(vec![RTCIceServer {
102//! urls: vec!["stun:stun.l.google.com:19302".to_string()],
103//! ..Default::default()
104//! }])
105//! .build()
106//! )
107//! .with_media_engine(media_engine)
108//! .build(Instant::now())?;
109//!
110//! // Bind UDP socket for network I/O, on the concrete address of the host candidate you add:
111//! // `local_addr` must be a local candidate's address, and a socket bound to 0.0.0.0 reports
112//! // 0.0.0.0:port, which none is (README, "The local address of a datagram").
113//! let socket = UdpSocket::bind("192.168.1.100:0").await?;
114//! let local_addr = socket.local_addr()?;
115//!
116//! let mut buf = vec![0u8; 2000];
117//! const DEFAULT_TIMEOUT: Duration = Duration::from_secs(86400);
118//!
119//! // Main event loop
120//! loop {
121//! // 1. poll_write() - Get outgoing network packets
122//! while let Some(msg) = pc.poll_write() {
123//! socket.send_to(&msg.message, msg.transport.peer_addr).await?;
124//! }
125//!
126//! // 2. poll_event() - Process connection state changes and events
127//! while let Some(event) = pc.poll_event() {
128//! match event {
129//! RTCPeerConnectionEvent::OnIceConnectionStateChangeEvent(state) => {
130//! println!("ICE Connection State: {state}");
131//! if state == RTCIceConnectionState::Failed {
132//! break;
133//! }
134//! }
135//! RTCPeerConnectionEvent::OnConnectionStateChangeEvent(state) => {
136//! println!("Connection State: {state}");
137//! if state == RTCPeerConnectionState::Failed {
138//! return Ok(());
139//! }
140//! }
141//! RTCPeerConnectionEvent::OnDataChannel(dc_event) => {
142//! println!("Data channel event: {:?}", dc_event);
143//! }
144//! RTCPeerConnectionEvent::OnTrack(track_event) => {
145//! match track_event {
146//! RTCTrackEvent::OnOpen(init) => {
147//! println!("Track opened: track_id={}, receiver_id={:?}",
148//! init.track_id, init.receiver_id);
149//! }
150//! RTCTrackEvent::OnClose(track_id) => {
151//! println!("Track closed: {track_id}");
152//! }
153//! _ => {}
154//! }
155//! }
156//! _ => {}
157//! }
158//! }
159//!
160//! // 3. poll_read() - Get incoming application messages (RTP/RTCP/data)
161//! while let Some(TaggedRTCMessage { message, .. }) = pc.poll_read() {
162//! match message {
163//! RTCMessage::RtpPacket(track_id, rtp_packet) => {
164//! println!("Received RTP packet on track {track_id}");
165//! // Process RTP packet
166//! }
167//! RTCMessage::RtcpPacket(receiver_id, rtcp_packets) => {
168//! println!("Received RTCP packets on receiver {:?}", receiver_id);
169//! // Process RTCP packets
170//! }
171//! RTCMessage::DataChannelMessage(channel_id, message) => {
172//! println!("Received data channel message on channel {:?}", channel_id);
173//! // Process data channel message
174//! }
175//! // RTCMessage is #[non_exhaustive]: a wildcard arm is required.
176//! _ => {}
177//! }
178//! }
179//!
180//! // 4. poll_timeout() - Get next timer deadline
181//! let timeout = pc.poll_timeout()
182//! .unwrap_or(Instant::now() + DEFAULT_TIMEOUT);
183//! let delay = timeout.saturating_duration_since(Instant::now());
184//!
185//! // Handle immediate timeout
186//! if delay.is_zero() {
187//! // 6. handle_timeout() - Notify about timer expiration
188//! pc.handle_timeout(Instant::now())?;
189//! continue;
190//! }
191//!
192//! // Wait for events using tokio::select!
193//! let timer = tokio::time::sleep(delay);
194//! tokio::pin!(timer);
195//!
196//! tokio::select! {
197//! biased;
198//!
199//! // Timer expired
200//! _ = timer => {
201//! pc.handle_timeout(Instant::now())?;
202//! }
203//! // Received network packet
204//! Ok((n, peer_addr)) = socket.recv_from(&mut buf) => {
205//! // 5. handle_read() - Feed incoming network packets
206//! pc.handle_read(TaggedBytesMut {
207//! now: Instant::now(),
208//! transport: TransportContext {
209//! local_addr,
210//! peer_addr,
211//! ecn: None,
212//! transport_protocol: TransportProtocol::UDP,
213//! },
214//! message: BytesMut::from(&buf[..n]),
215//! })?;
216//! }
217//! // Ctrl-C to exit
218//! _ = tokio::signal::ctrl_c() => {
219//! break;
220//! }
221//! }
222//! }
223//!
224//! pc.close()?;
225//! # Ok(())
226//! # }
227//! ```
228//!
229//! ## Core API Methods
230//!
231//! ### Sans-I/O Event Loop Methods
232//!
233//! The event loop uses these six core methods:
234//!
235//! 1. **`poll_write()`** - Get outgoing network packets to send via UDP
236//! 2. **`poll_event()`** - Process connection state changes and notifications
237//! 3. **`poll_read()`** - Get incoming application messages (RTP, RTCP, data)
238//! 4. **`poll_timeout()`** - Get next timer deadline for retransmissions/keepalives
239//! 5. **`handle_read()`** - Feed incoming network packets into the connection
240//! 6. **`handle_timeout()`** - Notify about timer expiration
241//!
242//! Additional methods for external control:
243//!
244//! - **`handle_write()`** - Queue application messages (RTP/RTCP/data) for sending
245//! - **`handle_event()`** - Inject external events into the connection
246//!
247//! ### Signaling with Complete Example
248//!
249//! WebRTC requires an external signaling channel to exchange offers, answers, and ICE
250//! candidates. This example shows the complete offer/answer flow:
251//!
252//! ```no_run
253//! # use std::time::Instant;
254//! use rtci::peer_connection::RTCPeerConnectionBuilder;
255//! use rtci::peer_connection::configuration::RTCConfigurationBuilder;
256//! use rtci::peer_connection::transport::RTCIceServer;
257//! use rtci::peer_connection::sdp::RTCSessionDescription;
258//! use rtci::peer_connection::transport::{CandidateConfig, CandidateHostConfig, RTCIceCandidate};
259//!
260//! # fn send_to_remote_peer(_: &str) {}
261//! # fn receive_from_remote_peer() -> String { String::new() }
262//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
263//! // Offerer side - creates the offer
264//! let mut offerer = RTCPeerConnectionBuilder::new()
265//! .with_configuration(
266//! RTCConfigurationBuilder::new()
267//! .with_ice_servers(vec![RTCIceServer {
268//! urls: vec!["stun:stun.l.google.com:19302".to_string()],
269//! ..Default::default()
270//! }])
271//! .build()
272//! )
273//! .build(Instant::now())?;
274//!
275//! // 1. Create offer
276//! let offer = offerer.create_offer(None)?;
277//!
278//! // 2. Set local description
279//! offerer.set_local_description(Instant::now(), offer.clone())?;
280//!
281//! // 3. Add local ICE candidate
282//! let candidate = CandidateHostConfig {
283//! base_config: CandidateConfig {
284//! network: "udp".to_owned(),
285//! address: "192.168.1.100".to_string(),
286//! port: 8080,
287//! component: 1,
288//! ..Default::default()
289//! },
290//! ..Default::default()
291//! }
292//! .new_candidate_host()?;
293//! offerer.add_local_candidate(RTCIceCandidate::from(&candidate).to_json()?)?;
294//!
295//! // 4. Send offer to remote peer (your signaling channel)
296//! send_to_remote_peer(&serde_json::to_string(&offer)?);
297//!
298//! // --- On answerer side ---
299//! let mut answerer = RTCPeerConnectionBuilder::new()
300//! .with_configuration(
301//! RTCConfigurationBuilder::new()
302//! .with_ice_servers(vec![RTCIceServer {
303//! urls: vec!["stun:stun.l.google.com:19302".to_string()],
304//! ..Default::default()
305//! }])
306//! .build()
307//! )
308//! .build(Instant::now())?;
309//!
310//! // 5. Receive and set remote description
311//! let offer_json = receive_from_remote_peer();
312//! let remote_offer: RTCSessionDescription = serde_json::from_str(&offer_json)?;
313//! answerer.set_remote_description(Instant::now(), remote_offer)?;
314//!
315//! // 6. Create answer
316//! let answer = answerer.create_answer(None)?;
317//!
318//! // 7. Set local description
319//! answerer.set_local_description(Instant::now(), answer.clone())?;
320//!
321//! // 8. Send answer back to offerer
322//! send_to_remote_peer(&serde_json::to_string(&answer)?);
323//!
324//! // --- Back on offerer side ---
325//! // 9. Receive and set remote description
326//! let answer_json = receive_from_remote_peer();
327//! let remote_answer: RTCSessionDescription = serde_json::from_str(&answer_json)?;
328//! offerer.set_remote_description(Instant::now(), remote_answer)?;
329//!
330//! // Now both peers are connected!
331//! # Ok(())
332//! # }
333//! ```
334//!
335//! ## Module Organization
336//!
337//! ### [`peer_connection`]
338//!
339//! Core WebRTC peer connection implementation:
340//!
341//! - **[`RTCPeerConnection`](peer_connection::RTCPeerConnection)** - Peer connection interface
342//! - **[`certificate`](peer_connection::certificate)** - Peer connection certficiate
343//! - **[`configuration`](peer_connection::configuration)** - Peer connection configuration
344//! - **[`interceptor_registry`](peer_connection::configuration::interceptor_registry)** - NACK, TWCC, RTCP Reports configuration
345//! - **[`media_engine`](peer_connection::configuration::media_engine)** - Codec and RTP extension configuration
346//! - **[`setting_engine`](peer_connection::configuration::setting_engine)** - Low-level transport settings
347//! - **[`event`](peer_connection::event)** - Peer connection events
348//! - **[`message`](peer_connection::message)** - RTP/RTCP Packets and Application messages
349//! - **[`sdp`](peer_connection::sdp)** - SDP offer/answer types
350//! - **[`state`](peer_connection::state)** - Peer connection state types
351//! - **[`transport`](peer_connection::transport)** - ICE, DTLS, SCTP transport types
352//!
353//! ### [`data_channel`]
354//!
355//! WebRTC data channels for arbitrary data transfer:
356//!
357//! - **[`RTCDataChannel`](data_channel::RTCDataChannel)** - Data channel interface
358//! - **[`RTCDataChannelInit`](data_channel::RTCDataChannelInit)** - Channel configuration
359//! - **[`RTCDataChannelMessage`](data_channel::RTCDataChannelMessage)** - Data channel messages
360//!
361//! ### [`rtp_transceiver`]
362//!
363//! RTP media transmission and reception:
364//!
365//! - **[`RTCRtpSender`](rtp_transceiver::rtp_sender::RTCRtpSender)** - Media sender
366//! - **[`RTCRtpReceiver`](rtp_transceiver::rtp_receiver::RTCRtpReceiver)** - Media receiver
367//!
368//! ### [`media_stream`]
369//!
370//! Media track management:
371//!
372//! - **[`MediaStreamTrack`](media_stream::track::MediaStreamTrack)** - Audio/video track
373//!
374//! ## Features
375//!
376//! - ✅ **ICE (Interactive Connectivity Establishment)** - NAT traversal with STUN/TURN
377//! - ✅ **DTLS (Datagram Transport Layer Security)** - Encryption for media and data
378//! - ✅ **SCTP (Stream Control Transmission Protocol)** - Reliable data channels
379//! - ✅ **RTP/RTCP** - Real-time media transport and control
380//! - ✅ **SDP (Session Description Protocol)** - Offer/answer negotiation
381//! - ✅ **Data Channels** - Bidirectional peer-to-peer data transfer
382//! - ✅ **Media Tracks** - Audio/video transmission
383//! - ✅ **Trickle ICE** - Progressive candidate gathering
384//! - ✅ **ICE Restart** - Connection recovery
385//! - ✅ **Simulcast & SVC** - Scalable video coding
386//!
387//! ## Working Examples
388//!
389//! The crate includes comprehensive examples in the `examples/` directory:
390//!
391//! - **data-channels-offer-answer** - Complete data channel setup with signaling
392//! - **save-to-disk-vpx** - Receive and save VP8/VP9 video to disk
393//! - **play-from-disk-vpx** - Send VP8/VP9 video from disk
394//! - **rtp-forwarder** - Forward RTP streams between peers
395//! - **simulcast** - Multiple quality streams
396//! - **trickle-ice** - Progressive ICE candidate exchange
397//!
398//! See the `examples/` directory for complete, runnable code.
399//!
400//! ## Gathering
401//!
402//! The engine has no sockets, so the application gathers: it binds its UDP sockets, gives
403//! each host candidate to [`RTCPeerConnection::add_local_candidate`] (with the `sdp_mid` of
404//! the transport's first section when sections are not bundled, see
405//! [`RTCPeerConnection::ice_transport_sections`]), signals each candidate the engine surfaces
406//! (`OnIceCandidateEvent`) to the peer, and ends a generation with an empty candidate. From a
407//! host candidate the engine gathers the rest by itself when it is configured to, from the first
408//! local description on (RFC 9429 section 3.5.4; what it finds for an ICE generation no local
409//! description represents yet waits for one, W3C webrtc-pc 5.6): the
410//! server-reflexive candidates of the STUN servers, the TURN allocations, the ICE-TCP
411//! candidates (through the stream interface).
412//!
413//! ### A transport that needs new candidates
414//!
415//! A new DTLS association over UDP runs on a new 3-tuple (RFC 8842 section 5.1: "a new
416//! 3-tuple (transport/source address/source port) MUST be allocated by at least one of the
417//! endpoints"). So when one is set up on a transport that had one, the engine drops the
418//! transport's local candidates and refuses their UDP addresses
419//! (`Error::ErrICECandidateAddressOfPreviousDtlsAssociation`), and the application must gather
420//! again on new ports. It is told with
421//! [`RTCPeerConnectionEvent::OnLocalCandidatesNeeded`](peer_connection::event::RTCPeerConnectionEvent::OnLocalCandidatesNeeded),
422//! which names the transport (its ids, the mids of its sections, the first one's index), the
423//! reason ([`RTCLocalCandidatesNeededReason`](peer_connection::event::RTCLocalCandidatesNeededReason))
424//! and the refused addresses. It fires when the description that starts the transport's new
425//! gathering is set locally (W3C webrtc-pc 5.6 begins gathering a generation at
426//! `setLocalDescription`), right before the transport's `gatheringstatechange` to
427//! "gathering":
428//!
429//! - an ICE restart made for a new DTLS association: `renew_dtls_association`, automatic SRTP
430//! re-keying (`SrtpRekeying`, on the side that asked), an offer that replaces a data-only
431//! association to key SRTP, or a peer's offer with a new `a=tls-id` (the answer, when it is
432//! set); per transport, each with its own event;
433//! - the transport that replaced one an answer closed by rejecting every m= section
434//! (`TransportReplaced`): when the next description, which gives it a section, is set;
435//! - every ICE restart with `with_discard_local_candidates_during_ice_restart(true)`
436//! (`DiscardedBySetting`; no address is refused then).
437//! - the first local offer rolled back before any answer (`RolledBack`; no address is
438//! refused): RFC 9429 section 5.7 discards everything gathered for it ("Any resources or
439//! candidates that were allocated by the abandoned local description are discarded":
440//! the host candidates, the STUN probes, the TURN allocations, the ICE-TCP listeners),
441//! and the next local description (the answer to the peer's offer, say) gathers anew.
442//! The same sockets may be given again.
443//!
444//! What to do: bind new UDP sockets, add a host candidate for each with `sdp_mid` set to the
445//! event's first mid, signal the candidates the engine surfaces, end the generation with an
446//! empty candidate for that mid. Keep the previous sockets open and reading: the selected
447//! pair keeps carrying the transport's packets until a pair on a new socket is selected
448//! (`SelectedCandidatePairChange` on that transport), or until the transport closes; close
449//! them then, after a few seconds more: the peer selects on its own and may still send to
450//! the previous address for a while. The engine's own gathering follows the new host candidates by itself: it asks
451//! the STUN servers from each new base (the probes from a refused base end, so no mapped
452//! address of the previous socket is announced), allocates TURN again from a base that is not
453//! refused, and gives the ICE-TCP candidates of the address again (RFC 8842 section 5.1 asks a
454//! new 3-tuple of unordered transports only; their listener is kept).
455//!
456//! A local offer that is rolled back takes its ICE restart back (RFC 9429 section 5.7: "Any
457//! resources or candidates that were allocated by the abandoned local description are
458//! discarded"), its `OnLocalCandidatesNeeded` included, although the event has already
459//! fired: the transport holds its previous candidates again, on the previous addresses,
460//! which are no longer refused, and the candidates given for the abandoned generation are
461//! dropped (the peer, which ignored or never got that offer, drops the ones signalled to it:
462//! they carry the abandoned username fragment). The application then
463//!
464//! - keeps the previous sockets open and no longer counts them as retired: they carry the
465//! transport's packets as before the offer;
466//! - closes the sockets it bound for the abandoned generation (or keeps them for the next
467//! one: an address that no association used is not refused);
468//! - waits for the next `OnLocalCandidatesNeeded`: the answer to the peer's offer (the usual
469//! end of an offer collision, W3C webrtc-pc "perfect negotiation") fires one when it sets up
470//! a new association, and so does the next offer of this side that asks for one.
471//!
472//! The transport's candidates are what
473//! [`RTCIceTransport::get_local_candidates`](peer_connection::transport::RTCIceTransport::get_local_candidates)
474//! returns, so the application can match its sockets against them once the connection is
475//! back in the stable state (`OnSignalingStateChangeEvent(Stable)`). `rtci-stream-driver`'s
476//! `PeerDriver` does that.
477//!
478//! ```no_run
479//! use rtci::peer_connection::RTCPeerConnection;
480//! use rtci::peer_connection::event::{RTCLocalCandidatesNeededEvent, RTCPeerConnectionEvent};
481//! use rtci::peer_connection::transport::RTCIceCandidateInit;
482//! use std::net::UdpSocket;
483//!
484//! fn on_event(
485//! pc: &mut RTCPeerConnection,
486//! sockets: &mut Vec<UdpSocket>,
487//! event: RTCPeerConnectionEvent,
488//! ) -> Result<(), Box<dyn std::error::Error>> {
489//! if let RTCPeerConnectionEvent::OnLocalCandidatesNeeded(needed) = event {
490//! let RTCLocalCandidatesNeededEvent { mids, sdp_mline_index, .. } = needed;
491//! // A new port on the same interface (port 0: the system picks a free one).
492//! let socket = UdpSocket::bind("192.0.2.1:0")?;
493//! let local = socket.local_addr()?;
494//! pc.add_local_candidate(RTCIceCandidateInit {
495//! candidate: format!(
496//! "candidate:1 1 udp 2130706431 {} {} typ host",
497//! local.ip(),
498//! local.port()
499//! ),
500//! sdp_mid: mids.first().cloned(),
501//! sdp_mline_index,
502//! ..Default::default()
503//! })?;
504//! // The end of this transport's generation.
505//! pc.add_local_candidate(RTCIceCandidateInit {
506//! sdp_mid: mids.first().cloned(),
507//! ..Default::default()
508//! })?;
509//! // The previous sockets stay open until a pair on the new one is selected.
510//! sockets.push(socket);
511//! }
512//! Ok(())
513//! }
514//! ```
515//!
516//! The reference driver, `rtci-stream-driver`, does all of this by itself (its `peer`
517//! module).
518//!
519//! An application with one fixed socket, which cannot move to a new port, turns it off with
520//! [`SettingEngineBuilder::with_dtls_new_association_on_previous_addresses(true)`](peer_connection::configuration::setting_engine::SettingEngineBuilder::with_dtls_new_association_on_previous_addresses):
521//! the candidates are kept, their addresses accepted, and no event fires; the new association
522//! then shares the previous one's 3-tuple, which RFC 8842 section 5.1 allows only when the
523//! peer allocates a new one.
524//!
525//! [`RTCPeerConnection::add_local_candidate`]: peer_connection::RTCPeerConnection::add_local_candidate
526//! [`RTCPeerConnection::ice_transport_sections`]: peer_connection::RTCPeerConnection::ice_transport_sections
527//!
528//! ## Common Patterns
529//!
530//! ### Configuring Interceptors (NACK, TWCC, RTCP Reports)
531//!
532//! Interceptors process RTP/RTCP packets as they flow through the media pipeline.
533//! Use the [`interceptor_registry`](peer_connection::configuration::interceptor_registry) module
534//! to configure packet loss recovery, congestion control, and quality monitoring:
535//!
536//! ```no_run
537//! # use std::time::Instant;
538//! use rtci::peer_connection::RTCPeerConnectionBuilder;
539//! use rtci::peer_connection::configuration::RTCConfigurationBuilder;
540//! use rtci::peer_connection::configuration::media_engine::MediaEngine;
541//! use rtci::peer_connection::configuration::interceptor_registry::{
542//! Registry, register_default_interceptors,
543//! };
544//!
545//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
546//! // Create media engine with default codecs
547//! let mut media_engine = MediaEngine::default();
548//!
549//! // Collect the default interceptors:
550//! // - NACK: Packet loss recovery for video
551//! // - RTCP Reports: Sender/Receiver quality statistics
552//! // - TWCC Receiver: Congestion control feedback
553//! //
554//! // `build` sorts them wire-to-application, so the order these are asked for does not matter.
555//! let registry = Registry::new();
556//! let registry = register_default_interceptors(registry, &mut media_engine)?;
557//!
558//! // Build peer connection with interceptors
559//! let mut pc = RTCPeerConnectionBuilder::new()
560//! .with_media_engine(media_engine)
561//! .with_interceptor_registry(registry)
562//! .build(Instant::now())?;
563//! # Ok(())
564//! # }
565//! ```
566//!
567//! For custom interceptor configuration:
568//!
569//! ```no_run
570//! # use std::time::Instant;
571//! use rtci::peer_connection::RTCPeerConnectionBuilder;
572//! use rtci::peer_connection::configuration::RTCConfigurationBuilder;
573//! use rtci::peer_connection::configuration::media_engine::MediaEngine;
574//! use rtci::peer_connection::configuration::interceptor_registry::{
575//! Registry,
576//! configure_nack,
577//! configure_rtcp_reports,
578//! configure_twcc,
579//! };
580//!
581//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
582//! let mut media_engine = MediaEngine::default();
583//! let registry = Registry::new();
584//!
585//! // Ask for what you want, in any order — each interceptor carries the slot it belongs in.
586//! let registry = configure_nack(registry, &mut media_engine); // Packet loss recovery
587//! let registry = configure_rtcp_reports(registry); // SR/RR statistics
588//! let registry = configure_twcc(registry, &mut media_engine)?; // Full TWCC (sender + receiver)
589//!
590//! let registry = registry;
591//!
592//! let mut pc = RTCPeerConnectionBuilder::new()
593//! .with_media_engine(media_engine)
594//! .with_interceptor_registry(registry)
595//! .build(Instant::now())?;
596//! # Ok(())
597//! # }
598//! ```
599//!
600//! #### One connection type, whatever the chain
601//!
602//! A chain is a flat list of interceptors, and
603//! [`RTCPeerConnection`](peer_connection::RTCPeerConnection) has one concrete type no matter what
604//! the list contains. Nothing that holds a connection has to know how its chain was assembled,
605//! chains can be chosen at runtime, and connections built from different chains share a
606//! collection:
607//!
608//! ```no_run
609//! # use std::time::Instant;
610//! use rtci::peer_connection::configuration::interceptor_registry::{
611//! Registry, register_default_interceptors,
612//! };
613//! use rtci::peer_connection::configuration::media_engine::MediaEngine;
614//! use rtci::peer_connection::{RTCPeerConnection, RTCPeerConnectionBuilder};
615//!
616//! // No type parameter: this struct does not have to know the chain.
617//! struct Session {
618//! peer_connection: RTCPeerConnection,
619//! }
620//!
621//! # fn example(with_nack: bool) -> Result<(), Box<dyn std::error::Error>> {
622//! let mut media_engine = MediaEngine::default();
623//! let registry =
624//! register_default_interceptors(Registry::new(), &mut media_engine)?;
625//!
626//! let mut sessions: Vec<Session> = Vec::new();
627//! sessions.push(Session {
628//! peer_connection: RTCPeerConnectionBuilder::new()
629//! .with_media_engine(media_engine)
630//! .with_interceptor_registry(registry)
631//! .build(Instant::now())?,
632//! });
633//! # Ok(())
634//! # }
635//! ```
636//!
637//! The cost is one virtual call per interceptor per packet, which is nothing beside SRTP.
638//! Static dispatch is still the default — keep the generic form when the chain is fixed at
639//! compile time.
640//!
641//! ### Creating and Using Data Channels
642//!
643//! ```no_run
644//! use rtci::peer_connection::RTCPeerConnection;
645//! use rtci::peer_connection::configuration::RTCConfiguration;
646//! use rtci::data_channel::RTCDataChannelInit;
647//! use rtci::peer_connection::event::RTCPeerConnectionEvent;
648//! use std::time::Instant;
649//! use rtci::peer_connection::message::{RTCMessage, TaggedRTCMessage};
650//! use rtci::sansio::Protocol;
651//! use bytes::BytesMut;
652//!
653//! # fn example(mut pc: RTCPeerConnection) -> Result<(), Box<dyn std::error::Error>> {
654//! // Create data channel with ordered, reliable delivery
655//! let init = RTCDataChannelInit {
656//! ordered: true,
657//! max_retransmits: None,
658//! ..Default::default()
659//! };
660//!
661//! let mut dc = pc.create_data_channel("my-channel", Some(init))?;
662//! let channel_id = dc.id();
663//!
664//! // Send text message
665//! dc.send_text(Instant::now(), "Hello, WebRTC!")?;
666//!
667//! // Send binary message
668//! dc.send(Instant::now(), BytesMut::from(&[0x01, 0x02, 0x03, 0x04][..]))?;
669//!
670//! // Later, retrieve the data channel by ID
671//! if let Some(mut dc) = pc.data_channel(channel_id) {
672//! dc.send_text(Instant::now(), "Another message")?;
673//! }
674//!
675//! // Receive messages in event loop
676//! while let Some(TaggedRTCMessage { message, .. }) = pc.poll_read() {
677//! if let RTCMessage::DataChannelMessage(channel_id, msg) = message {
678//! if msg.is_string {
679//! let text = String::from_utf8_lossy(&msg.data);
680//! println!("Received text: {text}");
681//! } else {
682//! println!("Received binary: {} bytes", msg.data.len());
683//! }
684//! }
685//! }
686//! # Ok(())
687//! # }
688//! ```
689//!
690//! ### Adding Media Tracks with Codecs
691//!
692//! ```no_run
693//! use rtci::peer_connection::RTCPeerConnection;
694//! use rtci::media_stream::MediaStreamTrack;
695//! use rtci::rtp_transceiver::rtp_sender::{RTCRtpCodec, RTCRtpCodecParameters, RtpCodecKind};
696//! use rtci::rtp_transceiver::rtp_sender::{RTCRtpEncodingParameters, RTCRtpCodingParameters};
697//! use rtci::peer_connection::configuration::media_engine::{MIME_TYPE_VP8, MIME_TYPE_OPUS};
698//!
699//! # fn example(mut pc: RTCPeerConnection) -> Result<(), Box<dyn std::error::Error>> {
700//! // Configure VP8 video codec
701//! let video_codec = RTCRtpCodec {
702//! mime_type: MIME_TYPE_VP8.to_owned(),
703//! clock_rate: 90000,
704//! channels: 0,
705//! sdp_fmtp_line: "".to_owned(),
706//! rtcp_feedback: vec![],
707//! };
708//!
709//! // Create video track
710//! let video_track = MediaStreamTrack::new(
711//! "stream-id".to_string(),
712//! "video-track-id".to_string(),
713//! "video-label".to_string(),
714//! RtpCodecKind::Video,
715//! vec![RTCRtpEncodingParameters {
716//! rtp_coding_parameters: RTCRtpCodingParameters {
717//! ssrc: Some(rand::random::<u32>()),
718//! ..Default::default()
719//! },
720//! codec: video_codec.clone(),
721//! ..Default::default()
722//! }],
723//! );
724//!
725//! // Add track to peer connection
726//! let sender_id = pc.add_track(video_track)?;
727//!
728//! // Send RTP packets
729//! if let Some(mut sender) = pc.rtp_sender(sender_id) {
730//! // sender.write_rtp(Instant::now(), rtp_packet)?;
731//! }
732//! # Ok(())
733//! # }
734//! ```
735//!
736//! ### Receiving Media Tracks
737//!
738//! ```no_run
739//! use rtci::peer_connection::RTCPeerConnection;
740//! use rtci::peer_connection::event::{RTCPeerConnectionEvent, RTCTrackEvent};
741//! use rtci::peer_connection::message::{RTCMessage, TaggedRTCMessage};
742//! use rtci::sansio::Protocol;
743//! use std::collections::HashMap;
744//!
745//! # fn example(mut pc: RTCPeerConnection) -> Result<(), Box<dyn std::error::Error>> {
746//! // Track mapping for received tracks
747//! let mut track_to_receiver = HashMap::new();
748//!
749//! // Handle track events
750//! while let Some(event) = pc.poll_event() {
751//! if let RTCPeerConnectionEvent::OnTrack(track_event) = event {
752//! match track_event {
753//! RTCTrackEvent::OnOpen(init) => {
754//! println!("New track: track_id={}, receiver_id={:?}",
755//! init.track_id, init.receiver_id);
756//! track_to_receiver.insert(init.track_id.clone(), init.receiver_id);
757//! }
758//! RTCTrackEvent::OnClose(track_id) => {
759//! println!("Track closed: {track_id}");
760//! track_to_receiver.remove(&track_id);
761//! }
762//! _ => {}
763//! }
764//! }
765//! }
766//!
767//! // Receive RTP packets
768//! while let Some(TaggedRTCMessage { message, .. }) = pc.poll_read() {
769//! if let RTCMessage::RtpPacket(track_id, rtp_packet) = message {
770//! println!("RTP packet on track {}: {} bytes",
771//! track_id, rtp_packet.payload.len());
772//!
773//! // Access receiver to get track metadata
774//! if let Some(&receiver_id) = track_to_receiver.get(&track_id) {
775//! if let Some(receiver) = pc.rtp_receiver(receiver_id) {
776//! let track = receiver.track();
777//! let ssrcs: Vec<u32> = track.ssrcs().collect();
778//! println!(" SSRCs: {:?}, Kind: {:?}", ssrcs, track.kind());
779//! }
780//! }
781//! }
782//! }
783//! # Ok(())
784//! # }
785//! ```
786//!
787//! ### Sending RTCP Packets (e.g., PLI for keyframes)
788//!
789//! ```no_run
790//! use rtci::peer_connection::RTCPeerConnection;
791//! use rtci::rtp_transceiver::RTCRtpReceiverId;
792//! use rtci::rtcp::payload_feedbacks::picture_loss_indication::PictureLossIndication;
793//! use std::time::Instant;
794//!
795//! # fn example(mut pc: RTCPeerConnection, receiver_id: RTCRtpReceiverId, media_ssrc: u32)
796//! # -> Result<(), Box<dyn std::error::Error>> {
797//! // Request keyframe by sending Picture Loss Indication (PLI)
798//! if let Some(mut receiver) = pc.rtp_receiver(receiver_id) {
799//! receiver.write_rtcp(Instant::now(), vec![Box::new(PictureLossIndication {
800//! sender_ssrc: 0,
801//! media_ssrc,
802//! })])?;
803//! }
804//! # Ok(())
805//! # }
806//! ```
807//!
808//! ## Specification Compliance
809//!
810//! This implementation follows these specifications:
811//!
812//! - [W3C WebRTC 1.0] - Main WebRTC API specification
813//! - [RFC 9429] - JSEP: JavaScript Session Establishment Protocol
814//! - [RFC 8866] - SDP: Session Description Protocol
815//! - [RFC 8445] - ICE: Interactive Connectivity Establishment
816//! - [RFC 6347] - DTLS: Datagram Transport Layer Security
817//! - [RFC 8831] - WebRTC Data Channels
818//! - [RFC 3550] - RTP: Real-time Transport Protocol
819//!
820//! [W3C WebRTC 1.0]: https://www.w3.org/TR/webrtc/
821//! [RFC 9429]: https://datatracker.ietf.org/doc/html/rfc9429
822//! [RFC 8866]: https://datatracker.ietf.org/doc/html/rfc8866
823//! [RFC 8445]: https://datatracker.ietf.org/doc/html/rfc8445
824//! [RFC 6347]: https://datatracker.ietf.org/doc/html/rfc6347
825//! [RFC 8831]: https://datatracker.ietf.org/doc/html/rfc8831
826//! [RFC 3550]: https://datatracker.ietf.org/doc/html/rfc3550
827//!
828//! ## Further Reading
829//!
830//! - [Sans-I/O Approach](https://sans-io.readthedocs.io/) - Detailed explanation of sans-I/O design
831//! - [WebRTC for the Curious](https://webrtcforthecurious.com/) - Comprehensive WebRTC guide
832//! - [MDN WebRTC API](https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API) - Browser WebRTC documentation
833
834#![doc(
835 html_logo_url = "https://raw.githubusercontent.com/webrtc-rs/webrtc-rs.github.io/master/res/rtc.png"
836)]
837#![warn(rust_2018_idioms)]
838#![warn(missing_docs)]
839#![allow(dead_code)]
840
841pub use {
842 crypto, datachannel, dtls, ice, interceptor, mdns, media, rtcp, rtp, sansio, sctp, sdp, sframe,
843 shared, srtp, stun, turn,
844};
845
846pub mod data_channel;
847/// Entry points for stateful fuzz targets. Gated behind `cfg(fuzzing)`; not part of the
848/// supported API.
849#[cfg(fuzzing)]
850pub mod fuzzing;
851pub mod media_stream;
852pub mod peer_connection;
853pub mod rtp_transceiver;
854pub mod statistics;
855
856// The README's Rust examples are doctests: CI compiles them (they are `no_run`, they bind
857// sockets), so the README cannot drift from the API.
858#[cfg(doctest)]
859#[doc = include_str!("../README.md")]
860struct ReadmeDoctests;