Skip to main content

RTCPeerConnection

Struct RTCPeerConnection 

Source
pub struct RTCPeerConnection { /* private fields */ }
Expand description

The RTCPeerConnection interface represents a WebRTC connection between the local computer and a remote peer. It provides methods to connect to a remote peer, maintain and monitor the connection, and close the connection once it’s no longer needed.

This is a sans-I/O implementation following the W3C WebRTC specification.

§Examples

use rtc::peer_connection::RTCPeerConnectionBuilder;

let mut pc = RTCPeerConnectionBuilder::new().build(Instant::now())?;

Implementations§

Source§

impl RTCPeerConnection

Source

pub fn poll_media_read(&mut self) -> Option<TaggedRTCMessage>

Next media (RTP/RTCP) message for the application, if any.

Never affected by data-channel back-pressure. Media arrives over SRTP and is subject to none of SCTP’s flow control, so a caller throttling a slow data-channel consumer must still be able to deliver video — draining this is how.

Source

pub fn poll_data_read(&mut self) -> Option<TaggedRTCMessage>

Next data-channel message for the application, if any.

Declining to call this is how back-pressure is applied. Undrained 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. Stop calling it while the application is behind, resume when it catches up.

Source§

impl RTCPeerConnection

Source

pub fn create_offer( &mut self, options: Option<RTCOfferOptions>, ) -> Result<RTCSessionDescription>

Creates an SDP offer to start a new WebRTC connection to a remote peer.

The offer includes information about the attached media tracks, codecs and options supported by the browser, and ICE candidates gathered by the ICE agent. This offer can be sent to a remote peer over a signaling channel to establish a connection.

§Arguments
  • options - Optional configuration for the offer, such as whether to restart ICE.
§Returns

Returns an RTCSessionDescription containing the SDP offer.

§Errors

Returns an error if:

  • The peer connection is closed
  • There’s an error generating the SDP
§Specification

See createOffer

Source

pub fn create_answer( &mut self, _options: Option<RTCAnswerOptions>, ) -> Result<RTCSessionDescription>

Creates an SDP answer in response to an offer received from a remote peer.

The answer includes information about any media already attached to the session, codecs and options supported by the browser, and ICE candidates gathered by the ICE agent.

§Arguments
  • options - Optional configuration for the answer (currently unused).
§Returns

Returns an RTCSessionDescription containing the SDP answer.

§Errors

Returns an error if:

  • No remote description has been set
  • The peer connection is closed
  • The signaling state is not have-remote-offer or have-local-pranswer
§Specification

See createAnswer Creates an SDP answer in response to an offer from a remote peer.

This method must be called after set_remote_description() has been called with an offer. The answer describes which media formats and codecs this peer will accept and how the connection will be established.

§Parameters
  • options: Optional answer configuration. Currently not used but reserved for future extensions.
§Returns

Returns an RTCSessionDescription containing the SDP answer that should be set as the local description and sent to the remote peer.

§Errors

Returns an error if:

  • No remote description has been set (ErrNoRemoteDescription)
  • The peer connection is closed (ErrConnectionClosed)
  • The signaling state is incorrect (ErrIncorrectSignalingState)
  • SDP generation fails
§Signaling State Requirements

This method can only be called when the signaling state is:

  • HaveRemoteOffer - After receiving an initial offer
  • HaveLocalPranswer - After sending a provisional answer
§Examples
§Basic Answer Flow
use rtc::peer_connection::RTCPeerConnectionBuilder;
use rtc::peer_connection::sdp::RTCSessionDescription;

let mut pc = RTCPeerConnectionBuilder::new().build(Instant::now())?;

// 1. Receive and set remote offer
let offer = RTCSessionDescription::offer(remote_offer_sdp)?;
pc.set_remote_description(Instant::now(), offer)?;

// 2. Create answer
let answer = pc.create_answer(None)?;

// 3. Set as local description
pc.set_local_description(Instant::now(), answer.clone())?;

// 4. Send answer to remote peer
// signaling_channel.send(answer.sdp)?;
§With Media Tracks
use rtc::peer_connection::RTCPeerConnectionBuilder;
use rtc::peer_connection::sdp::RTCSessionDescription;
use rtc::media_stream::MediaStreamTrack;

