rtciv0.5.0

Getting started

Minimal rtci programs. Every code block on this page is copied from rtci 0.5.0 (README doctests, which CI compiles, and the repository's examples) and linked to the file at the tag.

Add the crate

cargo add [email protected]

The examples below also use tokio and bytes, as the README's do. The minimum supported Rust version is 1.89; see Install & download for the crypto provider features.

One rule first: bring the trait into scope

The event loop is the sansio::Protocol trait implemented by RTCPeerConnection. Bring it into scope with use rtci::sansio::Protocol;, or handle_read, poll_write, poll_read, poll_event, poll_timeout, handle_timeout and handle_write will not resolve. The sans-I/O model explains each of them.

A peer connection and its event loop

You own the socket and the loop. The connection is built with the instant the session starts, every description call takes the current instant, and the loop drains what the connection wants to send, its events and its inbound messages, then waits for a packet or the next 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.

Two things to note in it: the socket is bound to a concrete local address (the address of the host candidate you add, never 0.0.0.0), and RTCPeerConnectionEvent and RTCMessage are #[non_exhaustive], so a match on them needs a _ arm.

Tell it your candidates

The engine does no I/O, so it does no host candidate gathering either: you bind the sockets, so you add the local candidates. An empty candidate is the end-of-gathering sentinel:

use rtci::peer_connection::RTCPeerConnectionBuilder;
use rtci::peer_connection::transport::{
    CandidateConfig, CandidateHostConfig, RTCIceCandidate, RTCIceCandidateInit,
};
use std::time::Instant;

fn gather(pc: &mut rtci::peer_connection::RTCPeerConnection) -> Result<(), Box<dyn std::error::Error>> {
    let candidate = CandidateHostConfig {
        base_config: CandidateConfig {
            network: "udp".to_owned(),
            address: "192.168.1.100".to_string(),
            port: 8080,
            component: 1,
            ..Default::default()
        },
        ..Default::default()
    }
    .new_candidate_host()?;
    pc.add_local_candidate(RTCIceCandidate::from(&candidate).to_json()?)?;

    // An EMPTY candidate string is the end-of-gathering sentinel: it moves the ICE gathering
    // state to `Complete` and emits `OnIceGatheringStateChangeEvent(Complete)`. Nothing else
    // reaches that state, so send it once you have added every local candidate.
    pc.add_local_candidate(RTCIceCandidateInit::default())?;
    Ok(())
}

From README.md, “Feeding ICE Candidates” at v0.5.0.

Remote candidates arrive over your signalling channel and go in through add_remote_candidate, after a remote description has been set. With stun: / turn: servers configured the engine gathers the server-reflexive and relayed candidates itself, from the UDP host candidates you add (ICE, STUN, TURN and mDNS).

Signalling

rtci needs an external signalling channel to exchange offers and answers, as any WebRTC stack does:

use rtci::peer_connection::RTCPeerConnection;
use rtci::peer_connection::sdp::RTCSessionDescription;
use std::time::Instant;

fn negotiate(
    pc: &mut RTCPeerConnection,
    answer_sdp: String,
) -> Result<(), Box<dyn std::error::Error>> {
    let offer = pc.create_offer(None)?;
    pc.set_local_description(Instant::now(), offer.clone())?;
    // send `offer.sdp` over your signaling channel, receive the answer, then:
    let answer = RTCSessionDescription::answer(answer_sdp)?;
    pc.set_remote_description(Instant::now(), answer)?;
    Ok(())
}

From README.md, “Signaling” at v0.5.0.

A data channel

use rtci::data_channel::{RTCDataChannelId, RTCDataChannelInit};
use rtci::peer_connection::RTCPeerConnection;
use rtci::peer_connection::event::{RTCDataChannelEvent, RTCPeerConnectionEvent};
use rtci::sansio::Protocol;
use std::time::Instant;

fn open(pc: &mut RTCPeerConnection) -> Result<RTCDataChannelId, Box<dyn std::error::Error>> {
    let init = RTCDataChannelInit {
        ordered: true,
        max_retransmits: None,
        ..Default::default()
    };
    // The handle borrows `pc`, so keep the id to reach the channel again later.
    let id = pc.create_data_channel("my-channel", Some(init))?.id();
    Ok(id)
}

fn on_open(pc: &mut RTCPeerConnection, id: RTCDataChannelId) -> Result<(), Box<dyn std::error::Error>> {
    // Only send once the channel is open: an in-band channel's SCTP stream is
    // established by the DCEP handshake, and sending before then is rejected.
    if let Some(mut dc) = pc.data_channel(id) {
        dc.send_text(Instant::now(), "Hello, WebRTC!")?;
    }
    Ok(())
}

fn drive(pc: &mut RTCPeerConnection) -> Result<(), Box<dyn std::error::Error>> {
    while let Some(event) = pc.poll_event() {
        if let RTCPeerConnectionEvent::OnDataChannel(RTCDataChannelEvent::OnOpen(id)) = event {
            on_open(pc, id)?;
        }
    }
    Ok(())
}

From README.md, “Data Channels” at v0.5.0.

Send only once the channel is open, and keep the channel's id rather than the handle, which borrows the connection. See Data channels for the message size limit toward browsers.

The smallest complete program

stream-driver-loopback runs two peer connections in one process over loopback TCP, through the reference driver (rtci-stream-driver), with a data channel: the README calls it the smallest complete program. It exits 0 once 50 messages crossed the data channel in order. In the repository the driver is imported as stream_driver (the workspace's dependency key); from crates.io the crate is rtci_stream_driver (cargo add [email protected]).

//! Two peer connections over loopback TCP, through the reference driver (`rtci-stream-driver`),
//! with a data channel: the smallest complete program that runs the engine's stream half.
//!
//! What is the engine's and what is the driver's:
//!
//! - **Engine** (`rtci`): decides everything. It gathers the ICE-TCP candidates (RFC 6544) for
//!   the UDP host address the application gives it, asks for listeners and connections by id
//!   (`poll_stream_command`), frames every packet with RFC 4571 (`poll_stream_transmit`),
//!   runs ICE, DTLS, SCTP and the data channel over them and closes what ICE no longer needs.
//! - **Driver** (`rtci_stream_driver::StreamDriver`, tokio): owns the sockets and nothing else.
//!   It binds, connects, accepts, reads and writes when told and reports what happened
//!   (`DriverInput`), which the loop hands back to the engine.
//! - **Application** (this file): signalling (here, passing descriptions and candidates
//!   between the two connections in one process) and the event loop.
//!
//! UDP is "blocked" here: nothing written for it leaves, so the connection can only come up
//! over the engine's TCP candidates. Run with `cargo run --example stream-driver-loopback`; it
//! exits 0 once 50 messages crossed the data channel in order, 1 after 30 s without.

use bytes::BytesMut;
use rtci::peer_connection::event::{RTCDataChannelEvent, RTCPeerConnectionEvent};
use rtci::peer_connection::message::RTCMessage;
use rtci::peer_connection::state::RTCPeerConnectionState;
use rtci::peer_connection::transport::RTCIceCandidateInit;
use rtci::peer_connection::{RTCPeerConnection, RTCPeerConnectionBuilder};
use rtci::sansio::Protocol;
use std::time::{Duration, Instant};
use stream_driver::{DriverInput, StreamDriver};

/// One side: the engine, the driver that owns its sockets, and what it has seen.
struct Peer {
    name: &'static str,
    pc: RTCPeerConnection,
    driver: StreamDriver,
    connected: bool,
    /// Candidates to trickle to the other side.
    outbox: Vec<RTCIceCandidateInit>,
    received: Vec<Vec<u8>>,
    open: Option<rtci::data_channel::RTCDataChannelId>,
}

impl Peer {
    fn new(name: &'static str) -> Result<Self, Box<dyn std::error::Error>> {
        Ok(Self {
            name,
            pc: RTCPeerConnectionBuilder::new().build(Instant::now())?,
            driver: StreamDriver::default(),
            connected: false,
            outbox: vec![],
            received: vec![],
            open: None,
        })
    }

    /// The UDP host address the engine gathers its TCP candidates for. Its port is never
    /// used: UDP is blocked in this example.
    fn add_host(&mut self, port: u16) -> Result<(), Box<dyn std::error::Error>> {
        self.pc.add_local_candidate(RTCIceCandidateInit {
            candidate: format!("candidate:1 1 udp 2130706431 127.0.0.1 {port} typ host"),
            ..Default::default()
        })?;
        Ok(())
    }

    /// The engine's half of the loop: its commands and transmits to the driver, its events
    /// and reads to the application.
    fn run_engine(&mut self) {
        while let Some(command) = self.pc.poll_stream_command() {
            self.driver.execute(command);
        }
        while let Some(transmit) = self.pc.poll_stream_transmit() {
            self.driver.write(transmit);
        }
        // UDP is blocked: datagrams for it are dropped.
        while self.pc.poll_write().is_some() {}
        while let Some(event) = self.pc.poll_event() {
            match event {
                RTCPeerConnectionEvent::OnIceCandidateEvent(ev) => {
                    if let Some(c) = ev.candidate.filter(|c| !c.end_of_candidates)
                        && let Ok(init) = c.to_json()
                    {
                        self.outbox.push(init);
                    }
                }
                RTCPeerConnectionEvent::OnConnectionStateChangeEvent(
                    RTCPeerConnectionState::Connected,
                ) => {
                    println!("{}: connected", self.name);
                    self.connected = true;
                }
                RTCPeerConnectionEvent::OnDataChannel(RTCDataChannelEvent::OnOpen(id)) => {
                    self.open = Some(id);
                }
                _ => {}
            }
        }
        while let Some(message) = self.pc.poll_read() {
            if let RTCMessage::DataChannelMessage(_, m) = message.message {
                self.received.push(m.data.to_vec());
            }
        }
    }

    /// The driver's half: what the sockets did, back to the engine.
    fn run_driver(&mut self) {
        while let Some(input) = self.driver.try_next() {
            let now = Instant::now();
            match input {
                DriverInput::Event(event) => {
                    let _ = self.pc.handle_stream_event(now, event);
                }
                DriverInput::Read { id, data } => {
                    let _ = self.pc.handle_stream_read(now, id, &data);
                }
                DriverInput::Accepted(accepted) => {
                    match self.pc.handle_stream_accepted(
                        now,
                        accepted.listener,
                        accepted.local,
                        accepted.remote,
                    ) {
                        Some(id) => self.driver.adopt(id, accepted),
                        // Refused by the engine: dropping it closes the socket.
                        None => drop(accepted),
                    }
                }
            }
        }
        let now = Instant::now();
        if self.pc.poll_timeout().is_some_and(|t| t <= now) {
            let _ = self.pc.handle_timeout(now);
        }
    }
}

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut offerer = Peer::new("offerer")?;
    let mut answerer = Peer::new("answerer")?;

    // Signalling, in-process.
    let channel = offerer.pc.create_data_channel("loopback", None)?.id();
    let offer = offerer.pc.create_offer(None)?;
    offerer
        .pc
        .set_local_description(Instant::now(), offer.clone())?;
    answerer.pc.set_remote_description(Instant::now(), offer)?;
    let answer = answerer.pc.create_answer(None)?;
    answerer
        .pc
        .set_local_description(Instant::now(), answer.clone())?;
    offerer.pc.set_remote_description(Instant::now(), answer)?;
    offerer.add_host(40000)?;
    answerer.add_host(40001)?;

    let messages: Vec<Vec<u8>> = (0..50u8).map(|i| vec![i; 100 + 37 * i as usize]).collect();
    let mut sent = false;
    let deadline = Instant::now() + Duration::from_secs(30);
    while Instant::now() < deadline {
        for peer in [&mut offerer, &mut answerer] {
            peer.run_engine();
        }
        for c in std::mem::take(&mut offerer.outbox) {
            let _ = answerer.pc.add_remote_candidate(c);
        }
        for c in std::mem::take(&mut answerer.outbox) {
            let _ = offerer.pc.add_remote_candidate(c);
        }
        if !sent && offerer.open == Some(channel) {
            let mut dc = offerer.pc.data_channel(channel).ok_or("no channel")?;
            for m in &messages {
                dc.send(Instant::now(), BytesMut::from(&m[..]))?;
            }
            sent = true;
        }
        if answerer.received.len() >= messages.len() {
            assert_eq!(answerer.received, messages, "every message, in order");
            println!(
                "{} messages over a TCP candidate pair through the driver",
                messages.len()
            );
            return Ok(());
        }
        // Let the driver's tasks run, then take what the sockets did.
        tokio::time::sleep(Duration::from_millis(1)).await;
        for peer in [&mut offerer, &mut answerer] {
            peer.run_driver();
        }
    }
    eprintln!(
        "timed out: connected {}/{}, received {} of {}",
        offerer.connected,
        answerer.connected,
        answerer.received.len(),
        messages.len()
    );
    std::process::exit(1);
}

The whole of examples/stream-driver-loopback/stream-driver-loopback.rs at v0.5.0.

Run it from a checkout of the tag with cargo run --example stream-driver-loopback.

More examples

The repository's examples cover the common cases; they are not part of the published crate. Among them: data-channels-offer / data-channels-answer (complete data channel setup with signalling), data-channels-flow-control (back-pressure), trickle-ice, ice-restart, perfect-negotiation (glare-free renegotiation with rollback), reflect, save-to-disk-vpx / play-from-disk-vpx, simulcast, broadcast and stats. Run one by its registered name:

cargo run --example data-channels-offer
cargo run --example data-channels-answer

From README.md, “Examples” at v0.5.0.

Next