Skip to main content

Crate rtci

Crate rtci 

Source
Expand description

§RTC - Sans-I/O WebRTC Implementation

A Rust implementation of the WebRTC specification using a sans-I/O architecture. This crate provides full WebRTC functionality while giving you complete control over networking, threading, and async runtime integration.

§What is Sans-I/O?

Sans-I/O (without I/O) is a design pattern that separates protocol logic from I/O operations. Instead of the library performing network reads and writes directly, you provide the network data and handle the output. This gives you:

  • Runtime Independence: Works with tokio, async-std, smol, or blocking I/O
  • Full Control: You control threading, scheduling, and I/O multiplexing
  • Testability: Protocol logic can be tested without real network I/O
  • Flexibility: Easy integration with existing networking code

§Quick Start

use rtci::peer_connection::RTCPeerConnectionBuilder;
use rtci::peer_connection::configuration::RTCConfigurationBuilder;
use rtci::peer_connection::transport::RTCIceServer;
use rtci::peer_connection::sdp::RTCSessionDescription;
use rtci::peer_connection::transport::{CandidateConfig, CandidateHostConfig, RTCIceCandidate};

// 1. Create a peer connection with ICE servers
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. Create an offer
let offer = pc.create_offer(None)?;
pc.set_local_description(Instant::now(), offer.clone())?;

// Send offer to remote peer via your signaling channel
// signaling.send(offer.sdp)?;

// 3. Receive answer from remote peer
// let answer_sdp = signaling.receive()?;
let answer = RTCSessionDescription::answer(answer_sdp)?;
pc.set_remote_description(Instant::now(), answer)?;

// 4. Add local ICE candidate
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()?;
let local_candidate_init = RTCIceCandidate::from(&candidate).to_json()?;
pc.add_local_candidate(local_candidate_init)?;

// 5. Event loop - see complete example below

§Complete Event Loop with All API Calls

This example demonstrates the full sans-I/O event loop pattern with all key API methods:

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

// Configure media codecs
let media_engine = MediaEngine::default();

// Create peer connection
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()
    )
    .with_media_engine(media_engine)
    .build(Instant::now())?;

// Bind UDP socket for network I/O, on the concrete address of the host candidate you add:
// `local_addr` 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 (README, "The local address of a datagram").
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);

// Main event loop
loop {
    // 1. poll_write() - Get outgoing network packets
    while let Some(msg) = pc.poll_write() {
        socket.send_to(&msg.message, msg.transport.peer_addr).await?;
    }

    // 2. poll_event() - Process connection state changes and events
    while let Some(event) = pc.poll_event() {
        match event {
            RTCPeerConnectionEvent::OnIceConnectionStateChangeEvent(state) => {
                println!("ICE Connection State: {state}");
                if state == RTCIceConnectionState::Failed {
                    break;
                }
            }
            RTCPeerConnectionEvent::OnConnectionStateChangeEvent(state) => {
                println!("Connection State: {state}");
                if state == RTCPeerConnectionState::Failed {
                    return Ok(());
                }
            }
            RTCPeerConnectionEvent::OnDataChannel(dc_event) => {
                println!("Data channel event: {:?}", dc_event);
            }
            RTCPeerConnectionEvent::OnTrack(track_event) => {
                match track_event {
                    RTCTrackEvent::OnOpen(init) => {
                        println!("Track opened: track_id={}, receiver_id={:?}",
                            init.track_id, init.receiver_id);
                    }
                    RTCTrackEvent::OnClose(track_id) => {
                        println!("Track closed: {track_id}");
                    }
                    _ => {}
                }
            }
            _ => {}
        }
    }

    // 3. poll_read() - Get incoming application messages (RTP/RTCP/data)
    while let Some(TaggedRTCMessage { message, .. }) = pc.poll_read() {
        match message {
            RTCMessage::RtpPacket(track_id, rtp_packet) => {
                println!("Received RTP packet on track {track_id}");
                // Process RTP packet
            }
            RTCMessage::RtcpPacket(receiver_id, rtcp_packets) => {
                println!("Received RTCP packets on receiver {:?}", receiver_id);
                // Process RTCP packets
            }
            RTCMessage::DataChannelMessage(channel_id, message) => {
                println!("Received data channel message on channel {:?}", channel_id);
                // Process data channel message
            }
            // RTCMessage is #[non_exhaustive]: a wildcard arm is required.
            _ => {}
        }
    }

    // 4. poll_timeout() - Get next timer deadline
    let timeout = pc.poll_timeout()
        .unwrap_or(Instant::now() + DEFAULT_TIMEOUT);
    let delay = timeout.saturating_duration_since(Instant::now());

    // Handle immediate timeout
    if delay.is_zero() {
        // 6. handle_timeout() - Notify about timer expiration
        pc.handle_timeout(Instant::now())?;
        continue;
    }

    // Wait for events using tokio::select!
    let timer = tokio::time::sleep(delay);
    tokio::pin!(timer);

    tokio::select! {
        biased;

        // Timer expired
        _ = timer => {
            pc.handle_timeout(Instant::now())?;
        }
        // Received network packet
        Ok((n, peer_addr)) = socket.recv_from(&mut buf) => {
            // 5. handle_read() - Feed incoming network packets
            pc.handle_read(TaggedBytesMut {
                now: Instant::now(),
                transport: TransportContext {
                    local_addr,
                    peer_addr,
                    ecn: None,
                    transport_protocol: TransportProtocol::UDP,
                },
                message: BytesMut::from(&buf[..n]),
            })?;
        }
        // Ctrl-C to exit
        _ = tokio::signal::ctrl_c() => {
            break;
        }
    }
}