let mut pc = RTCPeerConnectionBuilder::new().build(Instant::now())?;

// Set remote offer
let offer = RTCSessionDescription::offer(remote_offer_sdp)?;
pc.set_remote_description(Instant::now(), offer)?;

// Add local track before creating answer
pc.add_track(audio_track)?;

// Create answer (will include the track)
let answer = pc.create_answer(None)?;
pc.set_local_description(Instant::now(), answer)?;
§DTLS Role Selection

The answer automatically determines the appropriate DTLS role:

  • Uses answering_dtls_role from settings if configured
  • Defaults to Client (active) for lower latency
  • Uses Server (passive) if remote is ICE-Lite
§Specifications
Source

pub fn set_local_description( &mut self, now: Instant, local_description: RTCSessionDescription, ) -> Result<()>

Sets the local description as part of the offer/answer negotiation.

This changes the local description associated with the connection. If the sdp field is empty, an implicit description will be created based on the type.

§Arguments
  • local_description - The local session description to set.
§Errors

Returns an error if:

  • The peer connection is closed
  • The SDP type is invalid
  • The SDP cannot be parsed
§Specification

See setLocalDescription Sets the local description for this peer connection.

This method applies a local SDP description (offer or answer) to the peer connection, updating the local media and transport configuration. It must be called after creating an offer or answer.

§Parameters
  • local_description: The session description to set as the local description. This should be an offer or answer created by create_offer() or create_answer().
§Returns

Returns Ok(()) on success.

§Errors

Returns an error if:

  • The peer connection is closed (ErrConnectionClosed)
  • The SDP type is invalid for the current signaling state
  • SDP parsing fails
  • Transport configuration fails
§Signaling State Transitions

Setting the local description causes signaling state transitions:

  • Offer: StableHaveLocalOffer
  • Answer: HaveRemoteOfferStable
  • Pranswer: HaveRemoteOfferHaveLocalPranswer
§Examples
§Setting Local Offer
use rtc::peer_connection::RTCPeerConnectionBuilder;

let mut pc = RTCPeerConnectionBuilder::new().build(Instant::now())?;

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

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

// Now send offer.sdp to remote peer via signaling
// signaling_channel.send(offer.sdp)?;
§Setting Local Answer
use rtc::peer_connection::RTCPeerConnectionBuilder;
use rtc::peer_connection::sdp::RTCSessionDescription;

let mut pc = RTCPeerConnectionBuilder::new().build(Instant::now())?;

// Set remote offer first
let offer = RTCSessionDescription::offer(remote_offer_sdp)?;
pc.set_remote_description(Instant::now(), offer)?;

// Create and set local answer
let answer = pc.create_answer(None)?;
pc.set_local_description(Instant::now(), answer.clone())?;

// Send answer to remote peer
// signaling_channel.send(answer.sdp)?;
§Empty SDP Handling (JSEP 5.4)

If the SDP string is empty, the last offer or answer is reused:

  • For offers: Uses the last generated offer
  • For answers: Uses the last generated answer

This allows re-applying descriptions without regenerating SDP.

§Media and Transport Activation

When setting a local answer:

  • RTP transceivers are activated
  • SCTP transport is started for data channels
  • Media can begin flowing
§Specifications
Source

pub fn local_description(&self) -> Option<RTCSessionDescription>

Returns the local session description.

Returns pending_local_description if it is not null, otherwise returns current_local_description. This property is used to determine if set_local_description has already been called.

§Specification

See localDescription

Source

pub fn current_local_description(&self) -> Option<RTCSessionDescription>

Returns the current local description as last successfully negotiated since the last negotiation completed.

This represents the local description from the last offer/answer exchange that was successfully applied, not including any offers currently being negotiated.

Returns None if there is no current local description (e.g., before initial negotiation).

§Specification

See currentLocalDescription

Source

pub fn pending_local_description(&self) -> Option<RTCSessionDescription>

Returns the pending local description if it exists.

This represents the local description from a call to set_local_description() whose corresponding remote description has not yet been applied. This is None if negotiation is not in progress or if a rollback has been performed.

