Skip to content
Systems programming for what’s next.
— Vex

Real-time protocol components (webrtc) ​

webrtc contains SDP negotiation, ICE/STUN/TURN state, RTP/RTCP media transport, SRTP/SRTCP protection, SCTP data-channel components and DTLS parsing/state. Import from "webrtc" or a component such as "webrtc/rtp". The useful unit can be a packet parser or a bounded media receiver; it need not be an entire peer connection.

Inspect and rebuild an RTP packet ​

This complete example round-trips a synthetic RTP packet. Its three payload bytes are test data, not an encoded audio frame.

vex
import { rtpDepacketize, rtpSerializePacket } from "webrtc/rtp";

fn main() {
    let bytes: [u8; 15] = [128, 111, 0, 7, 0, 0, 3, 192, 0, 0, 0, 1, 10, 20, 30];
    let! wire = Vec.new<u8>();
    for octet in bytes { wire.push(octet); }
    let packet = match rtpDepacketize(wire) {
        Ok(value) => value,
        Err(reason) => { $panic(reason); },
    };
    if packet.header.sequenceNumber != 7 || packet.header.timestamp != 960 {
        $panic("wrong RTP header");
    }
    if packet.payload.len() != 3 { $panic("wrong payload length"); }
    let encoded = match rtpSerializePacket(&packet) {
        Ok(value) => value,
        Err(reason) => { $panic(reason); },
    };
    if encoded.len() != 15 || encoded[14] != 30 { $panic("wrong packet output"); }
    $println("RTP: PASS");
}

rtpDepacketize owns its input and returns an owning payload. It checks RTP version, header length, CSRCs, padding and extension length. Basic rtpSerializePacket accepts packets without extensions/padding; dedicated serializers supply MID, RID, transport-wide sequence numbers and padding. Setting a header flag alone does not generate that field's wire bytes.

Packetize encoded media ​

newRtpSession(payloadType, clockRate) creates sequence, SSRC and timestamp state. Use the payload type and clock rate negotiated in SDP. The following function fragment wraps an already encoded Opus packet:

vex
import { RtpSession, rtpTimestampFromPtsNs,
         rtpPacketizeOpus, rtpSerializePacket } from "webrtc/rtp";

fn wrapOpus(session: &RtpSession!, encoded: Vec<u8>, ptsNs: i64): Result<Vec<u8>, string> {
    let timestamp = rtpTimestampFromPtsNs(session, ptsNs)?;
    let packet = rtpPacketizeOpus(session, encoded, false, timestamp, 1200)?;
    return rtpSerializePacket(&packet);
}

The 1200-byte argument is a chosen RTP payload budget, not the whole transport MTU. Account for RTP extensions, protection and network headers. Opus packetization does not fragment a frame: oversized input is an error. H.264 provides single-NAL, STAP-A and Annex-B/FU-A paths. Its receivers return encoded NAL access units; Opus receivers return encoded packets. A separate codec converts them into media tensors.

Packet reordering, loss decisions and playout are explicit. Receiver constructors accept a reorder-window budget. Playout pipelines add queue capacity and target delay; caller-clock methods release due encoded frames. Supply nanosecond presentation/arrival times only where the signature requests them. RTP media timestamps use clockRate, wrap at 32 bits, and are not Unix timestamps.

Protocol map ​

LayerMain operations and responsibilities
SDPparseSdp, codec/header-extension/RID/simulcast parsers, generation and direction negotiation
ICELocal/remote credentials, candidate parsing/pairs, connectivity checks, nomination and consent
STUN/TURNBounded message builders/parsers, integrity checks, transaction matching, permissions/channel leases
RTP receptionMID/payload-type/SSRC gates, reorder queues, H.264 reassembly and Opus delivery
RTCPSender/receiver reports, NACK, PLI/FIR, transport feedback, reception statistics and clock anchoring
RetransmissionExact serialized-packet cache and negotiated RTX mappings
CongestionExplicit feedback observation, pacing allowance and commit operations
ProtectionSRTP/SRTCP packet protection, authentication, rollover state and replay windows
SCTPAssociation/chunk processing, outbound peek/commit, retransmission and data-channel state
Peer orchestrationOffer/answer, receive-only media requests, UDP transport, timer and datagram routing

RTP reassembly bounds include a 4 MiB H.264 NAL limit, 16 MiB access-unit byte limit, and separate NAL/packet-count caps. These are memory limits, not MTU recommendations. Keep an application budget for concurrent streams and queued frames as well.

Signaling and peer ownership ​

Create a RtcConfig and pass it to newPeerConnection. The application supplies signaling: transport the offer/answer and candidates over your chosen trusted channel. The package does not provide a signaling server. Use createOffer, createReceiveOnlyOffer, setRemoteDescription and createAnswer for their respective roles; preserve media IDs and codec mappings across that exchange.

The peer models one bundled RTP/RTCP transport. ICE credentials, candidates, DTLS fingerprint and media directions are negotiated state, not independent strings to replace after a connection is active. restartIce starts another ICE generation. bindUdpTransport binds an explicit IPv4 interface and nonzero port. Its adapter performs bounded nonblocking UDP I/O; interface discovery and candidate policy remain separate responsibilities.

Drive peer timers and packet routing from your event loop. A check or packet prepared for transmission must be committed only after the corresponding send succeeds. Continue servicing consent, retransmission and close timers even when no application media is being sent. close(&peer!) ends the owned state.

Authentication boundary ​

SDP fingerprint syntax validation is not certificate verification. Match the certificate's SHA-256 fingerprint to the value obtained through authenticated signaling, verify the handshake transcript and Finished, and install the negotiated record/key state before permitting application data. Do not force a public state field to Connected to bypass those steps.

The supplied DTLS path parses records, reassembles handshake fragments and tracks ordering/replay state. It rejects Finished because verification is not implemented, and does not decrypt application records. Consequently these components do not by themselves establish an authenticated browser peer session. dtlsCreateSrtpContexts requires a connected, keyed session; a key derivation helper alone is not proof that a peer is authenticated.

For packet protection, maintain a separate mutable SRTP/SRTCP context for each direction and the negotiated stream identity. Authenticate before committing receive replay state or releasing plaintext. Never use fixed example keys for a real connection, reuse packet indices under a key, or strip protection merely to make RTP parsing succeed. See crypto for key and buffer ownership rules and networking for the lower-level transport APIs.

Released under the MIT License.