rtciv0.5.0

The sans-I/O model

rtci handles the protocol logic; you control all I/O. You feed it network data and the time, and it tells you what to send, what happened and when to call it next.

What sans-I/O means here

Instead of the library performing network reads and writes, the application feeds it network data and it says what to send. That makes the engine independent of the async runtime (tokio, async-std, smol or blocking I/O), leaves threading, scheduling and I/O multiplexing to the application, lets the protocol logic run in tests without a network, and fits it into existing networking code.

There is no ambient clock either: every method that needs the time takes an Instant from the caller. That is what makes a whole session reproducible in a test without a socket or a sleep. The protocol crates' READMEs (rtci-ice, rtci-dtls, rtci-sctp, rtci-srtp and the others) each have a "Sans-I/O" section to the same effect: no I/O, no clock, time passed in by the caller.

The event loop methods

The loop is the sansio::Protocol trait implemented by RTCPeerConnection. Bring it into scope with use rtci::sansio::Protocol; or none of these methods will resolve. From the README:

MethodDirectionWhat it does
handle_read(TaggedBytesMut)inFeed one received UDP/TCP datagram, tagged with its 5-tuple and arrival instant
poll_write() -> Option<TaggedBytesMut>outTake the next packet to put on the wire; drain until None
poll_read() -> Option<TaggedRTCMessage>outTake the next inbound RTP/RTCP/data-channel message for the application
poll_event() -> Option<RTCPeerConnectionEvent>outTake the next state change or notification
poll_timeout() -> Option<Instant>outNext deadline for retransmissions, keepalives and ICE checks
handle_timeout(Instant)inTell the connection a deadline has passed
handle_write(TaggedRTCMessage)inQueue an outbound RTP/RTCP/data-channel message
close()inShut the connection down

Order matters only in that poll_write should be drained after anything that could have produced output: handle_read, handle_timeout, handle_write and the negotiation calls all queue packets rather than sending them.

handle_event is also part of the trait, but RTCEvent is currently uninhabited: no value of it can be constructed, so there is nothing to call it with.

Timers

poll_timeout() is the next protocol deadline (retransmissions, keepalives, ICE checks). Wait for whichever comes first, a datagram or that deadline, and call handle_timeout(now) when the deadline passes. The README's loop uses a long default when there is no deadline:

use rtci::peer_connection::RTCPeerConnectionBuilder;
use rtci::peer_connection::configuration::RTCConfigurationBuilder;
use rtci::peer_connection::event::{RTCPeerConnectionEvent, RTCTrackEvent};
use rtci::peer_connection::state::RTCPeerConnectionState;
use rtci::peer_connection::message::{RTCMessage, TaggedRTCMessage};
use rtci::peer_connection::sdp::RTCSessionDescription;
use rtci::peer_connection::transport::RTCIceServer;
use rtci::shared::{TaggedBytesMut, TransportContext, TransportProtocol};
use rtci::sansio::Protocol;
use std::time::{Duration, Instant};
use tokio::net::UdpSocket;
use bytes::BytesMut;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 1. Build the peer connection. `build` takes the instant the session starts.
    let mut pc = RTCPeerConnectionBuilder::new()
        .with_configuration(
            RTCConfigurationBuilder::new()
                .with_ice_servers(vec![RTCIceServer {
                    urls: vec!["stun:stun.l.google.com:19302".to_string()],
                    ..Default::default()
                }])
                .build(),
        )
        .build(Instant::now())?;

    // 2. Signaling: every description call also takes the current instant.
    let offer = pc.create_offer(None)?;
    pc.set_local_description(Instant::now(), offer.clone())?;
    // send `offer.sdp` over your signaling channel, then:
    //   let answer = RTCSessionDescription::answer(answer_sdp)?;
    //   pc.set_remote_description(Instant::now(), answer)?;

    // 3. You own the socket. Bind a concrete local address, the one you add as a host
    //    candidate ("Feeding ICE Candidates"): `local_addr` below must be a local candidate's
    //    address, and a socket bound to 0.0.0.0 reports 0.0.0.0:port, which none is.
    let socket = UdpSocket::bind("192.168.1.100:0").await?;
    let local_addr = socket.local_addr()?;
    let mut buf = vec![0u8; 2000];
    const DEFAULT_TIMEOUT: Duration = Duration::from_secs(86400);

    loop {
        // Drain everything the connection wants to send.
        while let Some(msg) = pc.poll_write() {
            socket.send_to(&msg.message, msg.transport.peer_addr).await?;
        }

        // Drain state changes and notifications.
        while let Some(event) = pc.poll_event() {
            match event {
                RTCPeerConnectionEvent::OnConnectionStateChangeEvent(state) => {
                    println!("connection state: {state}");
                    if state == RTCPeerConnectionState::Failed {
                        return Ok(());
                    }
                }
                RTCPeerConnectionEvent::OnTrack(RTCTrackEvent::OnOpen(init)) => {
                    println!("new track: {}", init.track_id);
                }
                // RTCPeerConnectionEvent is #[non_exhaustive].
                _ => {}
            }
        }

        // Drain inbound application messages. `poll_read` yields a *tagged* message:
        // `now` is when the packet was observed at the socket, not when you drained it.
        while let Some(TaggedRTCMessage { now, message }) = pc.poll_read() {
            match message {
                RTCMessage::RtpPacket(track_id, _packet) => {
                    println!("RTP on track {track_id} at {now:?}");
                }
                RTCMessage::RtcpPacket(receiver_id, _packets) => {
                    println!("RTCP for receiver {receiver_id:?}");
                }
                RTCMessage::DataChannelMessage(channel_id, _msg) => {
                    println!("data-channel message on {channel_id:?}");
                }
                // RTCMessage is #[non_exhaustive].
                _ => {}
            }
        }

        // Wait for whichever comes first: a packet or the next protocol deadline.
        let timeout = pc.poll_timeout().unwrap_or(Instant::now() + DEFAULT_TIMEOUT);
        let delay = timeout.saturating_duration_since(Instant::now());
        if delay.is_zero() {
            pc.handle_timeout(Instant::now())?;
            continue;
        }

        tokio::select! {
            biased;

            _ = tokio::time::sleep(delay) => {
                pc.handle_timeout(Instant::now())?;
            }
            Ok((n, peer_addr)) = socket.recv_from(&mut buf) => {
                pc.handle_read(TaggedBytesMut {
                    now: Instant::now(),
                    transport: TransportContext {
                        local_addr,
                        peer_addr,
                        ecn: None,
                        transport_protocol: TransportProtocol::UDP,
                    },
                    message: BytesMut::from(&buf[..n]),
                })?;
            }
        }
    }
}