Returns None if there is no pending local description.

§Specification

See pendingLocalDescription

Source

pub fn can_trickle_ice_candidates(&self) -> Option<bool>

Returns whether the remote peer supports trickle ICE.

This value is determined from the remote SDP description after set_remote_description() is called. It checks for “trickle” in the “ice-options” attribute per RFC 8838 and RFC 9429 section 4.1.17.

Returns:

  • None if no remote description has been set yet (unknown)
  • Some(true) if the remote peer indicated trickle ICE support
  • Some(false) if the remote peer did not indicate support
§Specification

See canTrickleIceCandidates

Source

pub fn set_remote_description( &mut self, now: Instant, remote_description: RTCSessionDescription, ) -> Result<()>

Sets the remote description as part of the offer/answer negotiation.

This changes the remote description associated with the connection. This description specifies the properties of the remote end of the connection, including the media format.

§Arguments
  • remote_description - The remote session description to set.
§Errors

Returns an error if:

  • The peer connection is closed
  • The SDP cannot be parsed
  • The media engine fails to update from the remote description
§Specification

See setRemoteDescription

Source

pub fn remote_description(&self) -> Option<&RTCSessionDescription>

Returns the remote session description.

Returns pending_remote_description if it is not null, otherwise returns current_remote_description. This property is used to determine if set_remote_description has already been called.

§Specification

See remoteDescription

Source

pub fn current_remote_description(&self) -> Option<&RTCSessionDescription>

Returns the current remote description as last successfully negotiated since the last negotiation completed.

This represents the remote description from the last offer/answer exchange that was successfully applied, not including any offers currently being negotiated.

Returns None if there is no current remote description (e.g., before initial negotiation).

§Specification

See currentRemoteDescription

Source

pub fn pending_remote_description(&self) -> Option<&RTCSessionDescription>

Returns the pending remote description if it exists.

This represents the remote description from a call to set_remote_description() whose corresponding local description has not yet been applied. This is None if negotiation is not in progress or if a rollback has been performed.

Returns None if there is no pending remote description.

§Specification

See pendingRemoteDescription

Source

pub fn add_remote_candidate( &mut self, remote_candidate: RTCIceCandidateInit, ) -> Result<()>

Adds a remote ICE candidate to the peer connection.

This method provides a remote candidate to the ICE agent. When the remote peer gathers ICE candidates and sends them over the signaling channel, this method should be called to add each candidate.

§Arguments
  • remote_candidate - The ICE candidate initialization data.
§Errors

Returns an error if:

  • No remote description has been set
  • The candidate string is invalid
§Specification

See addIceCandidate

Source

pub fn add_local_candidate( &mut self, local_candidate: RTCIceCandidateInit, ) -> Result<()>

Adds a local ICE candidate to the peer connection.

This method adds a locally gathered ICE candidate. In a typical implementation, local candidates are generated by the ICE agent and passed to this method.

§Arguments
  • local_candidate - The ICE candidate initialization data. For candidates of type “srflx” (server reflexive) or “relay”, the url field should contain the STUN/TURN server URL used to gather the candidate.
§Errors

Returns an error if the candidate string is invalid.

Source

pub fn restart_ice(&mut self)

Tells the peer connection that ICE should be restarted.

This method causes the next call to create_offer to generate an offer that will restart ICE. This is useful when network conditions change or the connection fails.

§Specification

See restartIce

Source

pub fn get_configuration(&self) -> &RTCConfiguration

Returns the current configuration of this peer connection.

The returned reference is to the current configuration. To modify the configuration, use set_configuration.

§Specification

See getConfiguration

Source

pub fn set_configuration( &mut self, configuration: RTCConfiguration, ) -> Result<()>

set_configuration updates the configuration of this PeerConnection object.

Source

pub fn create_data_channel( &mut self, label: &str, options: Option<RTCDataChannelInit>, ) -> Result<RTCDataChannel<'_>>

create_data_channel creates a new DataChannel object with the given label and optional DataChannelInit used to configure properties of the underlying channel such as data reliability.

Source

pub fn get_senders(&self) -> impl Iterator<Item = RTCRtpSenderId> + use<'_>