pc.close()?;

§Core API Methods

§Sans-I/O Event Loop Methods

The event loop uses these six core methods:

  1. poll_write() - Get outgoing network packets to send via UDP
  2. poll_event() - Process connection state changes and notifications
  3. poll_read() - Get incoming application messages (RTP, RTCP, data)
  4. poll_timeout() - Get next timer deadline for retransmissions/keepalives
  5. handle_read() - Feed incoming network packets into the connection
  6. handle_timeout() - Notify about timer expiration

Additional methods for external control:

  • handle_write() - Queue application messages (RTP/RTCP/data) for sending
  • handle_event() - Inject external events into the connection

§Signaling with Complete Example

WebRTC requires an external signaling channel to exchange offers, answers, and ICE candidates. This example shows the complete offer/answer flow:

use rtci::peer_connection::RTCPeerConnectionBuilder;
use rtci::peer_connection::configuration::RTCConfigurationBuilder;
use rtci::peer_connection::transport::RTCIceServer;
use rtci::peer_connection::sdp::RTCSessionDescription;
use rtci::peer_connection::transport::{CandidateConfig, CandidateHostConfig, RTCIceCandidate};

// Offerer side - creates the offer
let mut offerer = 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())?;

// 1. Create offer
let offer = offerer.create_offer(None)?;

// 2. Set local description
offerer.set_local_description(Instant::now(), offer.clone())?;

// 3. Add local ICE candidate
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()?;
offerer.add_local_candidate(RTCIceCandidate::from(&candidate).to_json()?)?;

// 4. Send offer to remote peer (your signaling channel)
send_to_remote_peer(&serde_json::to_string(&offer)?);

// --- On answerer side ---
let mut answerer = 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())?;

// 5. Receive and set remote description
let offer_json = receive_from_remote_peer();
let remote_offer: RTCSessionDescription = serde_json::from_str(&offer_json)?;
answerer.set_remote_description(Instant::now(), remote_offer)?;

// 6. Create answer
let answer = answerer.create_answer(None)?;

// 7. Set local description
answerer.set_local_description(Instant::now(), answer.clone())?;

// 8. Send answer back to offerer
send_to_remote_peer(&serde_json::to_string(&answer)?);

// --- Back on offerer side ---
// 9. Receive and set remote description
let answer_json = receive_from_remote_peer();
let remote_answer: RTCSessionDescription = serde_json::from_str(&answer_json)?;
offerer.set_remote_description(Instant::now(), remote_answer)?;

// Now both peers are connected!

§Module Organization

§peer_connection

Core WebRTC peer connection implementation:

§data_channel

WebRTC data channels for arbitrary data transfer:

§rtp_transceiver

RTP media transmission and reception:

§media_stream

Media track management:

