Rust 中的 Sans I/O WebRTC 实现。
A Sans I/O WebRTC implementation in Rust.
This is a [Sans I/O][sansio] implementation meaning the Rtc instance itself is not doing any network
talking. Furthermore it has no internal threads or async tasks. All operations are happening from the
calls of the public API.
This is deliberately not a standard RTCPeerConnection API since that isn't a great fit for Rust.
See more details in below section.
We are discussing str0m things on Discord. Join us using this [invitation link][discord].
The [chat][x-chat] example shows how to connect multiple browsers
together and act as an SFU (Selective Forwarding Unit). The example
multiplexes all traffic over one server UDP socket and uses two threads
(one for the web server, and one for the SFU loop).
For the browser to do WebRTC, all traffic must be under TLS. The
project ships with a self-signed certificate that is used for the
examples. The certificate is for hostname str0m.test since TLD .test
should never resolve to a real DNS name.
cargo run --example chatThe log should prompt you to connect a browser to https://10.0.0.103:3000 – this will most likely cause a security warning that you must get the browser to accept.
The [http-post][x-post] example roughly illustrates how to receive
media data from a browser client. The example is single threaded and
is a bit simpler than the chat. It is a good starting point to understand the API.
cargo run --example http-postTo see how str0m is used in a real project, check out [BitWHIP][bitwhip] – a CLI WebRTC Agent written in Rust.
For passive connections, i.e. where the media and initial OFFER is made by a remote peer, we need these steps to open the connection.
// Instantiate a new Rtc instance.
let mut rtc = Rtc::new(Instant::now());
// Add some ICE candidate such as a locally bound UDP port.
let addr = "1.2.3.4:5000".parse().unwrap();
let candidate = Candidate::host(addr, "udp").unwrap();
rtc.add_local_candidate(candidate);
// Accept an incoming offer from the remote peer
// and get the corresponding answer.
let offer = todo!();
let answer = rtc.sdp_api().accept_offer(offer).unwrap();
// Forward the answer to the remote peer.
// Go to _run loop_Active connections means we are making the inital OFFER and waiting for a remote ANSWER to start the connection.
…str0m's API has one strict contract that the run loop is built around:
Every mutation of an
Rtcinstance must be followed by a complete drain ofpoll_outputuntil it returnsOutput::Timeout, before the next mutation on the sameRtc.
A "mutation" is anything that takes &mut Rtc (directly or through a
handle obtained from it). The common ones are:
Rtc::handle_input — feeding a network packet or a timeoutWriter::write / Writer::request_keyframe — sending mediaChannel::write — sending data channel dataSdpApi::apply / DirectApi::* — negotiationRtc::add_local_candidate / Rtc::add_remote_candidateAlways: mutate → drain to Timeout → mutate → drain to Timeout → …
Doing two mutations back-to-back without draining in between, or
waiting on I/O while the engine still has output queued, leaves the
engine in an inconsistent state and produces wrong behavior. Mutations
issued from inside the drain loop (e.g. calling Writer::write in
response to an Output::Event) are fine — the drain loop naturally
continues calling poll_output afterward and so the invariant holds.
Driving an Rtc forward follows the same six-step shape, regardless
of sync or async:
Input to handle_input, or
call into a writer / channel / SDP API.Rtc::poll_output.Output::Transmit is sent on the socket,
Output::Event is dispatched to the application, Output::Timeout
records the next deadline.poll_output returns Output::Timeout. Only then
is the engine fully drained.…When creating the media, we can decide which codecs to support, and they are negotiated with the remote side. Each codec corresponds to a "payload type" (PT). To send media data we need to figure out which PT to use when sending.
// Obtain mid from Event::MediaAdded
let mid: Mid = todo!();
// Create a media writer for the mid.
let writer = rtc.writer(mid).unwrap();
// Get the payload type (pt) for the wanted codec.
let pt = writer.payload_params().nth(0).unwrap().pt();
// Write the data
let wallclock = todo!(); // Absolute time of the data
let media_time = todo!(); // Media time, in RTP time
let data: &[u8] = todo!(); // Actual data
writer.write(pt, wallclock, media_time, data).unwrap();Writer::write is a mutation, so the
single-mutation invariant applies:
after writing, drain Rtc::poll_output to Output::Timeout before
the next mutation on this Rtc.
str0m has three main concepts of time. "now", media time and wallclock.
Some calls in str0m, such as Rtc::handle_input takes a now argument
that is a std::time::Instant. These calls "drive the time forward" in
the internal state. This is used for everything like deciding when
to produce various feedback reports (RTCP) to remote peers, to
bandwidth estimation (BWE) and statistics.
Str0m has no internal clock calls. I.e. str0m never calls
Instant::now() itself. All time is external input. That means it's
possible to construct test cases driving an Rtc instance faster
than realtime (see the [integration tests][intg]).
Each RTP header has a 32 bit number that str0m calls media time. Media time is in some time base that is dependent on the codec, however all codecs in str0m use 90_000Hz for video and 48_000Hz for audio.
For video the MediaTime type is /90_000 str0m extends
the 32 bit number in the RTP header to 64 bit taking into account
"rollover". 64 bit is such a large number the user doesn't need to
think about rollovers.
With wallclock str0m means the time a sample of media was produced at an originating source. I.e. if we are talking into a microphone the wallclock is the NTP time the sound is sampled.
We can't know the exact wallclock for media from a remote peer since not every device is synchronized with NTP. Every sender does periodically produce a Sender Report (SR) that contains the peer's idea of its wallclock, however this number can be very wrong compared to "real" NTP time.
Furthermore, not all remote devices will have a linear idea of time passing that exactly matches the local time. A minute on the remote peer might not be exactly one minute locally.
These timestamps become important when handling simultaneous audio from multiple peers.
When writing media we need to provide str0m with an estimated wallclock.
The simplest strategy is to only trust local time and use arrival time
of the incoming UDP packet. Another simple strategy is to lock some
time T at the first UDP packet, and then offset each wallclock using
MediaTime, i.e. for video we could have T + /90_000
A production worthy SFU probably needs an even more sophisticated strategy weighing in all possible time sources to get a good estimate of the remote wallclock for a packet.
str0m supports multiple crypto backends via feature flags. The default is aws-lc-rs.
| Feature | Crate | DTLS | Platforms |
|---|---|---|---|
aws-lc-rs |
str0m-aws-lc-rs |
dimpl + AWS-LC-RS | All |
rust-crypto |
str0m-rust-crypto |
dimpl + RustCrypto | All |
openssl |
str0m-openssl |
OpenSSL (DTLS 1.2 only) | All |
openssl-dimpl |
str0m-openssl |
dimpl + OpenSSL crypto | All |
apple-crypto |
str0m-apple-crypto |
dimpl + Apple CryptoKit | macOS/iOS |
wincrypto |
str0m-wincrypto |
dimpl + Windows CNG | Windows |
wincrypto-dimpl |
str0m-wincrypto |
Alias for wincrypto |
Windows |
If multiple backend features are enabled, str0m automatically selects the backend in this
priority order: aws-lc-rs, rust-crypto, openssl-dimpl, openssl, apple-crypto
(Apple platforms only), wincrypto (Windows only).
If you disable the default features, you MUST explicitly configure an alternative crypto backend either process-wide or per-instance.
For applications, the easiest is to set a process-wide default at startup. Note that you can use any backend crate directly without enabling its feature flag:
// Set process default (will panic if called twice)
// No need to enable the "rust-crypto" feature flag
str0m_rust_crypto::default_provider().install_process_default();use std::sync::Arc;
use std::time::Instant;
use str0m::Rtc;
let rtc = Rtc::builder()
.set_crypto_provider(Arc::new(str0m_rust_crypto::default_provider()))
.build(Instant::now());Str0m was originally developed by Martin Algesten of [Lookback][lookback]. We use str0m for a specific use case: str0m as a server SFU (as opposed to peer-2-peer). That means we are heavily testing and developing the parts needed for our use case. Str0m is intended to be an all-purpose WebRTC library, which means it also works for peer-2-peer, though that aspect has received less testing.
Performance is very good, there have been some work the discover and optimize bottlenecks. Such efforts are of course never ending with diminishing returns. While there are no glaringly obvious performance bottlenecks, more work is always welcome – both algorithmically and allocation/cloning in hot paths etc.
Output from the Rtc instance can be grouped into three kinds.
Input to the Rtc instance is:
The correct use can be seen in the above Run loop or in the examples.
Sans I/O is a pattern where we turn both network input/output as well as time passing into external input to the API. This means str0m has no internal threads, just an enormous state machine that is driven forward by different kinds of input.
Str0m defaults to the "frame level" which treats the RTP as an internal detail. The user will thus mainly interact with:
Event::MediaData][evmed] to receive full frames (audio frames or video frames).Writer::write][writer] to write full frames.Writer::request_keyframe][reqkey] to request keyframes.All codecs such as h264, vp8, vp9 and opus outputs what we call "Frames". A frame has a very specific meaning for video, but this project uses it in a broader sense, where a frame is either a video or audio time stamped chunk of encoded data that typically represents a chunk of audio, or one single frame for video.
Frames are not suitable to use directly in UDP (RTP) packets - for one they are too big. Frames are therefore further chunked up by codec specific p
暂无开放 Issues,或尚未同步最近议题。