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
impl RTCPeerConnection
Sourcepub fn poll_media_read(&mut self) -> Option<TaggedRTCMessage>
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.
Sourcepub fn poll_data_read(&mut self) -> Option<TaggedRTCMessage>
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
impl RTCPeerConnection
Sourcepub fn create_offer(
&mut self,
options: Option<RTCOfferOptions>,
) -> Result<RTCSessionDescription>
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
Sourcepub fn create_answer(
&mut self,
_options: Option<RTCAnswerOptions>,
) -> Result<RTCSessionDescription>
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-offerorhave-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 offerHaveLocalPranswer- 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_rolefrom settings if configured - Defaults to
Client(active) for lower latency - Uses
Server(passive) if remote is ICE-Lite
§Specifications
- W3C RTCPeerConnection.createAnswer
- RFC 8829 Section 5.3 - Generating an Answer
Sourcepub fn set_local_description(
&mut self,
now: Instant,
local_description: RTCSessionDescription,
) -> Result<()>
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 bycreate_offer()orcreate_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:
Stable→HaveLocalOffer - Answer:
HaveRemoteOffer→Stable - Pranswer:
HaveRemoteOffer→HaveLocalPranswer
§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
- W3C RTCPeerConnection.setLocalDescription
- RFC 8829 Section 5.4 - Setting the Session Description
Sourcepub fn local_description(&self) -> Option<RTCSessionDescription>
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
Sourcepub fn current_local_description(&self) -> Option<RTCSessionDescription>
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
Sourcepub fn pending_local_description(&self) -> Option<RTCSessionDescription>
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
Sourcepub fn can_trickle_ice_candidates(&self) -> Option<bool>
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:
Noneif no remote description has been set yet (unknown)Some(true)if the remote peer indicated trickle ICE supportSome(false)if the remote peer did not indicate support
§Specification
Sourcepub fn set_remote_description(
&mut self,
now: Instant,
remote_description: RTCSessionDescription,
) -> Result<()>
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
Sourcepub fn remote_description(&self) -> Option<&RTCSessionDescription>
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
Sourcepub fn current_remote_description(&self) -> Option<&RTCSessionDescription>
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
Sourcepub fn pending_remote_description(&self) -> Option<&RTCSessionDescription>
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
Sourcepub fn add_remote_candidate(
&mut self,
remote_candidate: RTCIceCandidateInit,
) -> Result<()>
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
Sourcepub fn add_local_candidate(
&mut self,
local_candidate: RTCIceCandidateInit,
) -> Result<()>
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”, theurlfield should contain the STUN/TURN server URL used to gather the candidate.
§Errors
Returns an error if the candidate string is invalid.
Sourcepub fn restart_ice(&mut self)
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
Sourcepub fn get_configuration(&self) -> &RTCConfiguration
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
Sourcepub fn set_configuration(
&mut self,
configuration: RTCConfiguration,
) -> Result<()>
pub fn set_configuration( &mut self, configuration: RTCConfiguration, ) -> Result<()>
set_configuration updates the configuration of this PeerConnection object.
Sourcepub fn create_data_channel(
&mut self,
label: &str,
options: Option<RTCDataChannelInit>,
) -> Result<RTCDataChannel<'_>>
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.
Sourcepub fn get_senders(&self) -> impl Iterator<Item = RTCRtpSenderId> + use<'_>
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
Sourcepub fn get_receivers(&self) -> impl Iterator<Item = RTCRtpReceiverId> + use<'_>
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
Sourcepub fn get_transceivers(&self) -> impl Iterator<Item = RTCRtpTransceiverId>
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
Sourcepub fn add_track(&mut self, track: MediaStreamTrack) -> Result<RTCRtpSenderId>
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
Sourcepub fn remove_track(&mut self, sender_id: RTCRtpSenderId) -> Result<()>
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 theRTCRtpSenderto remove.
§Errors
Returns an error if:
- The peer connection is closed
- The sender ID is invalid
§Specification
See removeTrack
Sourcepub fn add_transceiver_from_track(
&mut self,
track: MediaStreamTrack,
init: Option<RTCRtpTransceiverInit>,
) -> Result<RTCRtpTransceiverId>
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
Sourcepub fn add_transceiver_from_kind(
&mut self,
kind: RtpCodecKind,
init: Option<RTCRtpTransceiverInit>,
) -> Result<RTCRtpTransceiverId>
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.
Sourcepub fn data_channel(
&mut self,
id: RTCDataChannelId,
) -> Option<RTCDataChannel<'_>>
pub fn data_channel( &mut self, id: RTCDataChannelId, ) -> Option<RTCDataChannel<'_>>
data_channel provides the access to RTCDataChannel object with the given id
Sourcepub fn sctp(&self) -> Option<RTCSctpTransport<'_>>
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
Sourcepub fn rtp_sender(&mut self, id: RTCRtpSenderId) -> Option<RTCRtpSender<'_>>
pub fn rtp_sender(&mut self, id: RTCRtpSenderId) -> Option<RTCRtpSender<'_>>
rtp_sender provides the access to RTCRtpSender object with the given id
Sourcepub fn rtp_receiver(
&mut self,
id: RTCRtpReceiverId,
) -> Option<RTCRtpReceiver<'_>>
pub fn rtp_receiver( &mut self, id: RTCRtpReceiverId, ) -> Option<RTCRtpReceiver<'_>>
rtp_receiver provides the access to RTCRtpReceiver object with the given id
Sourcepub fn rtp_transceiver(
&mut self,
id: RTCRtpTransceiverId,
) -> Option<RTCRtpTransceiver<'_>>
pub fn rtp_transceiver( &mut self, id: RTCRtpTransceiverId, ) -> Option<RTCRtpTransceiver<'_>>
rtp_transceiver provides the access to RTCRtpTransceiver object with the given id
Sourcepub fn get_stats(
&mut self,
now: Instant,
selector: StatsSelector,
) -> RTCStatsReport
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 connectionStatsSelector::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
Trait Implementations§
Source§impl Protocol<TransportMessage<BytesMut>, TaggedRTCMessage, TaggedRTCEvent> for RTCPeerConnection
impl Protocol<TransportMessage<BytesMut>, TaggedRTCMessage, TaggedRTCEvent> for RTCPeerConnection
Source§type Rout = TaggedRTCMessage
type Rout = TaggedRTCMessage
Source§type Eout = RTCPeerConnectionEvent
type Eout = RTCPeerConnectionEvent
Source§fn handle_read(&mut self, msg: TaggedBytesMut) -> Result<(), Self::Error>
fn handle_read(&mut self, msg: TaggedBytesMut) -> Result<(), Self::Error>
Source§fn handle_write(&mut self, msg: TaggedRTCMessage) -> Result<(), Self::Error>
fn handle_write(&mut self, msg: TaggedRTCMessage) -> Result<(), Self::Error>
Source§fn handle_event(&mut self, evt: TaggedRTCEvent) -> Result<(), Self::Error>
fn handle_event(&mut self, evt: TaggedRTCEvent) -> Result<(), Self::Error>
Auto Trait Implementations§
impl !RefUnwindSafe for RTCPeerConnection
impl !Sync for RTCPeerConnection
impl !UnwindSafe for RTCPeerConnection
impl Freeze for RTCPeerConnection
impl Send for RTCPeerConnection
impl Unpin for RTCPeerConnection
impl UnsafeUnpin for RTCPeerConnection
Blanket Implementations§
Source§impl<T> ArchivePointee for T
impl<T> ArchivePointee for T
Source§type ArchivedMetadata = ()
type ArchivedMetadata = ()
Source§fn pointer_metadata(
_: &<T as ArchivePointee>::ArchivedMetadata,
) -> <T as Pointee>::Metadata
fn pointer_metadata( _: &<T as ArchivePointee>::ArchivedMetadata, ) -> <T as Pointee>::Metadata
Source§impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
Source§impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> LayoutRaw for T
impl<T> LayoutRaw for T
Source§fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutError>
fn layout_raw(_: <T as Pointee>::Metadata) -> Result<Layout, LayoutError>
Source§impl<T, N1, N2> Niching<NichedOption<T, N1>> for N2
impl<T, N1, N2> Niching<NichedOption<T, N1>> for N2
Source§unsafe fn is_niched(niched: *const NichedOption<T, N1>) -> bool
unsafe fn is_niched(niched: *const NichedOption<T, N1>) -> bool
Source§fn resolve_niched(out: Place<NichedOption<T, N1>>)
fn resolve_niched(out: Place<NichedOption<T, N1>>)
out indicating that a T is niched.