§Features

  • ✅ ICE (Interactive Connectivity Establishment) - NAT traversal with STUN/TURN
  • ✅ DTLS (Datagram Transport Layer Security) - Encryption for media and data
  • ✅ SCTP (Stream Control Transmission Protocol) - Reliable data channels
  • ✅ RTP/RTCP - Real-time media transport and control
  • ✅ SDP (Session Description Protocol) - Offer/answer negotiation
  • ✅ Data Channels - Bidirectional peer-to-peer data transfer
  • ✅ Media Tracks - Audio/video transmission
  • ✅ Trickle ICE - Progressive candidate gathering
  • ✅ ICE Restart - Connection recovery
  • ✅ Simulcast & SVC - Scalable video coding

§Working Examples

The crate includes comprehensive examples in the examples/ directory:

  • data-channels-offer-answer - Complete data channel setup with signaling
  • save-to-disk-vpx - Receive and save VP8/VP9 video to disk
  • play-from-disk-vpx - Send VP8/VP9 video from disk
  • rtp-forwarder - Forward RTP streams between peers
  • simulcast - Multiple quality streams
  • trickle-ice - Progressive ICE candidate exchange

See the examples/ directory for complete, runnable code.

§Gathering

The engine has no sockets, so the application gathers: it binds its UDP sockets, gives each host candidate to RTCPeerConnection::add_local_candidate (with the sdp_mid of the transport’s first section when sections are not bundled, see RTCPeerConnection::ice_transport_sections), signals each candidate the engine surfaces (OnIceCandidateEvent) to the peer, and ends a generation with an empty candidate. From a host candidate the engine gathers the rest by itself when it is configured to, from the first local description on (RFC 9429 section 3.5.4; what it finds for an ICE generation no local description represents yet waits for one, W3C webrtc-pc 5.6): the server-reflexive candidates of the STUN servers, the TURN allocations, the ICE-TCP candidates (through the stream interface).

§A transport that needs new candidates

A new DTLS association over UDP runs on a new 3-tuple (RFC 8842 section 5.1: “a new 3-tuple (transport/source address/source port) MUST be allocated by at least one of the endpoints”). So when one is set up on a transport that had one, the engine drops the transport’s local candidates and refuses their UDP addresses (Error::ErrICECandidateAddressOfPreviousDtlsAssociation), and the application must gather again on new ports. It is told with RTCPeerConnectionEvent::OnLocalCandidatesNeeded, which names the transport (its ids, the mids of its sections, the first one’s index), the reason (RTCLocalCandidatesNeededReason) and the refused addresses. It fires when the description that starts the transport’s new gathering is set locally (W3C webrtc-pc 5.6 begins gathering a generation at setLocalDescription), right before the transport’s gatheringstatechange to “gathering”:

  • an ICE restart made for a new DTLS association: renew_dtls_association, automatic SRTP re-keying (SrtpRekeying, on the side that asked), an offer that replaces a data-only association to key SRTP, or a peer’s offer with a new a=tls-id (the answer, when it is set); per transport, each with its own event;
  • the transport that replaced one an answer closed by rejecting every m= section (TransportReplaced): when the next description, which gives it a section, is set;
  • every ICE restart with with_discard_local_candidates_during_ice_restart(true) (DiscardedBySetting; no address is refused then).
  • the first local offer rolled back before any answer (RolledBack; no address is refused): RFC 9429 section 5.7 discards everything gathered for it (“Any resources or candidates that were allocated by the abandoned local description are discarded”: the host candidates, the STUN probes, the TURN allocations, the ICE-TCP listeners), and the next local description (the answer to the peer’s offer, say) gathers anew. The same sockets may be given again.

What to do: bind new UDP sockets, add a host candidate for each with sdp_mid set to the event’s first mid, signal the candidates the engine surfaces, end the generation with an empty candidate for that mid. Keep the previous sockets open and reading: the selected pair keeps carrying the transport’s packets until a pair on a new socket is selected (SelectedCandidatePairChange on that transport), or until the transport closes; close them then, after a few seconds more: the peer selects on its own and may still send to the previous address for a while. The engine’s own gathering follows the new host candidates by itself: it asks the STUN servers from each new base (the probes from a refused base end, so no mapped address of the previous socket is announced), allocates TURN again from a base that is not refused, and gives the ICE-TCP candidates of the address again (RFC 8842 section 5.1 asks a new 3-tuple of unordered transports only; their listener is kept).