Returns an iterator over the RTCRtpSender objects.

The RTCRtpSender objects represent the media streams that are being sent to the remote peer.

§Specification

See getSenders

Source

pub fn get_receivers(&self) -> impl Iterator<Item = RTCRtpReceiverId> + use<'_>

Returns an iterator over the RTCRtpReceiver objects.

The RTCRtpReceiver objects represent the media streams that are being received from the remote peer.

§Specification

See getReceivers

Source

pub fn get_transceivers(&self) -> impl Iterator<Item = RTCRtpTransceiverId>

Returns an iterator over the RTCRtpTransceiver objects.

The RTCRtpTransceiver objects represent the combination of an RTCRtpSender and an RTCRtpReceiver that share a common mid.

§Specification

See getTransceivers

Source

pub fn add_track(&mut self, track: MediaStreamTrack) -> Result<RTCRtpSenderId>

Adds a media track to the peer connection.

This method adds a track to the connection, either by finding an existing transceiver that can be reused, or by creating a new transceiver. The track represents media (audio or video) that will be sent to the remote peer.

§Arguments
  • track - The media stream track to add.
§Returns

Returns the ID of the RTCRtpSender that will send this track.

§Errors

Returns an error if the peer connection is closed.

§Specification

See addTrack

Source

pub fn remove_track(&mut self, sender_id: RTCRtpSenderId) -> Result<()>

Removes a track from the peer connection.

This method stops an RTCRtpSender from sending media and marks its transceiver as no longer sending. This will trigger renegotiation.

§Arguments
  • sender_id - The ID of the RTCRtpSender to remove.
§Errors

Returns an error if:

  • The peer connection is closed
  • The sender ID is invalid
§Specification

See removeTrack

Source

pub fn add_transceiver_from_track( &mut self, track: MediaStreamTrack, init: Option<RTCRtpTransceiverInit>, ) -> Result<RTCRtpTransceiverId>

Creates a new RTCRtpTransceiver and adds it to the set of transceivers.

This method creates a transceiver associated with the given track, which can be configured to send, receive, or both.

§Arguments
  • track - The media stream track to associate with the transceiver.
  • init - Optional initialization parameters for the transceiver.
§Returns

Returns the ID of the created transceiver.

§Errors

Returns an error if the peer connection is closed.

§Specification

See addTransceiver

Source

pub fn add_transceiver_from_kind( &mut self, kind: RtpCodecKind, init: Option<RTCRtpTransceiverInit>, ) -> Result<RTCRtpTransceiverId>

add_transceiver_from_kind Create a new RtpTransceiver and adds it to the set of transceivers.

Source

pub fn data_channel( &mut self, id: RTCDataChannelId, ) -> Option<RTCDataChannel<'_>>

data_channel provides the access to RTCDataChannel object with the given id

Source

pub fn sctp(&self) -> Option<RTCSctpTransport<'_>>

The SCTP transport over which data channels are carried.

None until SCTP has been negotiated — that is, until a description establishing an SCTP association has been applied by both sides. A connection carrying only media never has one.

This is the only transport accessor on RTCPeerConnection, matching the W3C interface, which exposes sctp and nothing else. The DTLS and ICE transports are reached by walking from here (or from a sender or receiver):

pc.sctp()?.transport().ice_transport()
§Specifications
Source

pub fn rtp_sender(&mut self, id: RTCRtpSenderId) -> Option<RTCRtpSender<'_>>

rtp_sender provides the access to RTCRtpSender object with the given id

Source

pub fn rtp_receiver( &mut self, id: RTCRtpReceiverId, ) -> Option<RTCRtpReceiver<'_>>

rtp_receiver provides the access to RTCRtpReceiver object with the given id

Source

pub fn rtp_transceiver( &mut self, id: RTCRtpTransceiverId, ) -> Option<RTCRtpTransceiver<'_>>

rtp_transceiver provides the access to RTCRtpTransceiver object with the given id

Source

pub fn get_stats( &mut self, now: Instant, selector: StatsSelector, ) -> RTCStatsReport

Returns a snapshot of accumulated statistics.

