str0m/lib.rs
1// Changed by Alakazam Labs for sew-str0m; the fork's patches are listed in its README.
2//! **This is sew-str0m, a fork of [str0m](https://github.com/algesten/str0m)** that Alakazam
3//! Labs publishes for Sew, Alakazam Labs' chat and voice core: upstream str0m 0.25.0 plus
4//! patches. Depend on it as `str0m = { package = "sew-str0m", version = "0.25.6" }`; the library
5//! name stays `str0m`. It is used instead of upstream str0m; a build that also pulls in
6//! upstream str0m gets both, and their types do not mix. It works with upstream's `str0m-*`
7//! backend crates. The crate's [README](https://crates.io/crates/sew-str0m) lists the patches
8//! and the defaults that differ from upstream, and where to report problems. The rest of this
9//! page is upstream's documentation.
10//!
11//! <image
12//! src="https://user-images.githubusercontent.com/227204/226143511-66fe5264-6ab7-47b9-9551-90ba7e155b96.svg"
13//! alt="str0m logo" >
14//! </image>
15//!
16//! A Sans I/O WebRTC implementation in Rust.
17//!
18//! This is a [Sans I/O][sansio] implementation meaning the `Rtc` instance itself is not doing any network
19//! talking. Furthermore it has no internal threads or async tasks. All operations are happening from the
20//! calls of the public API.
21//!
22//! This is deliberately not a standard `RTCPeerConnection` API since that isn't a great fit for Rust.
23//! See more details in below section.
24//!
25//! # Join us
26//!
27//! We are discussing str0m things on Discord. Join us using this [invitation link][discord].
28//!
29//! <image width="300px"
30//! src="https://user-images.githubusercontent.com/227204/209446544-f8a8d673-cb1b-4144-a0f2-42307b8d8869.gif"
31//! alt="silly clip showing video playing" >
32//! </image>
33//!
34//! # Usage
35//!
36//! The [`chat`][x-chat] example shows how to connect multiple browsers
37//! together and act as an SFU (Selective Forwarding Unit). The example
38//! multiplexes all traffic over one server UDP socket and uses two threads
39//! (one for the web server, and one for the SFU loop).
40//!
41//! ## TLS
42//!
43//! For the browser to do WebRTC, all traffic must be under TLS. The
44//! project ships with a self-signed certificate that is used for the
45//! examples. The certificate is for hostname `str0m.test` since TLD .test
46//! should never resolve to a real DNS name.
47//!
48//! ```text
49//! cargo run --example chat
50//! ```
51//!
52//! The log should prompt you to connect a browser to https://10.0.0.103:3000 – this will
53//! most likely cause a security warning that you must get the browser to accept.
54//!
55//! The [`http-post`][x-post] example roughly illustrates how to receive
56//! media data from a browser client. The example is single threaded and
57//! is a bit simpler than the chat. It is a good starting point to understand the API.
58//!
59//! ```text
60//! cargo run --example http-post
61//! ```
62//!
63//! ### Real example
64//!
65//! To see how str0m is used in a real project, check out [BitWHIP][bitwhip] –
66//! a CLI WebRTC Agent written in Rust.
67//!
68//! ## Passive
69//!
70//! For passive connections, i.e. where the media and initial OFFER is
71//! made by a remote peer, we need these steps to open the connection.
72//!
73//! ```no_run
74//! # use std::time::Instant;
75//! # use str0m::{Rtc, Candidate};
76//! // Instantiate a new Rtc instance.
77//! let mut rtc = Rtc::new(Instant::now());
78//!
79//! // Add some ICE candidate such as a locally bound UDP port.
80//! let addr = "1.2.3.4:5000".parse().unwrap();
81//! let candidate = Candidate::host(addr, "udp").unwrap();
82//! rtc.add_local_candidate(candidate);
83//!
84//! // Accept an incoming offer from the remote peer
85//! // and get the corresponding answer.
86//! let offer = todo!();
87//! let answer = rtc.sdp_api().accept_offer(offer).unwrap();
88//!
89//! // Forward the answer to the remote peer.
90//!
91//! // Go to _run loop_
92//! ```
93//!
94//! ## Active
95//!
96//! Active connections means we are making the inital OFFER and waiting for a
97//! remote ANSWER to start the connection.
98//!
99//! ```no_run
100//! # use std::time::Instant;
101//! # use str0m::{Rtc, Candidate};
102//! # use str0m::media::{MediaKind, Direction};
103//! // Instantiate a new Rtc instance.
104//! let mut rtc = Rtc::new(Instant::now());
105//!
106//! // Add some ICE candidate such as a locally bound UDP port.
107//! let addr = "1.2.3.4:5000".parse().unwrap();
108//! let candidate = Candidate::host(addr, "udp").unwrap();
109//! rtc.add_local_candidate(candidate);
110//!
111//! // Create a `SdpApi`. The change lets us make multiple changes
112//! // before sending the offer.
113//! let mut change = rtc.sdp_api();
114//!
115//! // Do some change. A valid OFFER needs at least one "m-line" (media).
116//! let mid = change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None);
117//!
118//! // Get the offer.
119//! let (offer, pending) = change.apply().unwrap();
120//!
121//! // Forward the offer to the remote peer and await the answer.
122//! // How to transfer this is outside the scope for this library.
123//! let answer = todo!();
124//!
125//! // Apply answer.
126//! rtc.sdp_api().accept_answer(pending, answer).unwrap();
127//!
128//! // Go to _run loop_
129//! ```
130//!
131//! ## Run loop
132//!
133//! ### The single-mutation invariant
134//!
135//! str0m's API has one strict contract that the run loop is built around:
136//!
137//! > **Every mutation of an `Rtc` instance must be followed by a complete
138//! > drain of `poll_output` until it returns `Output::Timeout`, before the
139//! > next mutation on the same `Rtc`.**
140//!
141//! A "mutation" is anything that takes `&mut Rtc` (directly or through a
142//! handle obtained from it). The common ones are:
143//!
144//! - `Rtc::handle_input` — feeding a network packet or a timeout
145//! - `Writer::write` / `Writer::request_keyframe` — sending media
146//! - `Channel::write` — sending data channel data
147//! - `SdpApi::apply` / `DirectApi::*` — negotiation
148//! - `Rtc::add_local_candidate` / `Rtc::add_remote_candidate`
149//!
150//! Always: **mutate → drain to `Timeout` → mutate → drain to `Timeout` → …**
151//!
152//! Doing two mutations back-to-back without draining in between, or
153//! waiting on I/O while the engine still has output queued, leaves the
154//! engine in an inconsistent state and produces wrong behavior. Mutations
155//! issued from inside the drain loop (e.g. calling `Writer::write` in
156//! response to an `Output::Event`) are fine — the drain loop naturally
157//! continues calling `poll_output` afterward and so the invariant holds.
158//!
159//! ### Canonical shape
160//!
161//! Driving an `Rtc` forward follows the same six-step shape, regardless
162//! of sync or async:
163//!
164//! 1. **Wait** for one of: the next timeout firing, an incoming network
165//! packet, or the application wanting to perform a mutation (e.g.
166//! write media).
167//! 2. **Perform that ONE mutation** — feed `Input` to `handle_input`, or
168//! call into a writer / channel / SDP API.
169//! 3. **Poll** `Rtc::poll_output`.
170//! 4. **Handle** the output: `Output::Transmit` is sent on the socket,
171//! `Output::Event` is dispatched to the application, `Output::Timeout`
172//! records the next deadline.
173//! 5. **Goto 3** until `poll_output` returns `Output::Timeout`. Only then
174//! is the engine fully drained.
175//! 6. The returned timeout is what we wait on next — **goto 1**.
176//!
177//! ```no_run
178//! # use str0m::{Rtc, Output, IceConnectionState, Event, Input};
179//! # use str0m::net::{Receive, Protocol};
180//! # use std::io::ErrorKind;
181//! # use std::net::UdpSocket;
182//! # use std::time::{Duration, Instant};
183//! # let mut rtc = Rtc::new(Instant::now());
184//! // A UdpSocket we obtained _somehow_.
185//! let socket: UdpSocket = todo!();
186//!
187//! // Buffer for reading incoming UDP packets.
188//! let mut buf = vec![0; 2000];
189//!
190//! loop {
191//! // === Steps 3-5: drain poll_output until we get the next timeout. ===
192//! let timeout = loop {
193//! match rtc.poll_output().unwrap() {
194//! // Step 5: a Timeout exits the drain loop.
195//! Output::Timeout(t) => break t,
196//!
197//! // Step 4: transmit on the socket and keep draining.
198//! // The destination IP comes from the ICE agent and may
199//! // change during the session.
200//! Output::Transmit(t) => {
201//! socket.send_to(&t.contents, t.destination).unwrap();
202//! }
203//!
204//! // Step 4: hand the event to the application and keep draining.
205//! // Events are mainly incoming media data from the remote peer,
206//! // but also data channel data and statistics.
207//! Output::Event(e) => {
208//! if e == Event::IceConnectionStateChange(IceConnectionState::Disconnected) {
209//! return;
210//! }
211//! // TODO: handle other events here, such as incoming media data.
212//! }
213//! }
214//! };
215//!
216//! // === Step 1: wait for ONE of: the timeout firing, an incoming
217//! // packet, or application-side data. The example below uses a
218//! // blocking UDP socket with a read timeout. With async you would
219//! // `select!` over multiple futures; with application-side data you
220//! // would also include a channel.
221//! //
222//! // set_read_timeout(Some(ZERO)) is not allowed, so clamp to >= 1ms.
223//! let duration = (timeout - Instant::now()).max(Duration::from_millis(1));
224//! socket.set_read_timeout(Some(duration)).unwrap();
225//! buf.resize(2000, 0);
226//!
227//! // === Step 2: take ONE event and feed it as Input ===
228//! let input = match socket.recv_from(&mut buf) {
229//! Ok((n, source)) => {
230//! buf.truncate(n);
231//! Input::Receive(
232//! Instant::now(),
233//! Receive {
234//! proto: Protocol::Udp,
235//! source,
236//! destination: socket.local_addr().unwrap(),
237//! contents: buf.as_slice().try_into().unwrap(),
238//! },
239//! )
240//! }
241//!
242//! // The socket read timed out — feed Input::Timeout to advance
243//! // the engine to the deadline. WouldBlock is the unix error,
244//! // TimedOut is the windows error.
245//! Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => {
246//! Input::Timeout(Instant::now())
247//! }
248//!
249//! Err(e) => {
250//! eprintln!("Error: {:?}", e);
251//! return;
252//! }
253//! };
254//!
255//! rtc.handle_input(input).unwrap();
256//!
257//! // === Step 6: back to the top of the outer loop (goto step 3). ===
258//! }
259//! ```
260//!
261//! ## Sending media data
262//!
263//! When creating the media, we can decide which codecs to support, and they
264//! are negotiated with the remote side. Each codec corresponds to a
265//! "payload type" (PT). To send media data we need to figure out which PT
266//! to use when sending.
267//!
268//! ```no_run
269//! # use str0m::Rtc;
270//! # use str0m::media::Mid;
271//! # let rtc: Rtc = todo!();
272//! // Obtain mid from Event::MediaAdded
273//! let mid: Mid = todo!();
274//!
275//! // Create a media writer for the mid.
276//! let writer = rtc.writer(mid).unwrap();
277//!
278//! // Get the payload type (pt) for the wanted codec.
279//! let pt = writer.payload_params().nth(0).unwrap().pt();
280//!
281//! // Write the data
282//! let wallclock = todo!(); // Absolute time of the data
283//! let media_time = todo!(); // Media time, in RTP time
284//! let data: &[u8] = todo!(); // Actual data
285//! writer.write(pt, wallclock, media_time, data).unwrap();
286//! ```
287//!
288//! `Writer::write` is a mutation, so the
289//! [single-mutation invariant](#the-single-mutation-invariant) applies:
290//! after writing, drain `Rtc::poll_output` to `Output::Timeout` before
291//! the next mutation on this `Rtc`.
292//!
293//! ## Media time, wallclock and local time
294//!
295//! str0m has three main concepts of time. "now", media time and wallclock.
296//!
297//! ### Now
298//!
299//! Some calls in str0m, such as `Rtc::handle_input` takes a `now` argument
300//! that is a `std::time::Instant`. These calls "drive the time forward" in
301//! the internal state. This is used for everything like deciding when
302//! to produce various feedback reports (RTCP) to remote peers, to
303//! bandwidth estimation (BWE) and statistics.
304//!
305//! Str0m has _no internal clock_ calls. I.e. str0m never calls
306//! `Instant::now()` itself. All time is external input. That means it's
307//! possible to construct test cases driving an `Rtc` instance faster
308//! than realtime (see the [integration tests][intg]).
309//!
310//! ### Media time
311//!
312//! Each RTP header has a 32 bit number that str0m calls _media time_.
313//! Media time is in some time base that is dependent on the codec,
314//! however all codecs in str0m use 90_000Hz for video and 48_000Hz
315//! for audio.
316//!
317//! For video the `MediaTime` type is `<timestamp>/90_000` str0m extends
318//! the 32 bit number in the RTP header to 64 bit taking into account
319//! "rollover". 64 bit is such a large number the user doesn't need to
320//! think about rollovers.
321//!
322//! ### Wallclock
323//!
324//! With _wallclock_ str0m means the time a sample of media was produced
325//! at an originating source. I.e. if we are talking into a microphone the
326//! wallclock is the NTP time the sound is sampled.
327//!
328//! We can't know the exact wallclock for media from a remote peer since
329//! not every device is synchronized with NTP. Every sender does
330//! periodically produce a Sender Report (SR) that contains the peer's
331//! idea of its wallclock, however this number can be very wrong compared to
332//! "real" NTP time.
333//!
334//! Furthermore, not all remote devices will have a linear idea of
335//! time passing that exactly matches the local time. A minute on the
336//! remote peer might not be exactly one minute locally.
337//!
338//! These timestamps become important when handling simultaneous audio from
339//! multiple peers.
340//!
341//! When writing media we need to provide str0m with an estimated wallclock.
342//! The simplest strategy is to only trust local time and use arrival time
343//! of the incoming UDP packet. Another simple strategy is to lock some
344//! time T at the first UDP packet, and then offset each wallclock using
345//! `MediaTime`, i.e. for video we could have `T + <media time>/90_000`
346//!
347//! A production worthy SFU probably needs an even more sophisticated
348//! strategy weighing in all possible time sources to get a good estimate
349//! of the remote wallclock for a packet.
350//!
351//! # Crypto backends
352//!
353//! str0m supports multiple crypto backends via feature flags. The default is `aws-lc-rs`.
354//!
355//! | Feature | Crate | DTLS | Platforms |
356//! |-------------------|-----------------------|----------------------------------|-----------|
357//! | `aws-lc-rs` | `str0m-aws-lc-rs` | dimpl + AWS-LC-RS | All |
358//! | `rust-crypto` | `str0m-rust-crypto` | dimpl + RustCrypto | All |
359//! | `openssl` | `str0m-openssl` | OpenSSL (DTLS 1.2 only) | All |
360//! | `openssl-dimpl` | `str0m-openssl` | dimpl + OpenSSL crypto | All |
361//! | `apple-crypto` | `str0m-apple-crypto` | dimpl + Apple CryptoKit | macOS/iOS |
362//! | `wincrypto` | `str0m-wincrypto` | dimpl + Windows CNG | Windows |
363//! | `wincrypto-dimpl` | `str0m-wincrypto` | Alias for `wincrypto` | Windows |
364//!
365//! If multiple backend features are enabled, str0m automatically selects the backend in this
366//! priority order: `aws-lc-rs`, `rust-crypto`, `openssl-dimpl`, `openssl`, `apple-crypto`
367//! (Apple platforms only), `wincrypto` (Windows only).
368//!
369//! If you disable the default features, you MUST explicitly configure an alternative
370//! crypto backend either process-wide or per-instance.
371//!
372//! ## Process-wide default
373//!
374//! For applications, the easiest is to set a process-wide default at startup.
375//! Note that you can use any backend crate directly without enabling its feature flag:
376//!
377//! ```no_run
378//! // Set process default (will panic if called twice)
379//! // No need to enable the "rust-crypto" feature flag
380//! str0m_rust_crypto::default_provider().install_process_default();
381//! ```
382//!
383//! ## Crypto provider per Rtc instance
384//!
385//! ```no_run
386//! use std::sync::Arc;
387//! use std::time::Instant;
388//! use str0m::Rtc;
389//!
390//! let rtc = Rtc::builder()
391//! .set_crypto_provider(Arc::new(str0m_rust_crypto::default_provider()))
392//! .build(Instant::now());
393//! ```
394//!
395//! # Project status
396//!
397//! Str0m was originally developed by Martin Algesten of
398//! [Lookback][lookback]. We use str0m for a specific use case: str0m as a
399//! server SFU (as opposed to peer-2-peer). That means we are heavily
400//! testing and developing the parts needed for our use case. Str0m is
401//! intended to be an all-purpose WebRTC library, which means it also
402//! works for peer-2-peer, though that aspect has received less testing.
403//!
404//! Performance is very good, there have been some work the discover and
405//! optimize bottlenecks. Such efforts are of course never ending with
406//! diminishing returns. While there are no glaringly obvious performance
407//! bottlenecks, more work is always welcome – both algorithmically and
408//! allocation/cloning in hot paths etc.
409//!
410//! # Design
411//!
412//! Output from the `Rtc` instance can be grouped into three kinds.
413//!
414//! 1. Events (such as receiving media or data channel data).
415//! 2. Network output. Data to be sent, typically from a UDP socket.
416//! 3. Timeouts. Indicates when the instance next expects a time input.
417//!
418//! Input to the `Rtc` instance is:
419//!
420//! 1. User operations (such as sending media or data channel data).
421//! 2. Network input. Typically read from a UDP socket.
422//! 3. Timeouts. As obtained from the output above.
423//!
424//! The correct use can be seen in the above [Run loop](#run-loop) or in the
425//! examples.
426//!
427//! Sans I/O is a pattern where we turn both network input/output as well
428//! as time passing into external input to the API. This means str0m has
429//! no internal threads, just an enormous state machine that is driven
430//! forward by different kinds of input.
431//!
432//! ## Frame or RTP level?
433//!
434//! Str0m defaults to the "frame level" which treats the RTP as an internal detail. The user
435//! will thus mainly interact with:
436//!
437//! 1. [`Event::MediaData`][evmed] to receive full frames (audio frames or video frames).
438//! 2. [`Writer::write`][writer] to write full frames.
439//! 3. [`Writer::request_keyframe`][reqkey] to request keyframes.
440//!
441//! ### Frame level
442//!
443//! All codecs such as h264, vp8, vp9 and opus outputs what we call
444//! "Frames". A frame has a very specific meaning for video, but this
445//! project uses it in a broader sense, where a frame is either a video
446//! or audio time stamped chunk of encoded data that typically represents
447//! a chunk of audio, or _one single frame for video_.
448//!
449//! Frames are not suitable to use directly in UDP (RTP) packets - for
450//! one they are too big. Frames are therefore further chunked up by
451//! codec specific payloaders into RTP packets.
452//!
453//! ### RTP mode
454//!
455//! Str0m also provides an RTP level API. This would be similar to many other
456//! RTP libraries where the RTP packets themselves are the API surface
457//! towards the user (when building an SFU one would often talk about "forwarding
458//! RTP packets", while with str0m we can also "forward frames"). Using
459//! this API requires a deeper knowledge of RTP and WebRTC.
460//!
461//! To enable RTP mode
462//!
463//! ```
464//! # use std::time::Instant;
465//! # use str0m::Rtc;
466//! let rtc = Rtc::builder()
467//! // Enable RTP mode for this Rtc instance.
468//! // This disables `MediaEvent` and the `Writer::write` API.
469//! .set_rtp_mode(true)
470//! .build(Instant::now());
471//! ```
472//!
473//! RTP mode gives us some new API points.
474//!
475//! 1. [`Event::RtpPacket`][rtppak] emitted for every incoming RTP packet. Empty packets for bandwidth
476//! estimation are silently discarded.
477//! 2. [`StreamTx::write_rtp`][wrtrtp] to write outgoing RTP packets.
478//! 3. [`StreamRx::request_keyframe`][reqkey2] to request keyframes from remote.
479//!
480//! ## NIC enumeration and TURN (and STUN)
481//!
482//! The [ICE RFC][ice] talks about "gathering ice candidates". This means
483//! inspecting the local network interfaces and potentially binding UDP
484//! sockets on each usable interface. Since str0m is Sans I/O, this part
485//! is outside the scope of what str0m does. How the user figures out
486//! local IP addresses, via config or via looking up local NICs is not
487//! something str0m cares about.
488//!
489//! TURN is a way of obtaining IP addresses that can be used as fallback
490//! in case direct connections fail. We consider TURN similar to
491//! enumerating local network interfaces – it's a way of obtaining
492//! sockets.
493//!
494//! All discovered candidates, be they local (NIC) or remote sockets
495//! (TURN), are added to str0m and str0m will perform the task of ICE
496//! agent, forming "candidate pairs" and figuring out the best connection
497//! while the actual task of sending the network traffic is left to the
498//! user.
499//!
500//! ## The importance of `&mut self`
501//!
502//! Rust shines when we can eschew locks and heavily rely `&mut` for data
503//! write access. Since str0m has no internal threads, we never have to
504//! deal with shared data. Furthermore the the internals of the library is
505//! organized such that we don't need multiple references to the same
506//! entities. In str0m there are no `Rc`, `Mutex`, `mpsc`, `Arc`(*), or
507//! other locks.
508//!
509//! This means all input to the lib can be modelled as
510//! `handle_something(&mut self, something)`.
511//!
512//! (*) Ok. There is one `Arc` if you use Windows where we also require openssl.
513//!
514//! ## Not a standard WebRTC "Peer Connection" API
515//!
516//! The library deliberately steps away from the "standard" WebRTC API as
517//! seen in JavaScript and/or [webrtc-rs][webrtc-rs] (or [Pion][pion] in Go).
518//! There are few reasons for this.
519//!
520//! First, in the standard API, events are callbacks, which are not a
521//! great fit for Rust. Callbacks require some kind of reference
522//! (ownership?) over the entity the callback is being dispatched
523//! upon. I.e. if in Rust we want `pc.addEventListener(x)`, `x` needs
524//! to be wholly owned by `pc`, or have some shared reference (like
525//! `Arc`). Shared references means shared data, and to get mutable shared
526//! data, we will need some kind of lock. i.e. `Arc<Mutex<EventListener>>`
527//! or similar.
528//!
529//! As an alternative we could turn all events into `mpsc` channels, but
530//! listening to multiple channels is awkward without async.
531//!
532//! Second, in the standard API, entities like `RTCPeerConnection` and
533//! `RTCRtpTransceiver`, are easily clonable and/or long lived
534//! references. I.e. `pc.getTranscievers()` returns objects that can be
535//! retained and owned by the caller. This pattern is fine for garbage
536//! collected or reference counted languages, but not great with Rust.
537//!
538//! ## Panics, Errors and unwraps
539//!
540//! Str0m adheres to [fail-fast][ff]. That means rather than brushing state
541//! bugs under the carpet, it panics. We make a distinction between errors and
542//! bugs.
543//!
544//! * Errors are as a result of incorrect or impossible to understand user input.
545//! * Bugs are broken internal invariants (assumptions).
546//!
547//! If you scan the str0m code you find a few `unwrap()` (or `expect()`). These
548//! will (should) always be accompanied by a code comment that explains why the
549//! unwrap is okay. This is an internal invariant, a state assumption that
550//! str0m is responsible for maintaining.
551//!
552//! We do not believe it's correct to change every `unwrap()`/`expect()` into
553//! `unwrap_or_else()`, `if let Some(x) = x { ... }` etc, because doing so
554//! brushes an actual problem (an incorrect assumption) under the carpet. Trying
555//! to hobble along with an incorrect state would at best result in broken
556//! behavior, at worst a security risk!
557//!
558//! Panics are our friends: *panic means bug*
559//!
560//! And also: str0m should *never* panic on any user input. If you encounter a panic,
561//! please report it!
562//!
563//! ### Catching panics
564//!
565//! Panics should be incredibly rare, or we have a serious problem as a project. For an SFU,
566//! it might not be ideal if str0m encounters a bug and brings the entire server down with it.
567//!
568//! For those who want an extra level of safety, we recommend looking at [`catch_unwind`][catch]
569//! to safely discard a faulty `Rtc` instance. Since `Rtc` has no internal threads, locks or async
570//! tasks, discarding the instance never risk poisoning locks or other issues that can happen
571//! when catching a panic.
572//!
573//! ## FAQ
574//!
575//! ### Features
576//!
577//! Below is a brief comparison of features between libWebRTC and str0m to help you determine
578//! if str0m is suitable for your project.
579//!
580//! | Feature | str0m | libWebRTC |
581//! | ------------------------ | ------------------ | ------------------ |
582//! | Peer Connection API | :x: | :white_check_mark: |
583//! | SDP | :white_check_mark: | :white_check_mark: |
584//! | ICE | :white_check_mark: | :white_check_mark: |
585//! | Data Channels | :white_check_mark: | :white_check_mark: |
586//! | Send/Recv Reports | :white_check_mark: | :white_check_mark: |
587//! | Transport Wide CC | :white_check_mark: | :white_check_mark: |
588//! | Bandwidth Estimation | :white_check_mark: | :white_check_mark: |
589//! | Simulcast | :white_check_mark: | :white_check_mark: |
590//! | NACK | :white_check_mark: | :white_check_mark: |
591//! | Packetize | :white_check_mark: | :white_check_mark: |
592//! | Fixed Depacketize Buffer | :white_check_mark: | :white_check_mark: |
593//! | Adaptive Jitter Buffer | :x: | :white_check_mark: |
594//! | Video/audio capture | :x: | :white_check_mark: |
595//! | Video/audio encode | :x: | :white_check_mark: |
596//! | Video/audio decode | :x: | :white_check_mark: |
597//! | Audio render | :x: | :white_check_mark: |
598//! | Turn | :x: | :white_check_mark: |
599//! | Network interface enum | :x: | :white_check_mark: |
600//!
601//! ### Platform Support
602//!
603//! Platforms str0m is compiled and tested on:
604//!
605//! | Platform | Compiled | Tested |
606//! | ------------------------------ | ----------------- | ----------------- |
607//! | `x86_64-pc-windows-msvc` | :white_check_mark:| :white_check_mark:|
608//! | `x86_64-unknown-linux-gnu` | :white_check_mark:| :white_check_mark:|
609//! | `x86_64-apple-darwin` | :white_check_mark:| :white_check_mark:|
610//! | `aarch64-apple-darwin` | :white_check_mark:| :white_check_mark:|
611//! | `aarch64-unknown-linux-gnu` | :white_check_mark:| :white_check_mark:|
612//! | `aarch64-pc-windows-msvc` | :white_check_mark:| :white_check_mark:|
613//! | `aarch64-apple-ios` | :white_check_mark:| :x: |
614//! | `aarch64-linux-android` | :white_check_mark:| :x: |
615//!
616//! If your platform isn't listed but is supported by Rust, we'd love for you to give str0m a try and
617//! share your experience. We greatly appreciate your feedback!
618//!
619//! ### Does str0m support IPv4, IPv6, UDP and TCP?
620//!
621//! Certainly! str0m fully support IPv4, IPv6, UDP and TCP protocols.
622//!
623//! ### Can I utilize str0m with any Rust async runtime?
624//!
625//! Absolutely! str0m is fully sync, ensuring that it integrates seamlessly with any Rust async
626//! runtime you opt for.
627//!
628//! ### Can I create a client with str0m?
629//!
630//! Of course! You have the freedom to create a client with str0m. However, please note that some
631//! common client features like media encoding, decoding, and capture are not included in str0m. But
632//! don't let that stop you from building amazing applications!
633//!
634//! ### Can I use str0m in a media server?
635//!
636//! Yes! str0m excels as a server component with support for both RTP API and Frame API. You can
637//! easily build that recording server or SFU you dreamt of in Rust!
638//!
639//! ### Can I deploy the chat example into production?
640//!
641//! While the chat example showcases how to use str0m's API, it's not intended for production use or
642//! heavy load. Writing a full-featured SFU or MCU (Multipoint Control Unit) is a significant
643//! undertaking, involving various design decisions based on production requirements.
644//!
645//! ### Discovered a bug? Here's how to share it with us
646//!
647//! We'd love to hear about it! Please submit an issue and consider joining our Discord community
648//! to discuss further. For a seamless reporting experience, refer to this exemplary
649//! bug report: <https://github.com/algesten/str0m/issues/382>. We appreciate your contribution
650//! to making str0m better!
651//!
652//! ### I am allergic to SDP can you help me?
653//!
654//! Yes use the direct API!
655//!
656//! [sansio]: https://sans-io.readthedocs.io
657//! [quinn]: https://github.com/quinn-rs/quinn
658//! [pion]: https://github.com/pion/webrtc
659//! [webrtc-rs]: https://github.com/webrtc-rs/webrtc
660//! [discord]: https://discord.gg/e2CC8UYebP
661//! [zulip]: https://str0m.zulipchat.com
662//! [ice]: https://www.rfc-editor.org/rfc/rfc8445
663//! [lookback]: https://www.lookback.com
664//! [x-post]: https://github.com/algesten/str0m/blob/main/examples/http-post.rs
665//! [x-chat]: https://github.com/algesten/str0m/blob/main/examples/chat.rs
666//! [intg]: https://github.com/algesten/str0m/blob/main/tests/unidirectional.rs#L12
667//! [ff]: https://en.wikipedia.org/wiki/Fail-fast
668//! [catch]: https://doc.rust-lang.org/std/panic/fn.catch_unwind.html
669//! [evmed]: https://docs.rs/str0m/*/str0m/enum.Event.html#variant.MediaData
670//! [writer]: https://docs.rs/str0m/*/str0m/media/struct.Writer.html#method.write
671//! [reqkey]: https://docs.rs/str0m/*/str0m/media/struct.Writer.html#method.request_keyframe
672//! [rtppak]: https://docs.rs/str0m/*/str0m/enum.Event.html#variant.RtpPacket
673//! [wrtrtp]: https://docs.rs/str0m/*/str0m/rtp/struct.StreamTx.html#method.write_rtp
674//! [reqkey2]: https://docs.rs/str0m/*/str0m/rtp/struct.StreamRx.html#method.request_keyframe
675//! [bitwhip]: https://github.com/bitwhip/bitwhip
676
677// Avoid rewriting existing code: nested conditions are often more readable than long if-chains.
678#![allow(clippy::collapsible_if)]
679#![forbid(unsafe_code)]
680#![allow(clippy::new_without_default)]
681#![allow(clippy::bool_to_int_with_if)]
682#![allow(clippy::assertions_on_constants)]
683#![allow(clippy::manual_range_contains)]
684#![allow(clippy::get_first)]
685#![allow(clippy::needless_lifetimes)]
686#![allow(clippy::precedence)]
687#![allow(clippy::doc_overindented_list_items)]
688#![allow(clippy::uninlined_format_args)]
689#![allow(mismatched_lifetime_syntaxes)]
690#![deny(clippy::needless_pass_by_ref_mut)]
691#![deny(missing_docs)]
692
693#[macro_use]
694extern crate tracing;
695
696use bwe::{Bwe, BweKind};
697use change::{DirectApi, SdpApi};
698use rtp::RawPacket;
699use std::fmt;
700use std::net::SocketAddr;
701use std::sync::Arc;
702use std::time::Instant;
703use str0m_proto::Pii;
704use streams::RtpPacket;
705use streams::StreamPaused;
706use util::InstantExt;
707
708// Identity `drv::ToStatic` (`Static = Self`) for the `Copy` identity types.
709// Used instead of `#[derive(drv::Input)]` because the derive's generated
710// shadow type isn't `Eq`/`Hash`/`Borrow<Self>`, so it can't be a `HashMap`
711// key inside a `#[drv::memo]` projection; `Static = Self` can. `eq_static`
712// defers to each type's own `PartialEq`. Each module invokes this for its
713// own types.
714#[cfg(feature = "drv")]
715macro_rules! drv_identity_copy {
716 ($($t:ty),* $(,)?) => {
717 $(
718 impl drv::ToStatic for $t {
719 type Static = $t;
720 fn to_static(&self) -> $t { *self }
721 fn eq_static(&self, other: &$t) -> bool { self == other }
722 }
723 )*
724 };
725}
726#[cfg(feature = "drv")]
727pub(crate) use drv_identity_copy;
728
729/// Cryptographic provider traits and implementations.
730///
731/// This module provides the traits for pluggable cryptographic operations
732/// used in DTLS, SRTP, and STUN.
733pub mod crypto;
734use crypto::Fingerprint;
735
736mod dtls;
737use crate::crypto::dtls::DtlsOutput;
738use crate::crypto::{CryptoProvider, DtlsError, from_feature_flags};
739use crate::dtls::is_would_block;
740use dtls::Dtls;
741
742use is::IceAgent;
743use is::IceAgentEvent;
744pub use is::{Candidate, CandidateBuilder, CandidateKind, IceConnectionState, IceCreds};
745
746#[path = "config.rs"]
747mod config_mod;
748pub use config_mod::RtcConfig;
749
750/// Default target MTU used when none is configured.
751pub use io::DATAGRAM_MTU_TARGET;
752/// Upper bound that the target endpoint of [`RtcConfig::set_mtu`] must satisfy.
753pub use io::DATAGRAM_MTU_TARGET_MAX;
754/// Lower bound that the target endpoint of [`RtcConfig::set_mtu`] must satisfy.
755pub use io::DATAGRAM_MTU_TARGET_MIN;
756/// Default warning threshold for over-sized packets.
757pub use io::DATAGRAM_MTU_WARN;
758
759/// Additional configuration.
760pub mod config {
761 pub use super::crypto::dtls::{DtlsCert, DtlsVersion, KeyingMaterial};
762 pub use super::crypto::{CryptoProvider, Fingerprint};
763}
764
765/// Low level ICE access.
766// The ICE API is not necessary to interact with directly for "regular"
767// use of str0m. This is exported for other libraries that want to
768// reuse str0m's ICE implementation. This is now in the `is` crate.
769#[doc(hidden)]
770pub mod ice {
771 pub use is::IceCreds;
772 pub use is::stun::{StunMessage, StunMessageBuilder, StunPacket, TransId};
773 pub use is::{IceAgent, IceAgentEvent};
774 pub use is::{LocalPreference, default_local_preference};
775}
776
777mod io;
778use io::DatagramRecvInner;
779
780mod packet;
781
782#[path = "rtp/mod.rs"]
783mod rtp_;
784use rtp_::{Bitrate, DataSize};
785
786/// Low level RTP access.
787pub mod rtp {
788 /// Feedback for RTP.
789 pub mod rtcp {
790 pub use crate::rtp_::AppSpecificFeedback;
791 pub use crate::rtp_::{Descriptions, ExtendedReport, Fir, Goodbye, Nack, Pli};
792 pub use crate::rtp_::{Dlrr, NackEntry, ReceptionReport, ReportBlock};
793 pub use crate::rtp_::{FirEntry, ReceiverReport, SenderInfo, SenderReport, Twcc};
794 pub use crate::rtp_::{ReportList, Rrtr, Rtcp, Sdes, SdesType};
795 }
796 use self::rtcp::Rtcp;
797
798 /// Video Layers Allocation RTP Header Extension
799 pub mod vla;
800 pub use crate::rtp_::{AbsCaptureTime, ExtensionValues, UserExtensionValues};
801 pub use crate::rtp_::{Extension, ExtensionMap, ExtensionSerializer};
802
803 pub use crate::packet::{
804 RedBlock, RedDecoder, RedEncoder, RedundantBlock, Vp8Descriptor, Vp8DescriptorError,
805 Vp8Patch, Vp8PatchBuilder, Vp8PatchError,
806 };
807 pub use crate::rtp_::{RtpHeader, SeqNo, Ssrc, VideoOrientation};
808 pub use crate::streams::{
809 NackPolicy, RtpPacket, RtpWrite, StreamPaused, StreamRx, StreamTx, StreamTxQueueInfo,
810 };
811
812 /// Debug output of the unencrypted RTP and RTCP packets.
813 ///
814 /// Enable using [`RtcConfig::enable_raw_packets()`][crate::RtcConfig::enable_raw_packets].
815 /// This clones data, and is therefore expensive.
816 /// Should not be enabled outside of tests and troubleshooting.
817 #[derive(Debug)]
818 pub enum RawPacket {
819 /// Sent RTCP.
820 RtcpTx(Rtcp),
821 /// Incoming RTCP.
822 RtcpRx(Rtcp),
823 /// Sent RTP.
824 RtpTx(RtpHeader, Vec<u8>),
825 /// Incoming RTP.
826 RtpRx(RtpHeader, Vec<u8>),
827 }
828}
829
830pub(crate) mod pacer;
831
832#[path = "bwe/mod.rs"]
833pub(crate) mod bwe_;
834
835/// Bandwidth estimation.
836pub mod bwe {
837 pub use crate::bwe_::api::*;
838}
839
840mod sctp;
841use sctp::{RtcSctp, SctpEvent, SctpInitData};
842
843mod sdp;
844
845pub mod format;
846use format::CodecConfig;
847
848pub mod channel;
849use channel::{Channel, ChannelData, ChannelHandler, ChannelId};
850
851pub mod media;
852use media::AppSpecificFeedback;
853use media::SenderFeedback;
854use media::{Direction, Media, Mid, Pt, Rid, Writer};
855use media::{KeyframeRequest, KeyframeRequestKind};
856use media::{MediaAdded, MediaChanged, MediaData};
857
858pub mod change;
859
860mod util;
861use util::{Soonest, not_happening};
862
863mod poll;
864use crate::poll::Readiness;
865
866mod session;
867use session::Session;
868
869pub mod stats;
870
871use stats::{CandidatePairStats, CandidateStats, MediaEgressStats, MediaIngressStats};
872use stats::{PeerStats, Stats, StatsEvent, StatsSnapshot};
873
874mod streams;
875
876pub mod error;
877
878/// Network related types to get socket data in/out of [`Rtc`].
879pub mod net {
880 pub use crate::io::{DatagramRecv, DatagramSend, Protocol, Receive, TcpType, Transmit};
881}
882
883const VERSION: &str = env!("CARGO_PKG_VERSION");
884
885pub use error::RtcError;
886
887/// Instance that does WebRTC. Main struct of the entire library.
888///
889/// ## Usage
890///
891/// The canonical run loop is: perform exactly one mutation (typically
892/// `handle_input` with a network packet or timeout), then drain
893/// `poll_output` until it returns `Output::Timeout`, then wait for the
894/// next event. **Every mutation must be followed by a full drain before
895/// the next mutation.** See the [crate docs](crate#run-loop) for the full
896/// explanation of the single-mutation invariant.
897///
898/// ```no_run
899/// # use std::time::Instant;
900/// # use str0m::{Rtc, Output, Input};
901/// let mut rtc = Rtc::new(Instant::now());
902///
903/// loop {
904/// // Drain poll_output until it returns the next timeout.
905/// let timeout = loop {
906/// match rtc.poll_output().unwrap() {
907/// Output::Timeout(t) => break t,
908/// Output::Transmit(t) => {
909/// // TODO: Send t.contents to t.destination on a UDP socket.
910/// }
911/// Output::Event(e) => {
912/// // TODO: Handle event.
913/// }
914/// }
915/// };
916///
917/// // TODO: Wait for ONE of: `timeout` firing, an incoming network
918/// // packet, or application-side data to send. Build an
919/// // `Input` from whichever fires first.
920/// let input: Input = todo!();
921///
922/// rtc.handle_input(input).unwrap();
923/// }
924/// ```
925pub struct Rtc {
926 state: RtcState,
927 ice: IceAgent,
928 dtls: Dtls,
929 dtls_connected: bool,
930 dtls_buf: Vec<u8>,
931 next_dtls_timeout: Option<Instant>,
932 sctp: RtcSctp,
933 chan: ChannelHandler,
934 stats: Option<Stats>,
935 session: Session,
936 remote_fingerprint: Option<Fingerprint>,
937 remote_addrs: Vec<SocketAddr>,
938 send_addr: Option<SendAddr>,
939 need_init_time: bool,
940 last_now: Instant,
941 peer_bytes_rx: u64,
942 peer_bytes_tx: u64,
943 change_counter: usize,
944 last_timeout_reason: Reason,
945 crypto_provider: Arc<crate::crypto::CryptoProvider>,
946 fingerprint_verification: bool,
947 close_dtls_started: bool,
948 // Signals which halves of the tree may need re-polling. Written locally by
949 // the components that mutate, via the `Wake` guard handed down the tree;
950 // read (and cleared) by `poll_output`. See the `poll` module.
951 readiness: Readiness,
952 // Last timeout returned by `poll_output`, reused while the readiness says
953 // the timeout is still valid.
954 cached_timeout: Instant,
955}
956
957#[derive(Clone, Copy, PartialEq, Eq)]
958enum RtcState {
959 Alive,
960 Closing,
961 Closed,
962}
963
964struct SendAddr {
965 proto: net::Protocol,
966 source: SocketAddr,
967 destination: SocketAddr,
968}
969
970/// Events produced by [`Rtc::poll_output()`].
971#[derive(Debug)]
972#[non_exhaustive]
973#[rustfmt::skip]
974pub enum Event {
975 // =================== ICE related events ===================
976
977 /// Emitted when we got ICE connection and established DTLS.
978 Connected,
979
980 /// ICE connection state changes tells us whether the [`Rtc`] instance is
981 /// connected to the peer or not.
982 IceConnectionStateChange(IceConnectionState),
983
984 // =================== Media related events ==================
985
986 /// Upon detecting the remote side adding new media to the session.
987 ///
988 /// For locally added media, this event never fires. Thus it can be thought of as an
989 /// "SDP only" event. If the direct API is used on both sides, the declaration is local \
990 /// to both sides and the event never fires.
991 ///
992 /// The [`Media`] instance is available via [`Rtc::media()`].
993 MediaAdded(MediaAdded),
994
995 /// Incoming media data sent by the remote peer.
996 MediaData(MediaData),
997
998 /// Changes to the media may be emitted.
999 ///
1000 ///. Currently only covers a change of direction.
1001 MediaChanged(MediaChanged),
1002
1003 // =================== Data channel related events ===================
1004
1005 /// A data channel has opened.
1006 ///
1007 /// The string is the channel label which is set by the opening peer and can
1008 /// be used to identify the purpose of the channel when there are more than one.
1009 ///
1010 /// The negotiation is to set up an SCTP association via DTLS. Subsequent data
1011 /// channels reuse the same association.
1012 ///
1013 /// Upon this event, the [`Channel`] can be obtained via [`Rtc::channel()`].
1014 ///
1015 /// For [`SdpApi`]: The first ever data channel results in an SDP
1016 /// negotiation, and this events comes at the end of that.
1017 ChannelOpen(ChannelId, String),
1018
1019 /// Incoming data channel data from the remote peer.
1020 ChannelData(ChannelData),
1021
1022 /// A data channel has been closed.
1023 ChannelClose(ChannelId),
1024
1025 /// A data channel's buffered amount has dropped below the configured threshold.
1026 ChannelBufferedAmountLow(ChannelId),
1027
1028 // =================== Statistics and BWE related events ===================
1029
1030 /// Statistics event for the Rtc instance
1031 ///
1032 /// Includes both media traffic (rtp payload) as well as all traffic
1033 PeerStats(PeerStats),
1034
1035 /// Aggregated statistics for each media (mid, rid) in the ingress direction
1036 MediaIngressStats(MediaIngressStats),
1037
1038 /// Aggregated statistics for each media (mid, rid) in the egress direction
1039 MediaEgressStats(MediaEgressStats),
1040
1041 /// A new estimate from the bandwidth estimation subsystem.
1042 EgressBitrateEstimate(BweKind),
1043
1044 // =================== RTP related events ===================
1045
1046 /// Incoming keyframe request for media that we are sending to the remote peer.
1047 ///
1048 /// The request is either PLI (Picture Loss Indication) or FIR (Full Intra Request).
1049 KeyframeRequest(KeyframeRequest),
1050
1051 /// Whether an incoming encoded stream is paused.
1052 ///
1053 /// This means the stream has not received any data for some time (default 1.5 seconds).
1054 StreamPaused(StreamPaused),
1055
1056 /// Sender feedback for an incoming stream, derived from RTCP SR.
1057 SenderFeedback(SenderFeedback),
1058
1059 /// Incoming RTP data.
1060 RtpPacket(RtpPacket),
1061
1062 /// Incoming application-specific Payload-Specific Feedback (PSFB FMT=15, PT=206).
1063 ///
1064 /// Emitted when a non-REMB FMT=15 RTCP PSFB message is received. The payload
1065 /// is opaque and application-defined (RFC 4585 Section 6.4).
1066 AppSpecificFeedback(AppSpecificFeedback),
1067
1068 /// The remote DTLS connection or SCTP association has closed.
1069 ///
1070 /// When this event is emitted, `Rtc` starts local shutdown signals and
1071 /// remains alive only while [`Rtc::poll_output()`] drains pending local
1072 /// close output such as RTCP BYE and the DTLS close_notify response.
1073 Closed,
1074
1075 /// Debug output of incoming and outgoing RTCP/RTP packets.
1076 ///
1077 /// Enable using [`RtcConfig::enable_raw_packets()`].
1078 /// This clones data, and is therefore expensive.
1079 /// Should not be enabled outside of tests and troubleshooting.
1080 RawPacket(Box<RawPacket>),
1081
1082 /// For internal testing only.
1083 ///
1084 /// The probe cluster config when a probe fires.
1085 #[cfg(feature = "_internal_test_exports")]
1086 Probe(crate::bwe_::ProbeClusterConfig),
1087}
1088
1089impl Event {
1090 /// Reference to the [`RawPacket`] if this is indeed an `Event::RawPacket`.
1091 pub fn as_raw_packet(&self) -> Option<&RawPacket> {
1092 if let Self::RawPacket(boxed) = &self {
1093 Some(&**boxed)
1094 } else {
1095 None
1096 }
1097 }
1098}
1099
1100/// Input as expected by [`Rtc::handle_input()`]. Either network data or a timeout.
1101#[derive(Debug)]
1102#[allow(clippy::large_enum_variant)] // We purposely don't want to allocate.
1103pub enum Input<'a> {
1104 /// A timeout without any network input.
1105 Timeout(Instant),
1106 /// Network input. The [`Instant`] is the time the packet was received from the socket -
1107 /// not necessarily "now" (e.g. when UDP demultiplexing runs on a separate thread). It
1108 /// drives time forward when more recent than the last "now" the instance has seen.
1109 Receive(Instant, net::Receive<'a>),
1110}
1111
1112/// Output produced by [`Rtc::poll_output()`]
1113#[allow(clippy::large_enum_variant)]
1114#[derive(Debug)]
1115pub enum Output {
1116 /// When the [`Rtc`] instance expects an [`Input::Timeout`].
1117 Timeout(Instant),
1118
1119 /// Network data that is to be sent.
1120 Transmit(net::Transmit),
1121
1122 /// Some event such as media data arriving from the remote peer or connection events.
1123 Event(Event),
1124}
1125
1126pub use crate::pacer::PacerReason;
1127
1128/// The reason for the next [`Output::Timeout`].
1129///
1130/// This enum is not considered stable API and may change in minor revisions.
1131#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1132#[non_exhaustive]
1133pub enum Reason {
1134 /// No timeout scheduled.
1135 ///
1136 /// The timeout value is in the distant future.
1137 #[default]
1138 NotHappening,
1139
1140 /// The DTLS subsystem.
1141 ///
1142 /// Only relevant during handshaking.
1143 DTLS,
1144
1145 /// The ICE agent.
1146 ///
1147 /// Includes checking candidate pairs and various cleanups.
1148 Ice,
1149
1150 /// The SCTP subsystem.
1151 ///
1152 /// Things like handling retransmissions and keep-alive checks.
1153 Sctp,
1154
1155 /// Data channels.
1156 ///
1157 /// Scheduled when we need to open allocations using SCTP.
1158 Channel,
1159
1160 /// Stats gathering (if enabled).
1161 ///
1162 /// Periodic gathering of statistics.
1163 Stats,
1164
1165 /// Regular RTP feedback.
1166 ///
1167 /// Receiver reports (RR) and sender reports (SR).
1168 Feedback,
1169
1170 /// Sending of RTP NACK.
1171 ///
1172 /// When missing packets are discovered, a NACK is scheduled.
1173 /// Retries for each packet wait for the receive-stream RTT plus 5 ms,
1174 /// using a 100 ms RTT until a measurement is available.
1175 Nack,
1176
1177 /// Reporting of TWCC (if enabled).
1178 ///
1179 /// All incoming RTP packets are reported using TWCC. Enabled via SDP if both
1180 /// sides support it.
1181 Twcc,
1182
1183 /// RTP streams not receiving data goes into a paused state.
1184 ///
1185 /// Whenever an RTP receive stream receives data, a new timeout is scheduled.
1186 PauseCheck,
1187
1188 /// Preprocessing of RTP packets to be sent.
1189 ///
1190 /// Housekeeping task in RTP send streams.
1191 SendStream,
1192
1193 /// Packetizing of media into RTP data (if used).
1194 ///
1195 /// Written media data needs packetizing. This is not used in RTP mode.
1196 Packetize,
1197
1198 /// A complete video frame is waiting for missing earlier packets or its timeout.
1199 ReceiveReorder,
1200
1201 /// Pacer doing things.
1202 Pacer(PacerReason),
1203
1204 /// The delay controller of the BWE subsystem.
1205 BweDelayControl,
1206
1207 /// The probe controller of the BWE subsystem.
1208 BweProbeControl,
1209
1210 /// The probe estimator of the BWE subsystem.
1211 BweProbeEstimator,
1212}
1213
1214impl Rtc {
1215 /// Creates a new instance with default settings.
1216 ///
1217 /// To configure the instance, use [`RtcConfig`].
1218 ///
1219 /// ```
1220 /// use std::time::Instant;
1221 /// use str0m::Rtc;
1222 ///
1223 /// let rtc = Rtc::new(Instant::now());
1224 /// ```
1225 pub fn new(start: Instant) -> Self {
1226 let config = RtcConfig::default();
1227 Self::new_from_config(config, start).expect("Failed to create Rtc from default config")
1228 }
1229
1230 /// Creates a config builder that configures an [`Rtc`] instance.
1231 ///
1232 /// ```
1233 /// # use std::time::Instant;
1234 /// # use str0m::Rtc;
1235 /// let rtc = Rtc::builder()
1236 /// .set_ice_lite(true)
1237 /// .build(Instant::now());
1238 /// ```
1239 pub fn builder() -> RtcConfig {
1240 RtcConfig::new()
1241 }
1242
1243 pub(crate) fn new_from_config(config: RtcConfig, start: Instant) -> Result<Self, RtcError> {
1244 let crypto_provider = config
1245 .crypto_provider
1246 .clone()
1247 // If crypto_provider is not set in config, check process default
1248 .or_else(|| CryptoProvider::get_default().cloned().map(Arc::new))
1249 // Or fall back on feature flags
1250 .or_else(|| Some(Arc::new(from_feature_flags())))
1251 // from_feature_flags panics already, so we should never see
1252 // this expect message.
1253 .expect("a crash earlier if no crypto provider was set");
1254
1255 let session = Session::new(&config);
1256
1257 // Capture before any partial moves of `config` below.
1258 let mtu = config.mtu.clone();
1259
1260 let local_creds = config.local_ice_credentials.unwrap_or_else(IceCreds::new);
1261 let mut ice = IceAgent::with_hmac(local_creds, crypto_provider.sha1_hmac_provider);
1262 if config.ice_lite {
1263 ice.set_ice_lite(config.ice_lite);
1264 }
1265
1266 if let Some(initial_stun_rto) = config.initial_stun_rto {
1267 ice.set_initial_stun_rto(initial_stun_rto);
1268 }
1269
1270 if let Some(max_stun_rto) = config.max_stun_rto {
1271 ice.set_max_stun_rto(max_stun_rto);
1272 }
1273
1274 if let Some(max_stun_retransmits) = config.max_stun_retransmits {
1275 ice.set_max_stun_retransmits(max_stun_retransmits);
1276 }
1277
1278 ice.set_mtu(mtu.clone());
1279
1280 let dtls_cert = config
1281 .dtls_cert
1282 .or_else(|| crypto_provider.dtls_provider.generate_certificate())
1283 .expect(
1284 "No DTLS certificate provided and the crypto provider cannot generate one. \
1285 Either provide a certificate via RtcConfig::set_dtls_cert or use a \
1286 crypto provider that supports certificate generation.",
1287 );
1288
1289 let mut sctp = RtcSctp::new(*mtu.start(), config.sctp_max_message_size);
1290 if config.snap_enabled {
1291 sctp.enable_snap();
1292 }
1293 sctp.set_max_buffered_amount(config.sctp_max_buffered_amount);
1294
1295 Ok(Rtc {
1296 state: RtcState::Alive,
1297 ice,
1298 dtls: Dtls::new(
1299 &dtls_cert,
1300 crypto_provider.dtls_provider,
1301 crypto_provider.sha256_provider,
1302 start,
1303 config.dtls_version,
1304 mtu,
1305 )
1306 .expect("DTLS to init without problem"),
1307 dtls_connected: false,
1308 dtls_buf: vec![0; 2000],
1309 next_dtls_timeout: None,
1310 session,
1311 sctp,
1312 chan: ChannelHandler::default(),
1313 stats: config.stats_interval.map(Stats::new),
1314 remote_fingerprint: None,
1315 remote_addrs: vec![],
1316 send_addr: None,
1317 need_init_time: true,
1318 last_now: start,
1319 peer_bytes_rx: 0,
1320 peer_bytes_tx: 0,
1321 change_counter: 0,
1322 last_timeout_reason: Reason::NotHappening,
1323 crypto_provider,
1324 fingerprint_verification: config.fingerprint_verification,
1325 close_dtls_started: false,
1326 readiness: Readiness::armed(),
1327 cached_timeout: start,
1328 })
1329 }
1330
1331 /// Tests if this instance is still working.
1332 ///
1333 /// Certain events will straight away disconnect the `Rtc` instance, such as
1334 /// the DTLS fingerprint from the setup not matching that of the TLS negotiation
1335 /// (since that would potentially indicate a MITM attack!).
1336 ///
1337 /// The instance can be manually disconnected using [`Rtc::disconnect()`].
1338 ///
1339 /// During shutdown, this remains `true` until [`Rtc::poll_output()`]
1340 /// has drained pending local close output. App-facing operations such as
1341 /// [`Rtc::writer()`] and [`Rtc::channel()`] are unavailable during that
1342 /// closing drain.
1343 ///
1344 /// ```
1345 /// # use std::time::Instant;
1346 /// # use str0m::Rtc;
1347 /// let mut rtc = Rtc::new(Instant::now());
1348 ///
1349 /// assert!(rtc.is_alive());
1350 ///
1351 /// rtc.disconnect();
1352 /// assert!(!rtc.is_alive());
1353 /// ```
1354 pub fn is_alive(&self) -> bool {
1355 self.state != RtcState::Closed
1356 }
1357
1358 /// Force disconnects the instance making [`Rtc::is_alive()`] return `false`.
1359 ///
1360 /// This makes [`Rtc::poll_output`] and [`Rtc::handle_input`] go inert and not
1361 /// produce anymore network output or events.
1362 ///
1363 /// ```
1364 /// # use std::time::Instant;
1365 /// # use str0m::Rtc;
1366 /// let mut rtc = Rtc::new(Instant::now());
1367 ///
1368 /// rtc.disconnect();
1369 /// assert!(!rtc.is_alive());
1370 /// ```
1371 pub fn disconnect(&mut self) {
1372 self.state = RtcState::Closed;
1373 }
1374
1375 /// Add a local ICE candidate. Local candidates are socket addresses the `Rtc` instance
1376 /// use for communicating with the peer.
1377 ///
1378 /// If the candidate is accepted by the `Rtc` instance, it will return `Some` with a reference
1379 /// to it. You should then signal this candidate to the remote peer.
1380 ///
1381 /// This library has no built-in discovery of local network addresses on the host
1382 /// or NATed addresses via a STUN server or TURN server. The user of the library
1383 /// is expected to add new local candidates as they are discovered.
1384 ///
1385 /// In WebRTC lingo, the `Rtc` instance is permanently in a mode of [Trickle Ice][1]. It's
1386 /// however advisable to add at least one local candidate before starting the instance.
1387 ///
1388 /// ```
1389 /// # use std::time::Instant;
1390 /// # use str0m::{Rtc, Candidate};
1391 /// let mut rtc = Rtc::new(Instant::now());
1392 ///
1393 /// let a = "127.0.0.1:5000".parse().unwrap();
1394 /// let c = Candidate::host(a, "udp").unwrap();
1395 ///
1396 /// rtc.add_local_candidate(c);
1397 /// ```
1398 ///
1399 /// [1]: https://www.rfc-editor.org/rfc/rfc8838.txt
1400 pub fn add_local_candidate(&mut self, c: Candidate) -> Option<&Candidate> {
1401 // ICE is an external crate and can't take a `Wake`; adding a candidate
1402 // can start connectivity checks (transmits) and arm timers.
1403 self.wake_all();
1404 self.ice.add_local_candidate(c)
1405 }
1406
1407 /// Add a remote ICE candidate. Remote candidates are addresses of the peer.
1408 ///
1409 /// For [`SdpApi`]: Remote candidates are typically added via
1410 /// receiving a remote [`SdpOffer`][change::SdpOffer] or [`SdpAnswer`][change::SdpAnswer].
1411 ///
1412 /// However for the case of [Trickle Ice][1], this is the way to add remote candidates
1413 /// that are "trickled" from the other side.
1414 ///
1415 /// ```
1416 /// # use std::time::Instant;
1417 /// # use str0m::{Rtc, Candidate};
1418 /// let mut rtc = Rtc::new(Instant::now());
1419 ///
1420 /// let a = "1.2.3.4:5000".parse().unwrap();
1421 /// let c = Candidate::host(a, "udp").unwrap();
1422 ///
1423 /// rtc.add_remote_candidate(c);
1424 /// ```
1425 ///
1426 /// [1]: https://www.rfc-editor.org/rfc/rfc8838.txt
1427 pub fn add_remote_candidate(&mut self, c: Candidate) {
1428 // ICE is an external crate and can't take a `Wake`; see above.
1429 self.wake_all();
1430 self.ice.add_remote_candidate(c);
1431 }
1432
1433 /// Checks if we are connected.
1434 ///
1435 /// This tests if we have ICE connection, DTLS and the SRTP crypto derived contexts are up.
1436 pub fn is_connected(&self) -> bool {
1437 self.ice.state().is_connected() && self.dtls_connected && self.session.is_connected()
1438 }
1439
1440 /// Make changes to the Rtc session via SDP.
1441 ///
1442 /// ```no_run
1443 /// # use std::time::Instant;
1444 /// # use str0m::Rtc;
1445 /// # use str0m::media::{MediaKind, Direction};
1446 /// # use str0m::change::SdpAnswer;
1447 /// let mut rtc = Rtc::new(Instant::now());
1448 ///
1449 /// let mut changes = rtc.sdp_api();
1450 /// let mid_audio = changes.add_media(MediaKind::Audio, Direction::SendOnly, None, None, None);
1451 /// let mid_video = changes.add_media(MediaKind::Video, Direction::SendOnly, None, None, None);
1452 ///
1453 /// let (offer, pending) = changes.apply().unwrap();
1454 /// let json = serde_json::to_vec(&offer).unwrap();
1455 ///
1456 /// // Send json OFFER to remote peer. Receive an answer back.
1457 /// let answer: SdpAnswer = todo!();
1458 ///
1459 /// rtc.sdp_api().accept_answer(pending, answer).unwrap();
1460 /// ```
1461 pub fn sdp_api(&mut self) -> SdpApi {
1462 SdpApi::new(self)
1463 }
1464
1465 /// Makes direct changes to the Rtc session.
1466 ///
1467 /// This is a low level API. For "normal" use via SDP, see [`Rtc::sdp_api()`].
1468 pub fn direct_api(&mut self) -> DirectApi {
1469 DirectApi::new(self)
1470 }
1471
1472 /// Send outgoing media data (frames) or request keyframes.
1473 ///
1474 /// Returns `None` if the direction isn't sending (`sendrecv` or `sendonly`).
1475 ///
1476 /// ```no_run
1477 /// # use std::time::Instant;
1478 /// # use str0m::Rtc;
1479 /// # use str0m::media::{MediaData, Mid};
1480 /// # use str0m::format::PayloadParams;
1481 /// let mut rtc = Rtc::new(Instant::now());
1482 ///
1483 /// // add candidates, do SDP negotiation
1484 /// let mid: Mid = todo!(); // obtain mid from Event::MediaAdded.
1485 ///
1486 /// // Writer for this mid.
1487 /// let writer = rtc.writer(mid).unwrap();
1488 ///
1489 /// // Get incoming media data from another peer
1490 /// let data: MediaData = todo!();
1491 ///
1492 /// // Match incoming PT to an outgoing PT.
1493 /// let pt = writer.match_params(data.params).unwrap();
1494 ///
1495 /// writer.write(pt, data.network_time, data.time, data.data).unwrap();
1496 /// ```
1497 ///
1498 /// This is a frame level API: For RTP level see [`DirectApi::stream_tx()`]
1499 /// and [`DirectApi::stream_rx()`].
1500 ///
1501 pub fn writer(&mut self, mid: Mid) -> Option<Writer> {
1502 if self.session.rtp_mode {
1503 panic!("In rtp_mode use direct_api().stream_tx().write_rtp()");
1504 }
1505
1506 if self.state != RtcState::Alive {
1507 return None;
1508 }
1509
1510 // Disjoint borrows let the writer arm readiness within each mutation.
1511 let Rtc {
1512 session, readiness, ..
1513 } = self;
1514
1515 // This does not catch potential RIDs required to send simulcast, but
1516 // it's a good start. An error might arise later on RID mismatch.
1517 session.media_by_mid(mid)?;
1518
1519 Some(Writer::new(session, readiness, mid))
1520 }
1521
1522 /// Currently configured media.
1523 ///
1524 /// Read only access. Changes are made via [`Rtc::sdp_api()`] or [`Rtc::direct_api()`].
1525 pub fn media(&self, mid: Mid) -> Option<&Media> {
1526 self.session.media_by_mid(mid)
1527 }
1528
1529 fn init_dtls(&mut self, active: bool) -> Result<(), RtcError> {
1530 if self.dtls.is_inited() {
1531 return Ok(());
1532 }
1533
1534 debug!("DTLS setup is: {:?}", active);
1535 self.dtls.set_active(active);
1536
1537 // Initialize the DTLS state (client or server) before any operations
1538 // This ensures internal state like random (client) or last_now (server) is initialized
1539 self.dtls.handle_timeout(self.last_now)?;
1540
1541 if active {
1542 // Drive handshake by sending an empty packet to trigger ClientHello
1543 let _ = self.dtls.handle_receive(&[]);
1544 }
1545
1546 Ok(())
1547 }
1548
1549 fn try_init_sctp(
1550 &mut self,
1551 client: bool,
1552 sctp_init_data: Option<SctpInitData>,
1553 remote_max_message_size: Option<u32>,
1554 ) -> Result<(), RtcError> {
1555 // If we got an m=application line, ensure we have negotiated the
1556 // SCTP association with the other side.
1557 if self.sctp.is_inited() {
1558 return Ok(());
1559 }
1560
1561 self.sctp.init(
1562 client,
1563 self.last_now,
1564 sctp_init_data,
1565 remote_max_message_size,
1566 )?;
1567 Ok(())
1568 }
1569
1570 /// Creates a new Mid that is not in the session already.
1571 pub(crate) fn new_mid(&self) -> Mid {
1572 loop {
1573 let mid = Mid::new();
1574 if !self.session.has_mid(mid) {
1575 break mid;
1576 }
1577 }
1578 }
1579
1580 /// Poll the `Rtc` instance for output. Output can be three things, something to _Transmit_
1581 /// via a UDP socket (maybe via a TURN server). An _Event_, such as receiving media data,
1582 /// or a _Timeout_.
1583 ///
1584 /// The user of the library is expected to continuously call this function and deal with
1585 /// the output until it encounters an [`Output::Timeout`] at which point no further output
1586 /// is produced (if polled again, it will result in just another timeout).
1587 ///
1588 /// After exhausting the `poll_output`, the function will only produce more output again
1589 /// when one of two things happen:
1590 ///
1591 /// 1. The polled timeout is reached.
1592 /// 2. New network input.
1593 ///
1594 /// See [`Rtc`] instance documentation for how this is expected to be used in a loop.
1595 pub fn poll_output(&mut self) -> Result<Output, RtcError> {
1596 // SCTP packets fed into DTLS require another pass. Loop here so a large
1597 // batch does not grow the stack with one recursive call per packet.
1598 let o = loop {
1599 if let Some(o) = self.do_poll_output()? {
1600 break o;
1601 }
1602 };
1603
1604 match &o {
1605 Output::Event(e) => match e {
1606 Event::ChannelData(_)
1607 | Event::MediaData(_)
1608 | Event::RtpPacket(_)
1609 | Event::SenderFeedback(_)
1610 | Event::MediaEgressStats(_)
1611 | Event::MediaIngressStats(_)
1612 | Event::PeerStats(_)
1613 | Event::ChannelBufferedAmountLow(_)
1614 | Event::EgressBitrateEstimate(_)
1615 | Event::KeyframeRequest(_) => {
1616 trace!("{:?}", e)
1617 }
1618 _ => debug!("{:?}", e),
1619 },
1620 Output::Transmit(t) => {
1621 self.peer_bytes_tx += t.contents.len() as u64;
1622 trace!("OUT {:?}", t)
1623 }
1624 Output::Timeout(_t) => {}
1625 }
1626
1627 Ok(o)
1628 }
1629
1630 /// Conservatively re-poll the whole tree.
1631 fn wake_all(&mut self) {
1632 drop(self.readiness.wake());
1633 }
1634
1635 // Returns None when polling must restart after handling an SCTP packet.
1636 fn do_poll_output(&mut self) -> Result<Option<Output>, RtcError> {
1637 if self.state == RtcState::Closed {
1638 self.last_timeout_reason = Reason::NotHappening;
1639 return Ok(Some(Output::Timeout(not_happening())));
1640 }
1641
1642 if !self.readiness.wants_events() {
1643 return Ok(Some(Output::Timeout(self.poll_timeout())));
1644 }
1645
1646 while let Some(e) = self.ice.poll_event() {
1647 match e {
1648 IceAgentEvent::IceRestart(_) => {
1649 //
1650 }
1651 IceAgentEvent::IceConnectionStateChange(v) => {
1652 return Ok(Some(Output::Event(Event::IceConnectionStateChange(v))));
1653 }
1654 IceAgentEvent::DiscoveredRecv { proto, source } => {
1655 debug!("ICE remote address: {:?}/{:?}", Pii(source), proto);
1656 self.remote_addrs.push(source);
1657 while self.remote_addrs.len() > 20 {
1658 self.remote_addrs.remove(0);
1659 }
1660 }
1661 IceAgentEvent::NominatedSend {
1662 proto,
1663 source,
1664 destination,
1665 } => {
1666 debug!(
1667 "ICE nominated send from: {:?} to: {:?} with protocol {:?}",
1668 Pii(source),
1669 Pii(destination),
1670 proto,
1671 );
1672 self.send_addr = Some(SendAddr {
1673 proto,
1674 source,
1675 destination,
1676 });
1677 }
1678 }
1679 }
1680
1681 // Handle DTLS timeout before polling output so any retransmit packets
1682 // queued by dimpl and the re-armed flight timer are picked up by the
1683 // poll loop below in the same iteration.
1684 if let Some(timeout) = self.next_dtls_timeout {
1685 if timeout <= self.last_now {
1686 self.next_dtls_timeout = None;
1687
1688 if let Err(error) = self.dtls.handle_timeout(self.last_now) {
1689 // A failed timer transition leaves DTLS unrecoverable. Close the
1690 // RTC so continued polling cannot expose the same due timeout again.
1691 self.disconnect();
1692 return Err(error.into());
1693 }
1694 }
1695 }
1696
1697 // Poll DTLS output - collect packets, handle events
1698 let mut just_connected = false;
1699 loop {
1700 match self.dtls.poll_output(&mut self.dtls_buf) {
1701 DtlsOutput::Packet(_) => {
1702 unreachable!("We don't expect DTLS packets here since we use poll_packet");
1703 }
1704 DtlsOutput::Connected => {
1705 if !self.dtls_connected {
1706 debug!("DTLS connected");
1707 self.dtls_connected = true;
1708 just_connected = true;
1709 }
1710 }
1711 DtlsOutput::KeyingMaterial(km, profile) => {
1712 use config::KeyingMaterial;
1713 let km_bytes = km.as_ref().to_vec();
1714 debug!("DTLS set SRTP keying material and profile: {}", profile);
1715 let active = self.dtls.is_active().expect("DTLS must be inited by now");
1716 self.session.set_keying_material(
1717 KeyingMaterial::new(&km_bytes),
1718 &self.crypto_provider,
1719 profile,
1720 active,
1721 );
1722 }
1723 DtlsOutput::PeerCert(der) => {
1724 debug!("DTLS verify remote fingerprint");
1725 // Compute the fingerprint of the peer's DER certificate with the hash
1726 // function of the expected one (RFC 8122 §5): sha-256, or sha-1 as some
1727 // endpoints still announce. sha-256 when there is none to compare with.
1728 let provider = &self.crypto_provider;
1729 let matching = self.remote_fingerprint.as_ref().and_then(|expected| {
1730 crate::crypto::Fingerprint::of_certificate(
1731 der,
1732 &expected.hash_func,
1733 provider,
1734 )
1735 });
1736 let fingerprint = matching.clone().unwrap_or_else(|| {
1737 crate::crypto::Fingerprint::of_certificate(der, "sha-256", provider)
1738 .expect("sha-256 is supported")
1739 });
1740 self.dtls.set_remote_fingerprint(fingerprint.clone());
1741 if let Some(expected) = &self.remote_fingerprint {
1742 if !self.fingerprint_verification {
1743 debug!("DTLS fingerprint verification disabled");
1744 } else if matching.is_none() {
1745 let message = format!(
1746 "unsupported fingerprint hash function: {}",
1747 expected.hash_func
1748 );
1749 self.disconnect();
1750 return Err(RtcError::RemoteSdp(message));
1751 } else if fingerprint != *expected {
1752 self.disconnect();
1753 return Err(RtcError::RemoteSdp("remote fingerprint no match".into()));
1754 }
1755 } else {
1756 self.disconnect();
1757 return Err(RtcError::RemoteSdp("no a=fingerprint before dtls".into()));
1758 }
1759 }
1760 DtlsOutput::ApplicationData(data) => {
1761 self.sctp.handle_input(self.last_now, data);
1762 }
1763 DtlsOutput::Timeout(t) => {
1764 self.next_dtls_timeout = Some(t);
1765 break;
1766 }
1767 DtlsOutput::CloseNotify => {
1768 self.start_close()?;
1769 return Ok(Some(Output::Event(Event::Closed)));
1770 }
1771 other => {
1772 return Err(RtcError::Dtls(DtlsError::Io(std::io::Error::other(
1773 format!("Unexpected DTLS output: {other:?}"),
1774 ))));
1775 }
1776 }
1777 }
1778
1779 if just_connected {
1780 return Ok(Some(Output::Event(Event::Connected)));
1781 }
1782
1783 while let Some(e) = self.sctp.poll() {
1784 match e {
1785 SctpEvent::Transmit { mut packets } => {
1786 if let Some(v) = packets.front() {
1787 if let Err(e) = self.dtls.handle_input(v) {
1788 if is_would_block(&e) {
1789 self.sctp.push_back_transmit(packets);
1790 break;
1791 } else if self.state == RtcState::Closing {
1792 debug!(
1793 "Dropping SCTP transmit while closing after DTLS error: {e}"
1794 );
1795 packets.pop_front();
1796 if !packets.is_empty() {
1797 self.sctp.push_back_transmit(packets);
1798 }
1799 return Ok(None);
1800 } else {
1801 return Err(e.into());
1802 }
1803 }
1804
1805 packets.pop_front();
1806 // If there are still packets, they are sent on next
1807 // poll_output()
1808 if !packets.is_empty() {
1809 self.sctp.push_back_transmit(packets);
1810 }
1811
1812 // Run again since this would feed the DTLS subsystem
1813 // to produce a packet now.
1814 return Ok(None);
1815 }
1816 }
1817 SctpEvent::Open { id, label } => {
1818 self.chan.ensure_channel_id_for(id);
1819 let id = self.chan.channel_id_by_stream_id(id).unwrap();
1820 return Ok(Some(Output::Event(Event::ChannelOpen(id, label))));
1821 }
1822 SctpEvent::Close {
1823 id: stream_id,
1824 reset_pending,
1825 } => {
1826 let Some(channel_id) = self.chan.channel_id_by_stream_id(stream_id) else {
1827 warn!("Drop ChannelClose event for id: {:?}", stream_id);
1828 continue;
1829 };
1830 // When a reset is outstanding, remove_channel holds the stream id
1831 // back from reallocation until the handshake completes.
1832 self.chan.remove_channel(channel_id, reset_pending);
1833 return Ok(Some(Output::Event(Event::ChannelClose(channel_id))));
1834 }
1835 SctpEvent::StreamResetComplete { id } => {
1836 // The reset handshake completed, the stream id can be used again.
1837 self.chan.stream_reset_complete(id);
1838 continue;
1839 }
1840 SctpEvent::AssociationLost => {
1841 self.chan.association_lost();
1842 self.start_close()?;
1843 return Ok(Some(Output::Event(Event::Closed)));
1844 }
1845 SctpEvent::Data { id, binary, data } => {
1846 let Some(id) = self.chan.channel_id_by_stream_id(id) else {
1847 warn!("Drop ChannelData event for id: {:?}", id);
1848 continue;
1849 };
1850 let cd = ChannelData { id, binary, data };
1851 return Ok(Some(Output::Event(Event::ChannelData(cd))));
1852 }
1853 SctpEvent::BufferedAmountLow { id } => {
1854 let Some(id) = self.chan.channel_id_by_stream_id(id) else {
1855 warn!("Drop BufferedAmountLow for id: {:?}", id);
1856 continue;
1857 };
1858 return Ok(Some(Output::Event(Event::ChannelBufferedAmountLow(id))));
1859 }
1860 }
1861 }
1862
1863 if let Some(ev) = self.session.poll_event() {
1864 return Ok(Some(Output::Event(ev)));
1865 }
1866
1867 // Some polling needs to bubble up errors.
1868 if let Some(ev) = self.session.poll_event_fallible(self.last_now)? {
1869 return Ok(Some(Output::Event(ev)));
1870 }
1871
1872 if let Some(e) = self.stats.as_mut().and_then(|s| s.poll_output()) {
1873 return Ok(Some(match e {
1874 StatsEvent::Peer(s) => Output::Event(Event::PeerStats(s)),
1875 StatsEvent::MediaIngress(s) => Output::Event(Event::MediaIngressStats(s)),
1876 StatsEvent::MediaEgress(s) => Output::Event(Event::MediaEgressStats(s)),
1877 }));
1878 }
1879
1880 if let Some(v) = self.ice.poll_transmit() {
1881 return Ok(Some(Output::Transmit(v)));
1882 }
1883
1884 if let Some(send) = &self.send_addr {
1885 // These can only be sent after we got an ICE connection.
1886 let datagram = None
1887 .or_else(|| self.dtls.poll_packet())
1888 .or_else(|| self.session.poll_datagram(self.last_now));
1889
1890 if let Some(contents) = datagram {
1891 let t = net::Transmit {
1892 proto: send.proto,
1893 source: send.source,
1894 destination: send.destination,
1895 contents,
1896 };
1897 return Ok(Some(Output::Transmit(t)));
1898 }
1899 } else {
1900 // Don't allow accumulated feedback to build up indefinitely
1901 self.session.clear_feedback();
1902 }
1903
1904 self.readiness.clear_events();
1905
1906 Ok(Some(Output::Timeout(self.poll_timeout())))
1907 }
1908
1909 // Called only after the output pipeline has drained.
1910 fn poll_timeout(&mut self) -> Instant {
1911 if self.readiness.wants_timeout() {
1912 let stats_timeout = self.stats.as_mut().and_then(|s| s.poll_timeout());
1913 let time_and_reason = (None, Reason::NotHappening)
1914 .soonest((self.next_dtls_timeout, Reason::DTLS))
1915 .soonest((self.ice.poll_timeout(), Reason::Ice))
1916 .soonest(self.session.poll_timeout())
1917 .soonest((self.sctp.poll_timeout(), Reason::Sctp))
1918 .soonest((self.chan.poll_timeout(&self.sctp), Reason::Channel))
1919 .soonest((stats_timeout, Reason::Stats));
1920
1921 let time = time_and_reason.0.unwrap_or_else(not_happening);
1922 self.cached_timeout = time.max(self.last_now);
1923 self.last_timeout_reason = time_and_reason.1;
1924 self.readiness.clear_timeout();
1925 }
1926
1927 if self.state == RtcState::Closing && self.close_drain_complete() {
1928 self.state = RtcState::Closed;
1929 self.last_timeout_reason = Reason::NotHappening;
1930 return not_happening();
1931 }
1932
1933 self.cached_timeout
1934 }
1935
1936 /// The reason for the last [`Output::Timeout`]
1937 ///
1938 /// This is updated when calling [`Rtc::poll_output()`] and the next output
1939 /// is a timeout.
1940 ///
1941 /// ```
1942 /// # use str0m::{Rtc, Reason};
1943 /// # use std::time::Instant;
1944 /// let rtc = Rtc::new(Instant::now());
1945 ///
1946 /// // Before any call to poll_output(), the reason is the default.
1947 /// assert_eq!(rtc.last_timeout_reason(), Reason::NotHappening);
1948 /// ```
1949 pub fn last_timeout_reason(&self) -> Reason {
1950 self.last_timeout_reason
1951 }
1952
1953 /// Check if this `Rtc` instance accepts the given input. This is used for demultiplexing
1954 /// several `Rtc` instances over the same UDP server socket.
1955 ///
1956 /// [`Input::Timeout`] is always accepted. [`Input::Receive`] is tested against the nominated
1957 /// ICE candidate. If that doesn't match and the incoming data is a STUN packet, the accept call
1958 /// is delegated to the ICE agent which recognizes the remote peer from `a=ufrag`/`a=password`
1959 /// credentials negotiated in the SDP. If that also doesn't match, all remote ICE candidates are
1960 /// checked for a match.
1961 ///
1962 /// In a server setup, the server would try to find an `Rtc` instances using [`Rtc::accepts()`].
1963 /// The first found instance would be given the input via [`Rtc::handle_input()`].
1964 ///
1965 /// ```no_run
1966 /// # use std::time::Instant;
1967 /// # use str0m::{Rtc, Input};
1968 /// // A vec holding the managed rtc instances. One instance per remote peer.
1969 /// let now = Instant::now();
1970 /// let mut rtcs = vec![Rtc::new(now), Rtc::new(now), Rtc::new(now)];
1971 ///
1972 /// // Configure instances with local ice candidates etc.
1973 ///
1974 /// loop {
1975 /// // TODO poll_timeout() and handle the output.
1976 ///
1977 /// let input: Input = todo!(); // read network data from socket.
1978 /// for rtc in &mut rtcs {
1979 /// if rtc.accepts(&input) {
1980 /// rtc.handle_input(input).unwrap();
1981 /// }
1982 /// }
1983 /// }
1984 /// ```
1985 pub fn accepts(&self, input: &Input) -> bool {
1986 let Input::Receive(_, r) = input else {
1987 // always accept the Input::Timeout.
1988 return true;
1989 };
1990
1991 // Fast path: DTLS, RTP, and RTCP traffic coming in from the same socket address
1992 // we've nominated for sending via the ICE agent. This is the typical case
1993 if let Some(send_addr) = &self.send_addr {
1994 if r.source == send_addr.destination {
1995 return true;
1996 }
1997 }
1998
1999 // STUN can use the ufrag/password to identify that a message belongs
2000 // to this Rtc instance.
2001 if let DatagramRecvInner::Stun(v) = &r.contents.inner {
2002 return self.ice.accepts_message(v);
2003 }
2004
2005 // Slow path: Occasionally, traffic comes in on a socket address corresponding
2006 // to a successful candidate pair other than the one we've currently nominated.
2007 // This typically happens at the beginning of the connection
2008 if self.ice.has_viable_remote_candidate(r.source) {
2009 return true;
2010 }
2011
2012 false
2013 }
2014
2015 /// Provide input to this `Rtc` instance. Input is either a [`Input::Timeout`] for some
2016 /// time that was previously obtained from [`Rtc::poll_output()`], or [`Input::Receive`]
2017 /// for network data.
2018 ///
2019 /// Both the timeout and the network data contains a [`std::time::Instant`] which drives
2020 /// time forward in the instance. For network data, the intention is to record the time
2021 /// of receiving the network data as precise as possible. This time is used to calculate
2022 /// things like jitter and bandwidth.
2023 ///
2024 /// It's always okay to call [`Rtc::handle_input()`] with a timeout, also before the
2025 /// time obtained via [`Rtc::poll_output()`].
2026 ///
2027 /// ```no_run
2028 /// # use str0m::{Rtc, Input};
2029 /// # use std::time::Instant;
2030 /// let mut rtc = Rtc::new(Instant::now());
2031 ///
2032 /// loop {
2033 /// let timeout: Instant = todo!(); // rtc.poll_output() until we get a timeout.
2034 ///
2035 /// let input: Input = todo!(); // wait for network data or timeout.
2036 /// rtc.handle_input(input);
2037 /// }
2038 /// ```
2039 pub fn handle_input(&mut self, input: Input) -> Result<(), RtcError> {
2040 if self.state == RtcState::Closed {
2041 return Ok(());
2042 }
2043
2044 // The handlers below each arm their own `Wake`; nothing to do here.
2045 match input {
2046 Input::Timeout(now) => self.do_handle_timeout(now)?,
2047 Input::Receive(recv_time, r) => {
2048 self.do_handle_receive(recv_time, r)?;
2049 self.do_handle_timeout(recv_time)?;
2050 }
2051 }
2052 Ok(())
2053 }
2054
2055 /// Starts local shutdown.
2056 ///
2057 /// The `Rtc` instance schedules RTCP BYE, requests SCTP shutdown, and sends
2058 /// DTLS close_notify without waiting for remote replies. It enters a closing
2059 /// drain state where app-facing operations stop, but [`Rtc::poll_output()`]
2060 /// continues polling until pending local close output has drained. Once the
2061 /// drain is complete, [`Rtc::is_alive()`] returns `false`.
2062 pub fn close(&mut self) -> Result<(), RtcError> {
2063 self.start_close()
2064 }
2065
2066 fn start_close(&mut self) -> Result<(), RtcError> {
2067 if self.state == RtcState::Closed {
2068 return Ok(());
2069 }
2070
2071 // Closing queues RTCP BYE and a DTLS close_notify that must be drained
2072 // from the pipeline, so re-poll the whole tree.
2073 self.wake_all();
2074
2075 if self.state != RtcState::Closing {
2076 self.session.close_rtp();
2077 self.sctp.close()?;
2078 self.state = RtcState::Closing;
2079 }
2080
2081 self.start_dtls_close()
2082 }
2083
2084 fn start_dtls_close(&mut self) -> Result<(), RtcError> {
2085 if !self.close_dtls_started {
2086 self.dtls.close()?;
2087 self.close_dtls_started = true;
2088 }
2089
2090 Ok(())
2091 }
2092
2093 fn close_drain_complete(&self) -> bool {
2094 self.close_dtls_started && self.dtls.is_closed() && self.session.is_rtp_closed()
2095 }
2096
2097 fn init_time(&mut self, now: Instant) {
2098 // The operation is somewhat expensive, hence we only do it once.
2099 if !self.need_init_time {
2100 return;
2101 }
2102
2103 // We assume this first "now" is a time 0 start point for calculating ntp/unix time offsets.
2104 // This initializes the conversion of Instant -> NTP/Unix time.
2105 let _ = now.to_unix_duration();
2106
2107 self.need_init_time = false;
2108 }
2109
2110 fn do_handle_timeout(&mut self, now: Instant) -> Result<(), RtcError> {
2111 self.init_time(now);
2112
2113 // Prevent time from going backwards.
2114 if now < self.last_now {
2115 return Ok(());
2116 }
2117
2118 self.last_now = now;
2119
2120 // Disjoint borrows so each subsystem gets its own armed `Wake` and
2121 // makes its own re-poll decision; the guards fold into `readiness`
2122 // independently as each statement ends.
2123 let Rtc {
2124 ice,
2125 sctp,
2126 chan,
2127 session,
2128 stats,
2129 send_addr,
2130 peer_bytes_rx,
2131 peer_bytes_tx,
2132 readiness,
2133 ..
2134 } = self;
2135
2136 // ICE is an external crate and can't be handed a `Wake`. Driving it can
2137 // transmit and re-arm timers, so arm both on its behalf at the boundary.
2138 ice.handle_timeout(now);
2139 drop(readiness.wake());
2140
2141 sctp.handle_timeout(now, &mut readiness.wake());
2142 chan.handle_timeout(now, sctp, &mut readiness.wake());
2143 session.handle_timeout(now, &mut readiness.wake())?;
2144
2145 if let Some(stats) = stats {
2146 if stats.wants_timeout(now) {
2147 let mut snapshot = StatsSnapshot::new(now);
2148 snapshot.peer_rx = *peer_bytes_rx;
2149 snapshot.peer_tx = *peer_bytes_tx;
2150 let current_round_trip_time = ice.nominated_pair_rtt();
2151 let total_round_trip_time = ice.nominated_pair_total_rtt().unwrap_or_default();
2152 let responses_received = ice.nominated_pair_responses_received().unwrap_or(0);
2153 snapshot.selected_candidate_pair = send_addr.as_ref().map(|s| CandidatePairStats {
2154 protocol: s.proto,
2155 local: CandidateStats { addr: s.source },
2156 remote: CandidateStats {
2157 addr: s.destination,
2158 },
2159 current_round_trip_time,
2160 total_round_trip_time,
2161 responses_received,
2162 });
2163 session.visit_stats(now, &mut snapshot);
2164
2165 // A stats snapshot surfaces as an event and re-arms the stats
2166 // timer.
2167 drop(readiness.wake());
2168 stats.do_handle_timeout(&mut snapshot);
2169 }
2170 }
2171
2172 Ok(())
2173 }
2174
2175 fn do_handle_receive(&mut self, recv_time: Instant, r: net::Receive) -> Result<(), RtcError> {
2176 trace!("IN {:?}", r);
2177 use DatagramRecvInner::*;
2178
2179 let bytes_rx = match r.contents.inner {
2180 // TODO: stun is already parsed (depacketized) here
2181 Stun(_) => 0,
2182 Dtls(v) | Rtp(v) | Rtcp(v) => v.len(),
2183 };
2184
2185 self.peer_bytes_rx += bytes_rx as u64;
2186
2187 // Disjoint borrows so each subsystem gets its own armed `Wake`.
2188 let Rtc {
2189 ice,
2190 dtls,
2191 session,
2192 readiness,
2193 ..
2194 } = self;
2195
2196 match r.contents.inner {
2197 Stun(stun) => {
2198 let packet = is::stun::StunPacket {
2199 proto: r.proto,
2200 source: r.source,
2201 destination: r.destination,
2202 message: stun,
2203 };
2204 // ICE is an external crate; arm both on its behalf.
2205 ice.handle_packet(recv_time, packet);
2206 drop(readiness.wake());
2207 }
2208 Dtls(dtls_packet) => {
2209 // A failed receive can still change DTLS state and timers.
2210 let _wake = readiness.wake();
2211 dtls.handle_receive(dtls_packet)?;
2212 }
2213 Rtp(rtp) => session.handle_rtp_receive(recv_time, rtp, &mut readiness.wake()),
2214 Rtcp(rtcp) => session.handle_rtcp_receive(recv_time, rtcp, &mut readiness.wake()),
2215 }
2216
2217 Ok(())
2218 }
2219
2220 /// Obtain handle for writing to a data channel.
2221 ///
2222 /// This is first available when a [`ChannelId`] is advertised via [`Event::ChannelOpen`].
2223 /// The function returns `None` also for IDs from [`SdpApi::add_channel()`].
2224 ///
2225 /// Incoming channel data is via the [`Event::ChannelData`] event.
2226 ///
2227 /// ```no_run
2228 /// # use std::time::Instant;
2229 /// # use str0m::{Rtc, channel::ChannelId};
2230 /// let mut rtc = Rtc::new(Instant::now());
2231 ///
2232 /// let cid: ChannelId = todo!(); // obtain channel id from Event::ChannelOpen
2233 /// let channel = rtc.channel(cid).unwrap();
2234 /// // TODO write data channel data.
2235 /// ```
2236 pub fn channel(&mut self, id: ChannelId) -> Option<Channel<'_>> {
2237 if self.state != RtcState::Alive {
2238 return None;
2239 }
2240
2241 let sctp_stream_id = self.chan.stream_id_by_channel_id(id)?;
2242
2243 if !self.sctp.is_open(sctp_stream_id) {
2244 return None;
2245 }
2246
2247 Some(Channel::new(sctp_stream_id, self))
2248 }
2249
2250 /// Configure the Bandwidth Estimate (BWE) subsystem.
2251 ///
2252 /// Only relevant if BWE was enabled in the [`RtcConfig::enable_bwe()`]
2253 pub fn bwe(&mut self) -> Bwe {
2254 Bwe::new(self)
2255 }
2256
2257 fn is_correct_change_id(&self, change_id: usize) -> bool {
2258 self.change_counter == change_id + 1
2259 }
2260
2261 fn next_change_id(&mut self) -> usize {
2262 let n = self.change_counter;
2263 self.change_counter += 1;
2264 n
2265 }
2266
2267 /// The codec configs for sending/receiving data.
2268 ///
2269 /// The configurations can be set with [`RtcConfig`] before setting up the session, and they
2270 /// might be further updated by SDP negotiation.
2271 pub fn codec_config(&self) -> &CodecConfig {
2272 &self.session.codec_config
2273 }
2274}
2275
2276impl PartialEq for Event {
2277 fn eq(&self, other: &Self) -> bool {
2278 match (self, other) {
2279 (Self::IceConnectionStateChange(l0), Self::IceConnectionStateChange(r0)) => l0 == r0,
2280 (Self::MediaAdded(m0), Self::MediaAdded(m1)) => m0 == m1,
2281 (Self::MediaData(m1), Self::MediaData(m2)) => m1 == m2,
2282 (Self::ChannelOpen(l0, l1), Self::ChannelOpen(r0, r1)) => l0 == r0 && l1 == r1,
2283 (Self::ChannelData(l0), Self::ChannelData(r0)) => l0 == r0,
2284 (Self::ChannelClose(l0), Self::ChannelClose(r0)) => l0 == r0,
2285 _ => false,
2286 }
2287 }
2288}
2289
2290impl Eq for Event {}
2291
2292impl fmt::Debug for Rtc {
2293 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2294 f.debug_struct("Rtc").finish()
2295 }
2296}
2297
2298/// Log a CSV like stat to stdout.
2299///
2300/// ```ignore
2301/// log_stat!("MY_STAT", 1, "hello", 3);
2302/// ```
2303///
2304/// will result in the following being printed
2305///
2306/// ```text
2307/// MY_STAT 1, hello, 3, {unix_timestamp_ms}
2308/// ````
2309///
2310/// These logs can be easily grepped for, parsed and graphed, or otherwise analyzed.
2311///
2312/// This macro turns into a NO-OP if the `_internal_dont_use_log_stats` feature is not enabled
2313macro_rules! log_stat {
2314 ($name:expr, $($arg:expr),+) => {
2315 #[cfg(feature = "_internal_dont_use_log_stats")]
2316 {
2317 use std::time::SystemTime;
2318 use std::io::{self, Write};
2319
2320 let now = SystemTime::now();
2321 let since_epoch = now.duration_since(SystemTime::UNIX_EPOCH).unwrap();
2322 let unix_time_ms = since_epoch.as_millis();
2323 let mut lock = io::stdout().lock();
2324 write!(lock, "{} ", $name).expect("Failed to write to stdout");
2325
2326 $(
2327 write!(lock, "{},", $arg).expect("Failed to write to stdout");
2328 )+
2329 writeln!(lock, "{}", unix_time_ms).expect("Failed to write to stdout");
2330 }
2331 };
2332}
2333pub(crate) use log_stat;
2334
2335#[cfg(test)]
2336#[doc(hidden)]
2337pub fn init_crypto_default() {
2338 crate::crypto::from_feature_flags().install_process_default();
2339}
2340
2341#[cfg(test)]
2342mod test {
2343 use std::panic::UnwindSafe;
2344
2345 use super::*;
2346
2347 #[test]
2348 fn rtc_is_send() {
2349 fn is_send<T: Send>(_t: T) {}
2350 fn is_sync<T: Sync>(_t: T) {}
2351 is_send(Rtc::new(Instant::now()));
2352 is_sync(Rtc::new(Instant::now()));
2353 }
2354
2355 #[test]
2356 fn rtc_is_unwind_safe() {
2357 fn is_unwind_safe<T: UnwindSafe>(_t: T) {}
2358 is_unwind_safe(Rtc::new(Instant::now()));
2359 }
2360
2361 #[test]
2362 fn event_is_reasonably_sized() {
2363 let n = std::mem::size_of::<Event>();
2364 assert!(n < 530);
2365 }
2366}
2367
2368#[cfg(feature = "_internal_test_exports")]
2369#[allow(missing_docs)]
2370pub mod _internal_test_exports;
2371
2372#[cfg(feature = "unversioned")]
2373pub mod unversioned {
2374 //! This module provides functionality that is not versioned according to semver.
2375 //! It may change in breaking ways between minor/patch releases, there are no guarantees.
2376 //! USE AT YOUR OWN RISK.
2377 //!
2378 //! To use this module, enable the `unversioned` feature flag in your Cargo.toml.
2379
2380 pub use super::packet::{
2381 Depacketizer, H264Depacketizer, H264Packetizer, OpusPacketizer, Packetizer, TelephoneEvent,
2382 Vp8Depacketizer, Vp8Packetizer,
2383 };
2384}