rtciv0.5.0

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.

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 (.local candidates);
  • 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: DenyAllGate refuses everything, and every Peer, Network and IceTransport takes a gate.
  • NetIo: the only place sockets are created and names resolved. PlainNetIo uses 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.

  • modmedia_typesThe media types the front ends pass and receive (transceivers, tracks, codecs, capabilities, frames).
  • structAskGatefrom ask_gate::AskGateAn asynchronous gate answered by ticket. Deny by default: until AskGate::attach every question is refused at once (NO_GATE_REGISTERED). Once attached, each question the engine asks queues a GateRequest (AskGate::take_requests) and runs the notifier (AskGate::set_notify); AskGate::answer delivers the verdict. An answer is remembered and reused for the same question from any …
  • structCandidateArgRTCIceCandidateInit.
  • structCertificateInfoAn RTCCertificate for the front end's JavaScript.
  • structCertificateStorefrom certificate::CertificateStoreThe RTCCertificates 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 its RTCCertificate is garbage collected; a connection keeps its own copy.
  • structConfigArgRTCConfiguration, as the front end's JavaScript passes it.
  • structCreatedChannelA created data channel: its engine handle and its stream id, when assigned.
  • structDataChannelArgcreateDataChannel(label, init).
  • structDenyAllGatefrom gate::DenyAllGateRefuses everything.
  • structErrorfrom error::ErrorA failure of an rtci-host call: its kind and message.
  • structFingerprintInfoOne RTCDtlsFingerprint.
  • structGateRequestfrom ask_gate::GateRequestOne question for the front end: the gaterequest event.
  • structGateTokenfrom gate::GateTokenProof that the gate allowed a Reach: every NetIo call that creates a socket or resolves a name takes one. Only the engine mints them (there is no public constructor), from an allow for the Reach the call is for, so a NetIo implementation may check GateToken::reach against its arguments.
  • structIceServerArgOne RTCIceServer.
  • structIceServerSpecfrom peer::IceServerSpecA STUN or TURN server URL from RTCConfiguration.iceServers, parsed and permission-checked by the constructor.
  • structIceTimeoutsArgfrom net::IceTimeoutsArg
  • structIceTransportfrom ice_transport::IceTransport
  • structKeygenArggenerateCertificate's algorithm (WebCrypto's dictionaries).
  • structNetworkfrom net::Network
  • structNetworkArgfrom net::NetworkArg
  • structNetworkOptionsfrom net::NetworkOptions
  • structPairCandidatefrom peer::PairCandidateOne candidate of SelectedPair, with the fields JavaScript needs to build the RTCIceCandidate (a peer-reflexive remote candidate is exposed without its address, so it can't be found among the signalled ones).
  • structPayloadfrom peer::PayloadA received payload's bytes (a data channel message, an RTP packet, a frame). Serializes as bytes.
  • structPeerfrom peer::Peer
  • structPeerDescriptionsfrom peer::PeerDescriptionsThe four description slots of a connection, each (type, sdp).
  • structPeerOptionsfrom peer::PeerOptionsOptions for Peer::new, from RTCConfiguration.
  • structPlainNetIofrom net_io::PlainNetIoThe operating system's sockets and resolver, unrouted.
  • structPortRangeArgfrom net::PortRangeArg
  • structPublicAddressfrom net::PublicAddressA public address and the private one it maps to (None: every private address).
  • structReachfrom gate::ReachOne thing the engine wants to reach.
  • structSelectedPairfrom peer::SelectedPairThe ICE agent's selected candidate pair.
  • structSharedEndpointfrom net::SharedEndpointOne of a shared port's sockets.
  • structTcpEndpointfrom net::TcpEndpointOne of an ICE-TCP network's listeners.
  • structUdpOptsfrom net_io::UdpOptsHow NetIo::bind_udp binds.
  • enumDirectionfrom gate::DirectionWhether a Reach sends to an address or binds one.
  • enumErrorKindfrom error::ErrorKindWhich exception a failure is, as the W3C WebRTC specs name them.
  • enumHostfrom gate::HostA host a Reach names: a name (an ICE server URL's host, before DNS) or an IP address.
  • enumIceEventfrom ice_transport::IceEventAn event for JavaScript, delivered in batches by op_webrtc_ice_next_events.
  • enumJsEventfrom peer::JsEventAn event for JavaScript, delivered in batches by Peer::next_events. Data channels are named by their engine handle (channel), which exists before the SCTP stream id does.
  • enumMdnsModefrom net::MdnsModeWhat a connection does with mDNS .local host candidates.
  • enumProtofrom gate::ProtoThe transport of a Reach.
  • enumReachKindfrom gate::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 and resolved_from.
  • enumServerTransportfrom peer::ServerTransportHow a STUN/TURN client reaches its server.
  • enumVerdictfrom gate::VerdictA gate's answer.
  • traitNetGatefrom gate::NetGateThe net permission gate. There is no allowing default: every Peer, Network and IceTransport is given one, and DenyAllGate refuses everything.
  • traitNetIofrom net_io::NetIoThe socket factory.
  • fncertificate_fingerprintsfrom certificate::certificate_fingerprintsThe certificate's fingerprints, in each algorithm the engine computes.
  • fncertificate_from_pemfrom certificate::certificate_from_pemThe inverse of certificate_to_pem; anything else is a SyntaxError.
  • fncertificate_to_pemfrom certificate::certificate_to_pemDeno.webrtc.exportCertificate: the key and certificate as PEM, with the expires time, to keep a server's DTLS fingerprint across restarts.
  • fncheck_ice_serversAsks gate for each server's host and port before DNS (ReachKind::IceServer); the first refusal is a ErrorKind::NotCapable error.
  • fnengine_log_levelfrom log_level::engine_log_levelThe engine's log level (off by default: its outcomes are RTCPeerConnection events). A host's logger shows engine records at or above it, and no others.
  • fnepoch_fields_relativefrom peer::epoch_fields_relativeOne stats dictionary with its epoch fields made relative to wall_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 are DOMHighResTimeStamps on performance.timeOrigin's timeline (W3C webrtc-stats, hr-time) whatever the wall clock does.
  • fnexpires_msfrom certificate::expires_msThe W3C expires, a DOMTimeStamp: whole milliseconds since the epoch.
  • fnfake_media_devicesWhether the fake capture devices are on (DENO_FAKE_MEDIA_DEVICES=1).
  • fngenerate_certificatefrom certificate::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, as generateCertificate takes them). CPU-heavy for RSA: call it off the engine's thread.
  • fnis_engine_log_targetfrom log_level::is_engine_log_targetWhether a log record comes from the WebRTC engine (the rtci and rtci_* crates), whose records set_engine_log_level governs. 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.
  • fnmdns_socketfrom net_io::mdns_socketFinishes an mDNS socket (IPv4, UDP): reuse options and the bind on 0.0.0.0:5353 unless bound (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 of hosts (on the default interface when none joins). For NetIo::bind_mdns implementations.
  • fnneeds_tlsWhether any server needs TLS (turns: / stuns:): the front end then builds PeerOptions::tls.
  • fnparse_ice_serversParses every URL of RTCConfiguration.iceServers (the W3C SyntaxError / InvalidAccessError checks); no gate is asked.
  • fnset_engine_log_levelfrom log_level::set_engine_log_levelSets the engine's log level by name: off, error, warn, info, debug or trace (a ErrorKind::Type error for any other).
  • typeLocalBoxFuturefrom gate::LocalBoxFutureA boxed, !Send future (the engine is single-threaded).
  • typeResultfrom error::ResultResult with this crate's Error.
  • constDEFAULT_ASK_TIMEOUTfrom gate::DEFAULT_ASK_TIMEOUTHow long the engine waits for an asked answer by default (NetGate::ask_timeout).
  • constNO_GATE_REGISTEREDfrom ask_gate::NO_GATE_REGISTEREDThe refusal for every question asked before AskGate::attach.

rtci_host::media_types

The media types the front ends pass and receive (transceivers, tracks, codecs, capabilities, frames).

  • structCapabilitiesfrom crate::media::Capabilities
  • structCodecArgfrom crate::media::CodecArgRTCRtpCodec as JavaScript sees it: a dictionary, so a member the codec doesn't have (a video codec's channels, an absent fmtp line) is left out rather than null.
  • structEncodingArgfrom crate::media::EncodingArg
  • structFakeFramefrom crate::media::FakeFrameA fake capture device's frame, for an encoded transform.
  • structReceivedFrameInfofrom crate::encoded_frames::ReceivedFrameInfoWhat a received frame's metadata names.
  • structRemoteSectionfrom crate::media::RemoteSectionOne m-section of the remote description, by mid.
  • structSenderFrameInfofrom crate::media::SenderFrameInfoWhat an encoded frame's metadata names about its sender.
  • structTrackArgfrom crate::media::TrackArg
  • structTransceiverArgfrom crate::media::TransceiverArg
  • structTransceiverInfofrom crate::media::TransceiverInfoA transceiver as JavaScript reconciles it after every operation.
  • fncapabilitiesfrom crate::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 the apt that 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.