From README.md, “Event Loop Example” at v0.5.0.

poll_read yields a tagged message: its now is when the packet was observed at the socket, not when you drained it.

The local address of a datagram

The local_addr of a datagram given to handle_read is the address of the local candidate it arrived on, not necessarily the socket's own address: the ICE agent matches it exactly against its local candidates (RFC 8445 section 7.3.1.4) and discards anything else. Two cases trip ported code:

  • A socket bound to the unspecified address (0.0.0.0:port, [::]:port) must report the concrete local address each datagram was received on (IP_PKTINFO / IPV6_RECVPKTINFO or the platform's equivalent). Or bind one socket per local address, as rtci-stream-driver's PeerDriver does.
  • A datagram relayed by a TURN allocation the application runs (RelayGathering::Application) carries the relayed address as local_addr. In the other direction, a datagram from poll_write whose transport.local_addr is the relayed address goes through the allocation, not out of a socket.
// wildcard-bound socket: the destination address of the datagram, not 0.0.0.0:port
let local_addr = SocketAddr::new(destination_ip /* IP_PKTINFO */, socket.local_addr()?.port());
// relayed by the application's TURN client
pc.handle_read(TaggedBytesMut { now, message: payload, transport: TransportContext {
    local_addr: relayed_addr, peer_addr: peer, transport_protocol: TransportProtocol::UDP, ecn: None } })?;
// and out
while let Some(msg) = pc.poll_write() {
    if msg.transport.local_addr == relayed_addr { turn.send_to(&msg.message, msg.transport.peer_addr)?; }
    else { socket_of(msg.transport.local_addr).send_to(&msg.message, msg.transport.peer_addr)?; }
}

From README.md, “Driving the Engine” at v0.5.0.

The stream half: TCP without sockets

The second half of the loop is needed only when the engine is to run TCP itself (ICE-TCP candidates, TURN over TCP or TLS). The engine names its TCP connections and listeners by id; the application only owns the sockets. After each input:

while let Some(command) = pc.poll_stream_command()  { /* Listen, Connect, Close, Reset, Resolve */ }
while let Some(transmit) = pc.poll_stream_transmit() { /* write transmit.data on transmit.id */ }
// what the sockets did:
pc.handle_stream_event(now, event)?;   // Listening, Connected, Written, Closed, Reset, Resolved, ...
pc.handle_stream_accepted(now, listener, local, remote)   // Some(id), or None: close the socket
pc.handle_stream_read(now, id, &bytes)?;                  // any piece size; the engine reassembles

From README.md, “Driving the Engine” at v0.5.0.

Once the application serves this interface, the engine gathers passive, simultaneous-open and active TCP candidates for each UDP host address it is given (RFC 6544), frames with RFC 4571, connects to turn:...?transport=tcp and turns: servers (names resolved through StreamCommand::Resolve, Happy Eyeballs across the addresses) and closes the connections ICE no longer needs. StreamEvent::Written is the back-pressure signal. An application that never polls the stream interface gets no TCP candidate and nothing changes; SettingEngineBuilder::with_tcp_candidate_gathering(false) keeps the engine's TCP off.

Poll the stream interface before adding the end of candidates: the end of gathering waits for the listeners only of an application that has served the interface.

The reference driver, rtci-stream-driver, implements this half on an async runtime of your choice; its loop:

while let Some(command) = pc.poll_stream_command() { driver.execute(command) }
while let Some(transmit) = pc.poll_stream_transmit() { driver.write(transmit) }
match driver.next().await {
    DriverInput::Event(event) => pc.handle_stream_event(now, event)?,
    DriverInput::Read { id, data } => pc.handle_stream_read(now, id, &data)?,
    DriverInput::Accepted(accepted) => { /* pc.handle_stream_accepted, then driver.adopt */ }
}

From examples/stream-driver/README.md, “Use” at v0.5.0.

Back-pressure

poll_read is the throttle. Undrained data-channel messages leave bytes in SCTP's reassembly queue, which lowers the receiver-window credit advertised in every SACK, which tells the peer to slow down. Declining to call poll_read is how you apply back-pressure; resume when the application catches up. Media is never throttled this way: RTP arrives over SRTP and is subject to none of SCTP's flow control.

After close()

After close(), keep the loop running for the connection until poll_timeout() returns None: drain poll_write onto the socket, feed what arrives with handle_read, call handle_timeout at poll_timeout. close() queues the last datagrams (DTLS close_notify, a TURN Refresh of lifetime 0 that releases an allocation, retransmitted as an ordinary STUN transaction). Each released allocation raises OnTurnAllocationReleased with the local address it used. Dropping a connection without close() sends nothing.

Where to read more