rtci-host
The host I/O around the sans-I/O rtci WebRTC engine: sockets, timers, STUN/TURN clients, ICE-TCP, mDNS and media, behind a permission gate and a socket factory. 2 public modules, 75 items at 0.2.0.
cargo add [email protected] · crates.io · docs.rs · README on GitHub
README
The host I/O around rtci, the sans-I/O WebRTC engine: everything a WebRTC implementation needs besides the protocol state machines and its language bindings.
rtci runs ICE, DTLS, SCTP, the data channels, SRTP and RTP as state machines that never open a socket, arm a timer or read the clock. rtci-host gives each Peer (one RTCPeerConnection):
- its UDP sockets (one per address family, or a shared port through a
Network), timers and driver task; - STUN/TURN clients over UDP, TCP and TLS (RFC 6544 framing);
- ICE-TCP in both roles, and mDNS (
.localcandidates); - media: transceivers, packetizing, frame assembly, encoded frames, DTMF, stats, and fake capture devices for tests;
- a queue of W3C events (
JsEvent) for the front end.
It was extracted from the Denext-Deno fork's ext/webrtc. Two front ends use it: that fork's built-in extension, and rtci-ffi, a dynamic library for runtimes that load WebRTC through FFI.
The gate and the socket factory
Two traits stand between the engine and the network:
NetGate: every address the engine sends to, every IP it binds on and the machine's interface list are asked of it first. There is no allowing default:DenyAllGaterefuses everything, and everyPeer,NetworkandIceTransporttakes a gate.NetIo: the only place sockets are created and names resolved.PlainNetIouses the operating system's.
```rust,ignore use std::rc::Rc; use rtci_host::{NetGate, Peer, PeerOptions, PlainNetIo, Reach, Verdict};
struct AllowAll; impl NetGate for AllowAll { fn decide(&self, _: &Reach) -> Option<Verdict> { Some(Verdict::Allow) } fn interfaces(&self) -> Option<Verdict> { Some(Verdict::Allow) } }
let peer = Peer::new(PeerOptions::default(), Rc::new(AllowAll), Rc::new(PlainNetIo))?; let offer = peer.create_offer(false)?; while let Some(events) = peer.next_events().await { // hand events to the application }
## Writing a gate
The engine asks `decide(&reach)` first (and `interfaces()` for the interface
list). A `Reach` says why (`kind`: `IceServer`, `IceServerResolved`,
`RemoteCandidate`, `SendTo`, `TcpDial`, `Bind`, `Mdns`), the direction
(`Connect` or `Listen`), the transport, the host (a name before DNS, else an
IP), the port (none for a bind: any port) and, for `IceServerResolved`, the
name it was resolved from.
- **A synchronous gate** (a runtime's permission set) always returns
`Some(verdict)` from `decide` / `interfaces`. It is asked every time the
engine needs the answer, and nothing waits: `set_remote_description` and
`add_ice_candidate` finish before they return.
- **An asynchronous gate** returns `None` when it doesn't know yet. The
engine then calls `ask(reach)` (or `ask_interfaces()`) once per question
per connection and waits for the future, holding back whatever needed the
answer:
- no socket is bound, no name resolved and no datagram sent before an
`Allow`. Every `NetIo` call that creates a socket or resolves a name takes
a `GateToken`, which only the engine mints from an allow for that
`Reach`, so a `NetIo` can check `token.reach()` against its arguments;
- a datagram to an address still being asked is dropped (counted as
discarded on send). ICE and DTLS retransmit, and the answer wakes the
driver;
- binds (gathering, `IceTransport::gather`, `Network::create`), ICE servers
(asked before DNS, then for the resolved address) and remote candidates
wait.
The connection remembers each asked answer for its life, keyed by the
`Reach` without its `kind`, and dedupes the questions in flight. An answer
that doesn't come within `ask_timeout()` (10 s by default), a gate that
panics, and a future that ends without an answer all count as refusals.
Deny is the default throughout.
### `AskGate`: questions as events, answers by ticket
`AskGate` is a ready-made asynchronous gate. Until `attach()` it refuses
everything (`"no permission gate registered"`). Once attached, each question
queues a `GateRequest` and runs the `set_notify` callback. The front end
takes the requests with `take_requests()` and answers each one with
`answer(ticket, verdict)`. Answers are remembered and reused by any connection
on the same gate. `detach()`, or dropping the gate, refuses whatever is
pending. A request the engine stopped waiting for (it timed out, or its
connection closed) leaves the queue, and a late `answer` returns `false`.
A request serializes as the `gaterequest` event:
```json
{"type":"gaterequest","ticket":7,"kind":"remoteCandidate","dir":"connect",
"proto":"udp","host":"192.0.2.1","port":5000,"resolvedFrom":null}
kind is "interfaces" for the interface list; its dir, proto, host, port and resolvedFrom are then null. An IPv6 host has no brackets.
```rust,ignore let gate = rtci_host::AskGate::new(); gate.set_notify(|| wake_my_event_loop()); gate.attach(); let peer = Peer::new(PeerOptions::default(), Rc::new(gate.clone()), Rc::new(PlainNetIo))?; // later, on the engine's thread: for request in gate.take_requests() { let verdict = if allowed(&request) { Verdict::Allow } else { Verdict::Deny("denied".into()) }; gate.answer(request.ticket, verdict); }
### Two-phase operations: `opdone`
`Peer::set_remote_description` and `Peer::add_ice_candidate` return an
operation id. Their `Err` is only an argument error: a closed connection, an
oversized description, an invalid type or a malformed candidate. The outcome
is the `opdone` event with that id, queued in order after the gate has
answered:
```json
{"type":"opdone","op":3}
{"type":"opdone","op":4,"error":{"kind":"NotCapable","message":"..."}}
error.kind is an ErrorKind::name(): NotCapable for a refused candidate, the engine's error otherwise, and InvalidStateError for an operation still waiting when the connection closed. With a synchronous gate the opdone is queued before the call returns, so a front end has one code path for both kinds of gate. Operations finish in the order they were made.
Network::new asks synchronously only (None is a refusal). With an asynchronous gate, use Network::create(..).await.
End of candidates
A connection ends its own gathering: once every bind and ICE server has answered, the engine is told, icegatheringstatechange goes complete, and the front end fires its icecandidate event with a null candidate. The peer's end is the front end's to pass on: add_ice_candidate with an empty candidate (what addIceCandidate(), addIceCandidate(null) and {candidate: ""} mean), or a=end-of-candidates in a remote description. A remote description without a=ice-options:trickle counts as one too. With both ends signalled, ICE reports failed once the check list is exhausted (W3C webrtc-pc 5.6.4, rtci 0.3).
A departure from rtci's default: the host also reaches failed when the peer's end-of-candidates never arrives, once the engine's RFC 8863 peer-reflexive wait (PAC timer, 39.5 s by default) runs out (with_ice_failed_without_end_of_candidates(true)). That is what Chrome, Safari and Firefox do, and what applications written against them expect: the common if (e.candidate) pc.addIceCandidate(e.candidate) never relays the null candidate, and on rtci's default such a connection would stay disconnected for ever.
Datagrams too big for the path
A send the socket refuses for its size (EMSGSIZE, Windows's WSAEMSGSIZE) is reported to the engine (RTCPeerConnection::handle_datagram_too_big, rtci 0.4; RFC 6347 4.1.1.1, RFC 9147 section 4.4), on a direct path and on a TURN relay's (traced to the relayed path by the datagram the TURN message carried). A refused send names no MTU, so the engine assumes the family's minimum (576 or 1280). A DTLS datagram is quoted, which validates the report and lowers SCTP's packet size too; an SRTP datagram goes unquoted and reaches the DTLS handshake alone. The engine's OnPathMtuExceeded then cuts the RTP this crate packetizes (write_frame) for the path; it is not a W3C event and reaches no front end. The sockets read no ICMP errors (Packet Too Big, Fragmentation Needed), so a smaller MTU only a router on the path knows is not learned.
write_frame cuts each frame so that its RTP packets, with the header extensions the engine adds (RTCRtpSender::max_packet_expansion, RFC 7941 section 4.2.2), stay within 1200 octets.
Threading
The engine is single-threaded (Rc / RefCell) and spawns !Send tasks on the current thread. Run it on a current-thread tokio runtime (as Deno does), or inside a tokio::task::LocalSet.
Errors
Calls fail with rtci_host::Error { kind, message }; ErrorKind names the W3C exception (TypeError, InvalidStateError, ..., NotCapable for a gate refusal). Each front end maps it to its own error classes.
Status
Pre-1.0 and not externally audited. Tested with rtci 0.4.
Bundled media
src/fake_media/*.bin (about 234 KB in all) are the clips the fake capture devices send. generate.sh made every one of them from FFmpeg's own synthetic sources, with no third-party footage or audio: video is one second of the testsrc2 test card (640x480, 30 fps), audio one second of a 400 Hz sine tone (600 Hz on the stereo clip's right channel). Encoders: libvpx (VP8, VP9), libaom (AV1), libx264 (H.264 baseline), libx265 (H.265), libopus (Opus) and FFmpeg's own G.711 mu-law / A-law and G.722 encoders; pack.py re-frames the output. They are covered by this crate's licence like the rest of the source. An encoder's licence does not extend to the bitstreams it produces, and no patent licence is granted for decoding or encoding H.264 or H.265: the crate only replays these short bitstreams to a peer in tests and fake capture; it contains no codec implementation.
License
MIT OR Apache-2.0.
rtci_host
The host around the sans-I/O rtci WebRTC engine: everything a WebRTC implementation needs besides the protocol state machines and the JavaScript bindings.
- mod
media_typesThe media types the front ends pass and receive (transceivers, tracks, codecs, capabilities, frames). - struct
AskGatefromask_gate::AskGateAn asynchronous gate answered by ticket. Deny by default: untilAskGate::attachevery question is refused at once (NO_GATE_REGISTERED). Once attached, each question the engine asks queues aGateRequest(AskGate::take_requests) and runs the notifier (AskGate::set_notify);AskGate::answerdelivers the verdict. An answer is remembered and reused for the same question from any … - struct
CandidateArgRTCIceCandidateInit. - struct
CertificateInfoAnRTCCertificatefor the front end's JavaScript. - struct
CertificateStorefromcertificate::CertificateStoreTheRTCCertificates of a realm, by id: each holds a key and an X.509 certificate for the DTLS handshakes of the connections given it. The front end removes an entry when itsRTCCertificateis garbage collected; a connection keeps its own copy. - struct
ConfigArgRTCConfiguration, as the front end's JavaScript passes it. - struct
CreatedChannelA created data channel: its engine handle and its stream id, when assigned. - struct
DataChannelArgcreateDataChannel(label, init). - struct
DenyAllGatefromgate::DenyAllGateRefuses everything. - struct
Errorfromerror::ErrorA failure of anrtci-hostcall: its kind and message. - struct
FingerprintInfoOneRTCDtlsFingerprint. - struct
GateRequestfromask_gate::GateRequestOne question for the front end: thegaterequestevent. - struct
GateTokenfromgate::GateTokenProof that the gate allowed aReach: everyNetIocall that creates a socket or resolves a name takes one. Only the engine mints them (there is no public constructor), from an allow for theReachthe call is for, so aNetIoimplementation may checkGateToken::reachagainst its arguments. - struct
IceServerArgOneRTCIceServer. - struct
IceServerSpecfrompeer::IceServerSpecA STUN or TURN server URL fromRTCConfiguration.iceServers, parsed and permission-checked by the constructor. - struct
IceTimeoutsArgfromnet::IceTimeoutsArg - struct
IceTransportfromice_transport::IceTransport - struct
KeygenArggenerateCertificate's algorithm (WebCrypto's dictionaries). - struct
Networkfromnet::Network - struct
NetworkArgfromnet::NetworkArg - struct
NetworkOptionsfromnet::NetworkOptions - struct
PairCandidatefrompeer::PairCandidateOne candidate ofSelectedPair, with the fields JavaScript needs to build theRTCIceCandidate(a peer-reflexive remote candidate is exposed without its address, so it can't be found among the signalled ones). - struct
Payloadfrompeer::PayloadA received payload's bytes (a data channel message, an RTP packet, a frame). Serializes as bytes. - struct
Peerfrompeer::Peer - struct
PeerDescriptionsfrompeer::PeerDescriptionsThe four description slots of a connection, each(type, sdp). - struct
PeerOptionsfrompeer::PeerOptionsOptions forPeer::new, fromRTCConfiguration. - struct
PlainNetIofromnet_io::PlainNetIoThe operating system's sockets and resolver, unrouted. - struct
PortRangeArgfromnet::PortRangeArg - struct
PublicAddressfromnet::PublicAddressA public address and the private one it maps to (None: every private address). - struct
Reachfromgate::ReachOne thing the engine wants to reach. - struct
SelectedPairfrompeer::SelectedPairThe ICE agent's selected candidate pair. - struct
TcpEndpointfromnet::TcpEndpointOne of an ICE-TCP network's listeners. - struct
UdpOptsfromnet_io::UdpOptsHowNetIo::bind_udpbinds. - enum
Directionfromgate::DirectionWhether aReachsends to an address or binds one. - enum
ErrorKindfromerror::ErrorKindWhich exception a failure is, as the W3C WebRTC specs name them. - enum
Hostfromgate::HostA host aReachnames: a name (an ICE server URL's host, before DNS) or an IP address. - enum
IceEventfromice_transport::IceEventAn event for JavaScript, delivered in batches byop_webrtc_ice_next_events. - enum
JsEventfrompeer::JsEventAn event for JavaScript, delivered in batches byPeer::next_events. Data channels are named by their engine handle (channel), which exists before the SCTP stream id does. - enum
MdnsModefromnet::MdnsModeWhat a connection does with mDNS.localhost candidates. - enum
Protofromgate::ProtoThe transport of aReach. - enum
ReachKindfromgate::ReachKindWhy the engine asks (for logs and prompts; a gate may also decide on it). The engine's cache of asked answers ignores the kind: an answer for one kind is reused for another with the same direction, transport, host, port andresolved_from. - enum
ServerTransportfrompeer::ServerTransportHow a STUN/TURN client reaches its server. - enum
Verdictfromgate::VerdictA gate's answer. - trait
NetGatefromgate::NetGateThe net permission gate. There is no allowing default: everyPeer,NetworkandIceTransportis given one, andDenyAllGaterefuses everything. - trait
NetIofromnet_io::NetIoThe socket factory. - fn
certificate_fingerprintsfromcertificate::certificate_fingerprintsThe certificate's fingerprints, in each algorithm the engine computes. - fn
certificate_from_pemfromcertificate::certificate_from_pemThe inverse ofcertificate_to_pem; anything else is aSyntaxError. - fn
certificate_to_pemfromcertificate::certificate_to_pemDeno.webrtc.exportCertificate: the key and certificate as PEM, with theexpirestime, to keep a server's DTLS fingerprint across restarts. - fn
check_ice_serversAsksgatefor each server's host and port before DNS (ReachKind::IceServer); the first refusal is aErrorKind::NotCapableerror. - fn
engine_log_levelfromlog_level::engine_log_levelThe engine's log level (off by default: its outcomes areRTCPeerConnectionevents). A host's logger shows engine records at or above it, and no others. - fn
epoch_fields_relativefrompeer::epoch_fields_relativeOne stats dictionary with its epoch fields made relative towall_ms, the wall clock (milliseconds since the epoch) when the report was asked for: JavaScript adds the Performance time of that moment, so the timestamps areDOMHighResTimeStamps onperformance.timeOrigin's timeline (W3C webrtc-stats, hr-time) whatever the wall clock does. - fn
expires_msfromcertificate::expires_msThe W3Cexpires, a DOMTimeStamp: whole milliseconds since the epoch. - fn
fake_media_devicesWhether the fake capture devices are on (DENO_FAKE_MEDIA_DEVICES=1). - fn
generate_certificatefromcertificate::generate_certificateThe DTLS key: ECDSA P-256 (what browsers default to), or RSASSA-PKCS1-v1_5 with SHA-256 and the public exponent 65537 (WebCrypto's algorithm dictionaries, asgenerateCertificatetakes them). CPU-heavy for RSA: call it off the engine's thread. - fn
is_engine_log_targetfromlog_level::is_engine_log_targetWhether a log record comes from the WebRTC engine (thertciandrtci_*crates), whose recordsset_engine_log_levelgoverns. This crate's own records (rtci_host::*) are not the engine's: they follow the host's log filter, as they did inside the Deno extension. - fn
mdns_socketfromnet_io::mdns_socketFinishes an mDNS socket (IPv4, UDP): reuse options and the bind on0.0.0.0:5353unlessbound(a socket handed out bound already, as a sandbox broker does), non-blocking, multicast TTL 255 with loopback, and the mDNS group joined on each non-loopback IPv4 address ofhosts(on the default interface when none joins). ForNetIo::bind_mdnsimplementations. - fn
needs_tlsWhether any server needs TLS (turns:/stuns:): the front end then buildsPeerOptions::tls. - fn
parse_ice_serversParses every URL ofRTCConfiguration.iceServers(the W3CSyntaxError/InvalidAccessErrorchecks); no gate is asked. - fn
set_engine_log_levelfromlog_level::set_engine_log_levelSets the engine's log level by name:off,error,warn,info,debugortrace(aErrorKind::Typeerror for any other). - type
LocalBoxFuturefromgate::LocalBoxFutureA boxed,!Sendfuture (the engine is single-threaded). - type
Resultfromerror::ResultResultwith this crate'sError. - const
DEFAULT_ASK_TIMEOUTfromgate::DEFAULT_ASK_TIMEOUTHow long the engine waits for an asked answer by default (NetGate::ask_timeout). - const
NO_GATE_REGISTEREDfromask_gate::NO_GATE_REGISTEREDThe refusal for every question asked beforeAskGate::attach.
rtci_host::media_types
The media types the front ends pass and receive (transceivers, tracks, codecs, capabilities, frames).
- struct
Capabilitiesfromcrate::media::Capabilities - struct
CodecArgfromcrate::media::CodecArgRTCRtpCodecas JavaScript sees it: a dictionary, so a member the codec doesn't have (a video codec'schannels, an absent fmtp line) is left out rather thannull. - struct
EncodingArgfromcrate::media::EncodingArg - struct
FakeFramefromcrate::media::FakeFrameA fake capture device's frame, for an encoded transform. - struct
ReceivedFrameInfofromcrate::encoded_frames::ReceivedFrameInfoWhat a received frame's metadata names. - struct
RemoteSectionfromcrate::media::RemoteSectionOne m-section of the remote description, by mid. - struct
SenderFrameInfofromcrate::media::SenderFrameInfoWhat an encoded frame's metadata names about its sender. - struct
TrackArgfromcrate::media::TrackArg - struct
TransceiverArgfromcrate::media::TransceiverArg - struct
TransceiverInfofromcrate::media::TransceiverInfoA transceiver as JavaScript reconciles it after every operation. - fn
capabilitiesfromcrate::media::capabilitiesRTCRtpSender.getCapabilities(kind)/RTCRtpReceiver.getCapabilities: what the media stack offers, read from the offer of a connection that is never used for anything else (the engine's codec lists are internal). RTX is listed once, without theaptthat ties each RTX payload type to its primary, as browsers list it.
Generated from the sources of rtci-host 0.2.0 at its release tag. Items made by macros and methods are on docs.rs.