This method creates an immutable snapshot of WebRTC statistics at the given timestamp. When selector is StatsSelector::None, the returned RTCStatsReport contains statistics for all aspects of the peer connection. When a sender or receiver is specified, only statistics relevant to that sender/receiver are included.

§Statistics included by selector
  • StatsSelector::None - All statistics for the entire connection
  • StatsSelector::Sender(id) - Outbound RTP streams for the sender and all referenced stats (transport, codec, remote inbound, etc.)
  • StatsSelector::Receiver(id) - Inbound RTP streams for the receiver and all referenced stats (transport, codec, remote outbound, etc.)
§Arguments
  • now - The timestamp to use for all stats in the report. This is passed explicitly to support deterministic testing.
  • selector - Controls which statistics are included in the report.
§Returns

An RTCStatsReport containing snapshots of the selected statistics.

§Example
use std::time::Instant;
use rtc::peer_connection::RTCPeerConnectionBuilder;
use rtc::statistics::StatsSelector;

let mut pc = RTCPeerConnectionBuilder::new().build(Instant::now())?;

// Get all stats
let report = pc.get_stats(Instant::now(), StatsSelector::None);

// Access peer connection stats
if let Some(pc_stats) = report.peer_connection() {
    println!("Data channels opened: {}", pc_stats.data_channels_opened);
}

// Iterate over inbound RTP streams
for stream in report.inbound_rtp_streams() {
    println!("SSRC {}: {} packets received", stream.received_rtp_stream_stats.rtp_stream_stats.ssrc, stream.received_rtp_stream_stats.packets_received);
}
§Specification

See getStats and The stats selection algorithm

Trait Implementations§

Source§

impl Protocol<TransportMessage<BytesMut>, TaggedRTCMessage, TaggedRTCEvent> for RTCPeerConnection

Source§

type Rout = TaggedRTCMessage

Output read message type Read more
Source§

type Wout = TransportMessage<BytesMut>

Output write message type Read more
Source§

type Eout = RTCPeerConnectionEvent

Output event type Read more
Source§

type Error = Error

Error type for protocol operations
Source§

type Time = Instant

Time/Instant type for timeout handling Read more
Source§

fn handle_read(&mut self, msg: TaggedBytesMut) -> Result<(), Self::Error>

Handle an incoming read message. Read more
Source§

fn poll_read(&mut self) -> Option<Self::Rout>

Poll for a processed read message. Read more
Source§

fn handle_write(&mut self, msg: TaggedRTCMessage) -> Result<(), Self::Error>

Handle an outgoing write message. Read more
Source§

fn poll_write(&mut self) -> Option<Self::Wout>

Poll for a processed write message. Read more
Source§

fn handle_event(&mut self, evt: TaggedRTCEvent) -> Result<(), Self::Error>

Handle a custom event. Read more
Source§

fn poll_event(&mut self) -> Option<Self::Eout>

Poll for a generated event. Read more
Source§

fn handle_timeout(&mut self, now: Instant) -> Result<(), Self::Error>

Handle a timeout event. Read more
Source§

fn poll_timeout(&mut self) -> Option<Instant>

Poll for the next timeout deadline. Read more
Source§

fn close(&mut self) -> Result<(), Self::Error>

Close the protocol. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> ArchivePointee for T

Source§

type ArchivedMetadata = ()

The archived version of the pointer metadata for this type.
Source§

fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata, ) -> <T as Pointee>::Metadata

Converts some archived metadata to the pointer metadata for itself.
Source§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

Source§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

Source§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

Source§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> LayoutRaw for T

Source§

fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutError>

Returns the layout of the type.
Source§

impl<T, N1, N2> Niching<NichedOption<T, N1>> for N2
where T: SharedNiching<N1, N2>, N1: Niching<T>, N2: Niching<T>,

Source§

unsafe fn is_niched(niched: *const NichedOption<T, N1>) -> bool

Returns whether the given value has been niched. Read more
Source§

fn resolve_niched(out: Place<NichedOption<T, N1>>)

Writes data to out indicating that a T is niched.
Source§

impl<T> Pointee for T

Source§

type Metadata = ()

The metadata type for pointers and references to this type.
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.