A local offer that is rolled back takes its ICE restart back (RFC 9429 section 5.7: “Any resources or candidates that were allocated by the abandoned local description are discarded”), its OnLocalCandidatesNeeded included, although the event has already fired: the transport holds its previous candidates again, on the previous addresses, which are no longer refused, and the candidates given for the abandoned generation are dropped (the peer, which ignored or never got that offer, drops the ones signalled to it: they carry the abandoned username fragment). The application then

  • keeps the previous sockets open and no longer counts them as retired: they carry the transport’s packets as before the offer;
  • closes the sockets it bound for the abandoned generation (or keeps them for the next one: an address that no association used is not refused);
  • waits for the next OnLocalCandidatesNeeded: the answer to the peer’s offer (the usual end of an offer collision, W3C webrtc-pc “perfect negotiation”) fires one when it sets up a new association, and so does the next offer of this side that asks for one.

The transport’s candidates are what RTCIceTransport::get_local_candidates returns, so the application can match its sockets against them once the connection is back in the stable state (OnSignalingStateChangeEvent(Stable)). rtci-stream-driver’s PeerDriver does that.

use rtci::peer_connection::RTCPeerConnection;
use rtci::peer_connection::event::{RTCLocalCandidatesNeededEvent, RTCPeerConnectionEvent};
use rtci::peer_connection::transport::RTCIceCandidateInit;
use std::net::UdpSocket;

fn on_event(
    pc: &mut RTCPeerConnection,
    sockets: &mut Vec<UdpSocket>,
    event: RTCPeerConnectionEvent,
) -> Result<(), Box<dyn std::error::Error>> {
    if let RTCPeerConnectionEvent::OnLocalCandidatesNeeded(needed) = event {
        let RTCLocalCandidatesNeededEvent { mids, sdp_mline_index, .. } = needed;
        // A new port on the same interface (port 0: the system picks a free one).
        let socket = UdpSocket::bind("192.0.2.1:0")?;
        let local = socket.local_addr()?;
        pc.add_local_candidate(RTCIceCandidateInit {
            candidate: format!(
                "candidate:1 1 udp 2130706431 {} {} typ host",
                local.ip(),
                local.port()
            ),
            sdp_mid: mids.first().cloned(),
            sdp_mline_index,
            ..Default::default()
        })?;
        // The end of this transport's generation.
        pc.add_local_candidate(RTCIceCandidateInit {
            sdp_mid: mids.first().cloned(),
            ..Default::default()
        })?;
        // The previous sockets stay open until a pair on the new one is selected.
        sockets.push(socket);
    }
    Ok(())
}

The reference driver, rtci-stream-driver, does all of this by itself (its peer module).

An application with one fixed socket, which cannot move to a new port, turns it off with SettingEngineBuilder::with_dtls_new_association_on_previous_addresses(true): the candidates are kept, their addresses accepted, and no event fires; the new association then shares the previous one’s 3-tuple, which RFC 8842 section 5.1 allows only when the peer allocates a new one.

§Common Patterns

§Configuring Interceptors (NACK, TWCC, RTCP Reports)

Interceptors process RTP/RTCP packets as they flow through the media pipeline. Use the interceptor_registry module to configure packet loss recovery, congestion control, and quality monitoring:

use rtci::peer_connection::RTCPeerConnectionBuilder;
use rtci::peer_connection::configuration::RTCConfigurationBuilder;
use rtci::peer_connection::configuration::media_engine::MediaEngine;
use rtci::peer_connection::configuration::interceptor_registry::{
    Registry, register_default_interceptors,
};

// Create media engine with default codecs
let mut media_engine = MediaEngine::default();

// Collect the default interceptors:
// - NACK: Packet loss recovery for video
// - RTCP Reports: Sender/Receiver quality statistics
// - TWCC Receiver: Congestion control feedback
//
// `build` sorts them wire-to-application, so the order these are asked for does not matter.
let registry = Registry::new();
let registry = register_default_interceptors(registry, &mut media_engine)?;

// Build peer connection with interceptors
let mut pc = RTCPeerConnectionBuilder::new()
    .with_media_engine(media_engine)
    .with_interceptor_registry(registry)
    .build(Instant::now())?;

For custom interceptor configuration:

