rtciv0.5.0

Peer connection lifecycle

An RTCPeerConnection from build to close, in the W3C model: build it with a configuration, negotiate with offers and answers, watch its states, restart ICE, close it and keep driving it until it is done.

Build

RTCPeerConnectionBuilder takes the configuration (RTCConfigurationBuilder: ICE servers, transport policy, bundle policy, certificates), optionally a SettingEngine, a MediaEngine and an interceptor registry, and build(now), the instant the session starts:

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.

The builder pieces, all in rtci::peer_connection:

PieceWhat it setsWhere
RTCConfigurationBuilderthe W3C RTCConfiguration: ICE servers, ICE transport policy, bundle policy, RTCP mux policy, certificatesconfiguration
SettingEngineBuildereverything outside the W3C configuration: timers, candidate filters, mDNS, DTLS, SCTP, the behaviour profileconfiguration::setting_engine
MediaEnginecodecs and RTP header extensions (register_default_codecs, for_profile)configuration::media_engine
interceptor registrythe RTP/RTCP pipeline: RTCP session, NACK, feedback, congestion controlconfiguration::interceptor_registry

The bare builder has no congestion control. RTCPeerConnectionBuilder::new() without with_interceptor_registry runs the RTCP session and key-frame requests only: no NACK, no transport-wide feedback, no GCC, no pacer, no circuit breaker. Build the registry with register_default_interceptors_with_handles (or register_default_interceptors_with_options); see Congestion control and pacing.

Choose the defaults: behaviour profiles

The defaults follow the RFCs. To take libwebrtc's choices where the two differ, pass a profile to the setting engine, the media engine and (through the media engine) the interceptors:

use rtci::interceptor::Registry;
use rtci::peer_connection::configuration::BehaviourProfile;
use rtci::peer_connection::configuration::interceptor_registry::register_default_interceptors;
use rtci::peer_connection::configuration::media_engine::MediaEngine;
use rtci::peer_connection::configuration::setting_engine::SettingEngineBuilder;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Chosen at run time, here by name ("rfc", "chrome", "strict-rfc", "performance"), or
    // written as BehaviourProfile::Chrome.
    let profile = BehaviourProfile::from_name("chrome").unwrap_or_default();
    let setting_engine = SettingEngineBuilder::new()
        .with_behaviour_profile(profile)
        // A setting given after the profile overrides it.
        .with_sctp_message_size_limit_without_interleaving(true)
        .build();
    let mut media_engine = MediaEngine::for_profile(profile);
    media_engine.register_default_codecs()?;
    // The interceptors take the media engine's profile.
    let registry = register_default_interceptors(Registry::new(), &mut media_engine)?;
    let _ = (setting_engine, registry);
    Ok(())
}

From README.md, “Behaviour profiles” at v0.5.0.

A setting given after the profile overrides it. Every governed setting and its value per profile: Behaviour profiles.

Negotiate

Every description call takes the current instant:

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.

As the answerer: set_remote_description(now, offer), then create_answer(None) and set_local_description(now, answer). Renegotiation follows the W3C model: OnNegotiationNeededEvent says when an offer is needed, signaling_state() tells a collision, and an RTCSdpType::Rollback description undoes a local offer. The repository's perfect-negotiation example implements glare-free renegotiation with rollback at the application level.

Answers list the offered formats only (since 0.3.0): without codec preferences, an answer lists the offered formats this endpoint supports, in the offer's order, as libwebrtc (Chrome, WebKit) answers (RFC 9429 section 5.3.1 says both "MUST be added" and "MAY include" for the other formats). SettingEngineBuilder::with_answer_offered_formats_only(false), or the StrictRfc profile, also lists the other registered formats after them.

Bundle-only sections and browsers. With the default profile, an initial offer's bundle-only m= sections are written in the RFC 9143 / RFC 9429 form, which Chromium, WebKit and Firefox refuse: no browser accepts an rtci offer under max-bundle with more than one m= section. Use the Chrome profile, or SettingEngineBuilder::with_bundle_only_sections_in_browser_form(true) alone, or balanced with one section of each type. Offers from browsers, and answers, are not affected.

Watch the states

States and notifications come out of poll_event() as RTCPeerConnectionEvent values, which is #[non_exhaustive]. The W3C ones: OnNegotiationNeededEvent, OnIceCandidateEvent, OnIceCandidateErrorEvent, OnSignalingStateChangeEvent, OnIceConnectionStateChangeEvent, OnIceGatheringStateChangeEvent, OnConnectionStateChangeEvent, OnDataChannel and OnTrack. Others report what the transports did, among them OnSelectedCandidatePairChange, OnDtlsTransportStateChange, OnSctpTransportStateChange, OnKeyFrameRequest, OnCircuitBreaker, OnPathMtuExceeded, OnLocalCandidatesNeeded, OnTurnAllocationReleased and OnTurnRequestRejected; the event module documents each.

RTCPeerConnectionState is New, Connecting, Connected, Disconnected, Failed or Closed (and Unspecified); connection_state() and signaling_state() read the current ones.

Restart ICE

Two ways, which stage the same restart:

  • RTCOfferOptions { ice_restart: true, .. } restarts ICE in the one offer create_offer is called with;
  • restart_ice() (W3C restartIce) marks the restart until an offer carries it and fires negotiation-needed.

After a restart, send your local candidates to the peer again: a candidate the engine kept across the restart is not announced again, and without them a peer reached only through a relay never selects a pair in the new generation. TURN credentials that expire are rotated on a live connection with rotate_ice_servers(now, servers) and one offer / answer round, which the peer sees as an ICE restart. See ICE, STUN, TURN and mDNS.

Close

close() queues the last datagrams (DTLS close_notify, a TURN Refresh of lifetime 0 for each allocation the engine runs). 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. Each allocation released raises OnTurnAllocationReleased. Dropping a connection without close() sends nothing.

Porting from webrtc-rs rtc

The README's section "Porting from webrtc-rs rtc / older forks" lists the behaviour that differs from webrtc-rs rtc and trips ported code first: add_remote_candidate needs sdp_mid or sdp_mline_index; the bare builder has no congestion control; the target before feedback is a seed (300 kbit/s by default), never zero; data channel messages to browsers are capped at 16 KiB under the Rfc profile; after close(), keep draining poll_write; the engine gathers server-reflexive and relay candidates itself by default; and there are two ways to restart ICE. Read it in full in README.md at v0.5.0.