rtci-host
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.
use Rc;
use ;
;
let peer = new?;
let offer = peer.create_offer?;
while let Some = peer.next_events.await
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)fromdecide/interfaces. It is asked every time the engine needs the answer, and nothing waits:set_remote_descriptionandadd_ice_candidatefinish before they return. -
An asynchronous gate returns
Nonewhen it doesn't know yet. The engine then callsask(reach)(orask_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. EveryNetIocall that creates a socket or resolves a name takes aGateToken, which only the engine mints from an allow for thatReach, so aNetIocan checktoken.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
Reachwithout itskind, and dedupes the questions in flight. An answer that doesn't come withinask_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. - no socket is bound, no name resolved and no datagram sent before an
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:
kind is "interfaces" for the interface list; its dir, proto, host,
port and resolvedFrom are then null. An IPv6 host has no brackets.
let gate = new;
gate.set_notify;
gate.attach;
let peer = new?;
// later, on the engine's thread:
for request in gate.take_requests
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:
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.