use rtci::peer_connection::RTCPeerConnectionBuilder;
use rtci::peer_connection::configuration::RTCConfigurationBuilder;
use rtci::peer_connection::configuration::media_engine::MediaEngine;
use rtci::peer_connection::configuration::interceptor_registry::{
    Registry,
    configure_nack,
    configure_rtcp_reports,
    configure_twcc,
};

let mut media_engine = MediaEngine::default();
let registry = Registry::new();

// Ask for what you want, in any order — each interceptor carries the slot it belongs in.
let registry = configure_nack(registry, &mut media_engine);     // Packet loss recovery
let registry = configure_rtcp_reports(registry);                // SR/RR statistics
let registry = configure_twcc(registry, &mut media_engine)?;    // Full TWCC (sender + receiver)

let registry = registry;

let mut pc = RTCPeerConnectionBuilder::new()
    .with_media_engine(media_engine)
    .with_interceptor_registry(registry)
    .build(Instant::now())?;
§One connection type, whatever the chain

A chain is a flat list of interceptors, and RTCPeerConnection has one concrete type no matter what the list contains. Nothing that holds a connection has to know how its chain was assembled, chains can be chosen at runtime, and connections built from different chains share a collection:

use rtci::peer_connection::configuration::interceptor_registry::{
    Registry, register_default_interceptors,
};
use rtci::peer_connection::configuration::media_engine::MediaEngine;
use rtci::peer_connection::{RTCPeerConnection, RTCPeerConnectionBuilder};

// No type parameter: this struct does not have to know the chain.
struct Session {
    peer_connection: RTCPeerConnection,
}

let mut media_engine = MediaEngine::default();
let registry =
    register_default_interceptors(Registry::new(), &mut media_engine)?;

let mut sessions: Vec<Session> = Vec::new();
sessions.push(Session {
    peer_connection: RTCPeerConnectionBuilder::new()
        .with_media_engine(media_engine)
        .with_interceptor_registry(registry)
        .build(Instant::now())?,
});

The cost is one virtual call per interceptor per packet, which is nothing beside SRTP. Static dispatch is still the default — keep the generic form when the chain is fixed at compile time.

§Creating and Using Data Channels

use rtci::peer_connection::RTCPeerConnection;
use rtci::peer_connection::configuration::RTCConfiguration;
use rtci::data_channel::RTCDataChannelInit;
use rtci::peer_connection::event::RTCPeerConnectionEvent;
use std::time::Instant;
use rtci::peer_connection::message::{RTCMessage, TaggedRTCMessage};
use rtci::sansio::Protocol;
use bytes::BytesMut;

// Create data channel with ordered, reliable delivery
let init = RTCDataChannelInit {
    ordered: true,
    max_retransmits: None,
    ..Default::default()
};

let mut dc = pc.create_data_channel("my-channel", Some(init))?;
let channel_id = dc.id();

// Send text message
dc.send_text(Instant::now(), "Hello, WebRTC!")?;

// Send binary message
dc.send(Instant::now(), BytesMut::from(&[0x01, 0x02, 0x03, 0x04][..]))?;

// Later, retrieve the data channel by ID
if let Some(mut dc) = pc.data_channel(channel_id) {
    dc.send_text(Instant::now(), "Another message")?;
}

// Receive messages in event loop
while let Some(TaggedRTCMessage { message, .. }) = pc.poll_read() {
    if let RTCMessage::DataChannelMessage(channel_id, msg) = message {
        if msg.is_string {
            let text = String::from_utf8_lossy(&msg.data);
            println!("Received text: {text}");
        } else {
            println!("Received binary: {} bytes", msg.data.len());
        }
    }
}

§Adding Media Tracks with Codecs

use rtci::peer_connection::RTCPeerConnection;
use rtci::media_stream::MediaStreamTrack;
use rtci::rtp_transceiver::rtp_sender::{RTCRtpCodec, RTCRtpCodecParameters, RtpCodecKind};
use rtci::rtp_transceiver::rtp_sender::{RTCRtpEncodingParameters, RTCRtpCodingParameters};
use rtci::peer_connection::configuration::media_engine::{MIME_TYPE_VP8, MIME_TYPE_OPUS};

// Configure VP8 video codec
let video_codec = RTCRtpCodec {
    mime_type: MIME_TYPE_VP8.to_owned(),
    clock_rate: 90000,
    channels: 0,
    sdp_fmtp_line: "".to_owned(),
    rtcp_feedback: vec![],
};

// Create video track
let video_track = MediaStreamTrack::new(
    "stream-id".to_string(),
    "video-track-id".to_string(),
    "video-label".to_string(),
    RtpCodecKind::Video,
    vec![RTCRtpEncodingParameters {
        rtp_coding_parameters: RTCRtpCodingParameters {
            ssrc: Some(rand::random::<u32>()),
            ..Default::default()
        },
        codec: video_codec.clone(),
        ..Default::default()
    }],
);

// Add track to peer connection
let sender_id = pc.add_track(video_track)?;

// Send RTP packets
if let Some(mut sender) = pc.rtp_sender(sender_id) {
    // sender.write_rtp(Instant::now(), rtp_packet)?;
}

§Receiving Media Tracks

use rtci::peer_connection::RTCPeerConnection;
use rtci::peer_connection::event::{RTCPeerConnectionEvent, RTCTrackEvent};
use rtci::peer_connection::message::{RTCMessage, TaggedRTCMessage};
use rtci::sansio::Protocol;
use std::collections::HashMap;

// Track mapping for received tracks
let mut track_to_receiver = HashMap::new();

// Handle track events
while let Some(event) = pc.poll_event() {
    if let RTCPeerConnectionEvent::OnTrack(track_event) = event {
        match track_event {
            RTCTrackEvent::OnOpen(init) => {
                println!("New track: track_id={}, receiver_id={:?}",
                    init.track_id, init.receiver_id);
                track_to_receiver.insert(init.track_id.clone(), init.receiver_id);
            }
            RTCTrackEvent::OnClose(track_id) => {
                println!("Track closed: {track_id}");
                track_to_receiver.remove(&track_id);
            }
            _ => {}
        }
    }
}

// Receive RTP packets
while let Some(TaggedRTCMessage { message, .. }) = pc.poll_read() {
    if let RTCMessage::RtpPacket(track_id, rtp_packet) = message {
        println!("RTP packet on track {}: {} bytes",
            track_id, rtp_packet.payload.len());
         
        // Access receiver to get track metadata
        if let Some(&receiver_id) = track_to_receiver.get(&track_id) {
            if let Some(receiver) = pc.rtp_receiver(receiver_id) {
                let track = receiver.track();
                let ssrcs: Vec<u32> = track.ssrcs().collect();
                println!("  SSRCs: {:?}, Kind: {:?}", ssrcs, track.kind());
            }
        }
    }
}

§Sending RTCP Packets (e.g., PLI for keyframes)

use rtci::peer_connection::RTCPeerConnection;
use rtci::rtp_transceiver::RTCRtpReceiverId;
use rtci::rtcp::payload_feedbacks::picture_loss_indication::PictureLossIndication;
use std::time::Instant;

// Request keyframe by sending Picture Loss Indication (PLI)
if let Some(mut receiver) = pc.rtp_receiver(receiver_id) {
    receiver.write_rtcp(Instant::now(), vec![Box::new(PictureLossIndication {
        sender_ssrc: 0,
        media_ssrc,
    })])?;
}

§Specification Compliance

This implementation follows these specifications:

  • W3C WebRTC 1.0 - Main WebRTC API specification
  • RFC 9429 - JSEP: JavaScript Session Establishment Protocol
  • RFC 8866 - SDP: Session Description Protocol
  • RFC 8445 - ICE: Interactive Connectivity Establishment
  • RFC 6347 - DTLS: Datagram Transport Layer Security
  • RFC 8831 - WebRTC Data Channels
  • RFC 3550 - RTP: Real-time Transport Protocol

§Further Reading

Re-exports§

pub use crypto;
pub use datachannel;
pub use dtls;
pub use ice;
pub use interceptor;
pub use mdns;
pub use media;
pub use rtcp;
pub use rtp;
pub use sansio;
pub use sctp;
pub use sdp;
pub use sframe;
pub use shared;
pub use srtp;
pub use stun;
pub use turn;

Modules§

data_channel
Peer-to-peer Data API
media_stream
MediaStream API
peer_connection
Peer-to-peer connections
rtp_transceiver
RTP Media API
statistics
Statistics module for WebRTC.