Skip to main content

rtc/peer_connection/
mod.rs

1//! Peer-to-peer connections
2//!
3//! This module implements the `RTCPeerConnection` interface as defined in the
4//! [W3C WebRTC specification](https://w3c.github.io/webrtc-pc/). It provides
5//! the core functionality for establishing peer-to-peer connections, negotiating
6//! media capabilities, and managing data channels.
7//!
8//! # Overview
9//!
10//! `RTCPeerConnection` is the central interface in WebRTC. It handles:
11//!
12//! - **Signaling**: Creating and exchanging SDP offers/answers
13//! - **ICE**: Gathering candidates and establishing connectivity
14//! - **Media**: Managing audio/video tracks and transceivers
15//! - **Data**: Creating and managing data channels
16//! - **Security**: DTLS encryption for all communication
17//!
18//! # Architecture
19//!
20//! This is a **sans-I/O** implementation, meaning it separates protocol logic
21//! from I/O operations. The application is responsible for:
22//!
23//! - Transmitting/receiving network packets
24//! - Managing the event loop
25//! - Handling signaling channel communication
26//!
27//! ## Sans-I/O Benefits
28//!
29//! - **Flexibility**: Keeps protocol logic independent of I/O scheduling; rvoip's
30//!   integration layer uses Tokio
31//! - **Testability**: Protocol logic can be tested without network I/O
32//! - **Control**: Application has full control over threading and scheduling
33//!
34//! # Connection Establishment
35//!
36//! The typical WebRTC connection flow:
37//!
38//! ```text
39//! Peer A (Offerer)              Signaling Server              Peer B (Answerer)
40//! ════════════════              ════════════════              ═══════════════════
41//!      │                               │                               │
42//!      │ 1. create_offer()             │                               │
43//!      │─────────────────┐             │                               │
44//!      │                 │             │                               │
45//!      │<────────────────┘             │                               │
46//!      │                               │                               │
47//!      │ 2. set_local_description()    │                               │
48//!      │─────────────────┐             │                               │
49//!      │                 │             │                               │
50//!      │<────────────────┘             │                               │
51//!      │                               │                               │
52//!      │ 3. send offer (via signaling) │                               │
53//!      │──────────────────────────────>│──────────────────────────────>│
54//!      │                               │                               │
55//!      │                               │  4. set_remote_description()  │
56//!      │                               │                  ┌────────────┤
57//!      │                               │                  │            │
58//!      │                               │                  └───────────>│
59//!      │                               │                               │
60//!      │                               │       5. create_answer()      │
61//!      │                               │                  ┌────────────┤
62//!      │                               │                  │            │
63//!      │                               │                  └───────────>│
64//!      │                               │                               │
65//!      │                               │  6. set_local_description()   │
66//!      │                               │                  ┌────────────┤
67//!      │                               │                  │            │
68//!      │                               │                  └───────────>│
69//!      │                               │                               │
70//!      │ 7. receive answer             │<──────────────────────────────│
71//!      │<──────────────────────────────┤                               │
72//!      │                               │                               │
73//!      │ 8. set_remote_description()   │                               │
74//!      │─────────────────┐             │                               │
75//!      │                 │             │                               │
76//!      │<────────────────┘             │                               │
77//!      │                               │                               │
78//!      │ 9. ICE candidates exchanged   │                               │
79//!      │<─────────────────────────────────────────────────────────────>│
80//!      │                               │                               │
81//!      │ 10. Media/data flows directly │                               │
82//!      │<═════════════════════════════════════════════════════════════>│
83//! ```
84//!
85//! # Examples
86//!
87//! ## Creating a Peer Connection
88//!
89//! ```
90//! use rtc::peer_connection::RTCPeerConnectionBuilder;
91//!
92//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
93//! // Create with default configuration
94//! let mut pc = RTCPeerConnectionBuilder::new().build()?;
95//! # Ok(())
96//! # }
97//! ```
98//!
99//! ## Creating an Offer (Initiating Peer)
100//!
101//! ```no_run
102//! use rtc::peer_connection::RTCPeerConnectionBuilder;
103//!
104//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
105//! let mut pc = RTCPeerConnectionBuilder::new().build()?;
106//!
107//! // Add media track or data channel first
108//! // pc.add_track(audio_track)?;
109//!
110//! // Create offer
111//! let offer = pc.create_offer(None)?;
112//!
113//! // Set as local description
114//! pc.set_local_description(offer.clone())?;
115//!
116//! // Send offer.sdp to remote peer via signaling channel
117//! // signaling_channel.send(offer.sdp)?;
118//! # Ok(())
119//! # }
120//! ```
121//!
122//! ## Answering an Offer (Responding Peer)
123//!
124//! ```no_run
125//! use rtc::peer_connection::RTCPeerConnectionBuilder;
126//! use rtc::peer_connection::sdp::RTCSessionDescription;
127//!
128//! # fn example(remote_offer_sdp: String) -> Result<(), Box<dyn std::error::Error>> {
129//! let mut pc = RTCPeerConnectionBuilder::new().build()?;
130//!
131//! // Receive offer from remote peer
132//! let offer = RTCSessionDescription::offer(remote_offer_sdp)?;
133//!
134//! // Set as remote description
135//! pc.set_remote_description(offer)?;
136//!
137//! // Create answer
138//! let answer = pc.create_answer(None)?;
139//!
140//! // Set as local description
141//! pc.set_local_description(answer.clone())?;
142//!
143//! // Send answer.sdp to remote peer via signaling channel
144//! // signaling_channel.send(answer.sdp)?;
145//! # Ok(())
146//! # }
147//! ```
148//!
149//! ## Adding Media Tracks
150//!
151//! ```no_run
152//! use rtc::peer_connection::RTCPeerConnectionBuilder;
153//! use rtc::media_stream::MediaStreamTrack;
154//! use rtc::rtp_transceiver::rtp_sender::RtpCodecKind;
155//!
156//! # fn example(audio_track: MediaStreamTrack) -> Result<(), Box<dyn std::error::Error>> {
157//! let mut pc = RTCPeerConnectionBuilder::new().build()?;
158//!
159//! // Add an audio track
160//! let sender_id = pc.add_track(audio_track)?;
161//!
162//! // Or add a transceiver for receiving
163//! let transceiver_id = pc.add_transceiver_from_kind(RtpCodecKind::Video, None)?;
164//! # Ok(())
165//! # }
166//! ```
167//!
168//! ## Creating Data Channels
169//!
170//! ```no_run
171//! use rtc::peer_connection::RTCPeerConnectionBuilder;
172//! use rtc::data_channel::RTCDataChannelInit;
173//!
174//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
175//! let mut pc = RTCPeerConnectionBuilder::new().build()?;
176//!
177//! // Create a reliable, ordered data channel
178//! let init = RTCDataChannelInit {
179//!     ordered: true,
180//!     max_retransmits: None,
181//!     ..Default::default()
182//! };
183//!
184//! let channel_id = pc.create_data_channel("my-channel", Some(init))?;
185//! # Ok(())
186//! # }
187//! ```
188//!
189//! ## ICE Candidate Exchange
190//!
191//! ```no_run
192//! use rtc::peer_connection::{RTCPeerConnection, RTCPeerConnectionBuilder};
193//! use rtc::peer_connection::transport::RTCIceCandidateInit;
194//!
195//! # fn example(mut pc: RTCPeerConnection) -> Result<(), Box<dyn std::error::Error>> {
196//! // When local candidates are gathered, send to remote peer
197//! // (In sans-I/O, you'd poll for events to get candidates)
198//!
199//! // When receiving remote candidate from signaling channel
200//! let remote_candidate = RTCIceCandidateInit {
201//!     candidate: "candidate:1 1 UDP 2130706431 192.168.1.100 54321 typ host".to_string(),
202//!     ..Default::default()
203//! };
204//!
205//! pc.add_remote_candidate(remote_candidate)?;
206//! # Ok(())
207//! # }
208//! ```
209//!
210//! # State Management
211//!
212//! The peer connection maintains several state machines:
213//!
214//! - **Signaling State**: SDP negotiation progress (stable, have-local-offer, etc.)
215//! - **ICE Connection State**: Network connectivity status
216//! - **ICE Gathering State**: Candidate gathering progress
217//! - **Connection State**: Overall connection health
218//!
219//! Monitor these states through the event system (sans-I/O polling).
220//!
221//! # Thread Safety
222//!
223//! `RTCPeerConnection` is **not** thread-safe. The application must ensure
224//! exclusive access or use appropriate synchronization primitives.
225//!
226//! # Specifications
227//!
228//! - [W3C WebRTC 1.0] - Main specification
229//! - [RFC 8829] - JSEP: JavaScript Session Establishment Protocol
230//! - [RFC 8866] - SDP: Session Description Protocol
231//! - [RFC 8445] - ICE: Interactive Connectivity Establishment
232//! - [RFC 8831] - WebRTC Data Channels
233//!
234//! [W3C WebRTC 1.0]: https://w3c.github.io/webrtc-pc/
235//! [RFC 8829]: https://datatracker.ietf.org/doc/html/rfc8829
236//! [RFC 8866]: https://datatracker.ietf.org/doc/html/rfc8866
237//! [RFC 8445]: https://datatracker.ietf.org/doc/html/rfc8445
238//! [RFC 8831]: https://datatracker.ietf.org/doc/html/rfc8831
239
240pub mod certificate;
241pub mod configuration;
242pub mod event;
243pub(crate) mod handler;
244mod internal;
245pub mod message;
246pub mod sdp;
247pub mod state;
248pub mod transport;
249
250use crate::data_channel::init::RTCDataChannelInit;
251use crate::data_channel::parameters::DataChannelParameters;
252use crate::data_channel::{RTCDataChannel, RTCDataChannelId, internal::RTCDataChannelInternal};
253use crate::media_stream::track::MediaStreamTrack;
254use crate::peer_connection::configuration::media_engine::MediaEngine;
255use crate::peer_connection::configuration::setting_engine::{SctpMaxMessageSize, SettingEngine};
256use crate::peer_connection::configuration::{
257    RTCConfiguration, RTCIceTransportPolicy,
258    offer_answer_options::{RTCAnswerOptions, RTCOfferOptions},
259};
260use crate::peer_connection::event::RTCPeerConnectionEvent;
261use crate::peer_connection::handler::PipelineContext;
262use crate::peer_connection::handler::dtls::DtlsHandlerContext;
263use crate::peer_connection::handler::ice::IceHandlerContext;
264use crate::peer_connection::handler::sctp::SctpHandlerContext;
265use crate::peer_connection::sdp::session_description::RTCSessionDescription;
266use crate::peer_connection::sdp::{
267    extract_fingerprint, extract_ice_details, get_application_media_section_max_message_size,
268    get_application_media_section_sctp_port, get_mid_value, get_peer_direction,
269    has_ice_trickle_option, is_lite_set, sdp_type::RTCSdpType, update_sdp_origin,
270};
271use crate::peer_connection::state::RTCIceGatheringState;
272use crate::peer_connection::state::ice_connection_state::RTCIceConnectionState;
273use crate::peer_connection::state::peer_connection_state::{
274    NegotiationNeededState, RTCPeerConnectionState,
275};
276use crate::peer_connection::state::signaling_state::{RTCSignalingState, StateChangeOp};
277use crate::peer_connection::transport::dtls::RTCDtlsTransport;
278use crate::peer_connection::transport::dtls::fingerprint::RTCDtlsFingerprint;
279use crate::peer_connection::transport::dtls::parameters::DTLSParameters;
280use crate::peer_connection::transport::dtls::role::{
281    DEFAULT_DTLS_ROLE_ANSWER, DEFAULT_DTLS_ROLE_OFFER, RTCDtlsRole,
282};
283use crate::peer_connection::transport::ice::RTCIceTransport;
284use crate::peer_connection::transport::ice::candidate::RTCIceCandidateInit;
285use crate::peer_connection::transport::ice::parameters::RTCIceParameters;
286use crate::peer_connection::transport::ice::role::RTCIceRole;
287use crate::peer_connection::transport::sctp::RTCSctpTransport;
288use crate::peer_connection::transport::sctp::capabilities::SCTPTransportCapabilities;
289use crate::rtp_transceiver::direction::RTCRtpTransceiverDirection;
290use crate::rtp_transceiver::rtp_receiver::RTCRtpReceiver;
291use crate::rtp_transceiver::rtp_sender::internal::RTCRtpSenderInternal;
292use crate::rtp_transceiver::rtp_sender::rtp_codec::{
293    CodecMatch, RtpCodecKind, encoding_parameters_fuzzy_search,
294};
295use crate::rtp_transceiver::rtp_sender::{
296    RTCRtpCodingParameters, RTCRtpEncodingParameters, RTCRtpSender,
297};
298use crate::rtp_transceiver::{
299    RTCRtpReceiverId, RTCRtpSenderId, RTCRtpTransceiver, RTCRtpTransceiverId,
300    RTCRtpTransceiverInit, internal::RTCRtpTransceiverInternal,
301};
302use crate::statistics::StatsSelector;
303use crate::statistics::accumulator::RTCStatsAccumulator;
304use crate::statistics::report::RTCStatsReport;
305use ::sdp::description::session::Origin;
306use ::sdp::util::ConnectionRole;
307use ice::AgentConfig;
308use ice::candidate::{Candidate, unmarshal_candidate};
309use interceptor::{Interceptor, NoopInterceptor, Registry};
310use sdp::MEDIA_SECTION_APPLICATION;
311use shared::error::{Error, Result};
312use shared::util::math_rand_alpha;
313use std::collections::HashMap;
314use std::time::Instant;
315
316/// Builder for creating RTCPeerConnection instances.
317///
318/// This builder provides a fluent API for configuring peer connections with:
319/// - ICE servers (STUN/TURN) via [`RTCConfiguration`]
320/// - Media codecs and RTP extensions via [`MediaEngine`]
321/// - Low-level transport settings via [`SettingEngine`]
322/// - RTP/RTCP interceptors for NACK, TWCC, and RTCP reports
323///
324/// # Examples
325///
326/// ## Basic peer connection
327///
328/// ```
329/// use rtc::peer_connection::RTCPeerConnectionBuilder;
330///
331/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
332/// let pc = RTCPeerConnectionBuilder::new().build()?;
333/// # Ok(())
334/// # }
335/// ```
336///
337/// ## With ICE servers
338///
339/// ```
340/// use rtc::peer_connection::RTCPeerConnectionBuilder;
341/// use rtc::peer_connection::configuration::{RTCConfigurationBuilder, RTCIceServer};
342///
343/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
344/// let pc = RTCPeerConnectionBuilder::new()
345///     .with_configuration(
346///         RTCConfigurationBuilder::new()
347///             .with_ice_servers(vec![RTCIceServer {
348///                 urls: vec!["stun:stun.l.google.com:19302".to_string()],
349///                 ..Default::default()
350///             }])
351///             .build()
352///     )
353///     .build()?;
354/// # Ok(())
355/// # }
356/// ```
357///
358/// ## With custom media engine
359///
360/// ```
361/// use rtc::peer_connection::RTCPeerConnectionBuilder;
362/// use rtc::peer_connection::configuration::media_engine::MediaEngine;
363///
364/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
365/// let mut media_engine = MediaEngine::default();
366/// media_engine.register_default_codecs()?;
367///
368/// let pc = RTCPeerConnectionBuilder::new()
369///     .with_media_engine(media_engine)
370///     .build()?;
371/// # Ok(())
372/// # }
373/// ```
374///
375/// ## With interceptors
376///
377/// ```
378/// use rtc::peer_connection::RTCPeerConnectionBuilder;
379/// use rtc::peer_connection::configuration::media_engine::MediaEngine;
380/// use rtc::peer_connection::configuration::interceptor_registry::register_default_interceptors;
381/// use rtc::interceptor::Registry;
382///
383/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
384/// let mut media_engine = MediaEngine::default();
385/// let registry = Registry::new();
386/// let registry = register_default_interceptors(registry, &mut media_engine)?;
387///
388/// let pc = RTCPeerConnectionBuilder::new()
389///     .with_media_engine(media_engine)
390///     .with_interceptor_registry(registry)
391///     .build()?;
392/// # Ok(())
393/// # }
394/// ```
395pub struct RTCPeerConnectionBuilder<I = NoopInterceptor>
396where
397    I: Interceptor,
398{
399    configuration: RTCConfiguration,
400    media_engine: MediaEngine,
401    setting_engine: SettingEngine,
402    interceptor: I,
403}
404
405impl Default for RTCPeerConnectionBuilder<NoopInterceptor> {
406    fn default() -> Self {
407        Self {
408            configuration: RTCConfiguration::default(),
409            media_engine: MediaEngine::default(),
410            setting_engine: SettingEngine::default(),
411            interceptor: NoopInterceptor::new(),
412        }
413    }
414}
415
416// Non-generic impl block for associated functions that don't depend on I
417impl RTCPeerConnectionBuilder<NoopInterceptor> {
418    /// Creates a new RTCPeerConnectionBuilder with default configuration.
419    ///
420    /// The default builder includes:
421    /// - Empty ICE server list
422    /// - Default MediaEngine (no codecs registered)
423    /// - Default SettingEngine (standard timeouts and limits)
424    /// - NoopInterceptor (no RTP/RTCP processing)
425    ///
426    /// Use `with_*` methods to customize configuration before calling `build()`.
427    ///
428    /// # Examples
429    ///
430    /// ```
431    /// use rtc::peer_connection::RTCPeerConnectionBuilder;
432    ///
433    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
434    /// let pc = RTCPeerConnectionBuilder::new().build()?;
435    /// # Ok(())
436    /// # }
437    /// ```
438    pub fn new() -> Self {
439        Self::default()
440    }
441}
442
443impl<I> RTCPeerConnectionBuilder<I>
444where
445    I: Interceptor,
446{
447    /// Sets the RTCConfiguration for the peer connection.
448    ///
449    /// The configuration includes ICE servers, transport policies, bundle policies,
450    /// RTCP mux policies, and certificates.
451    ///
452    /// # Examples
453    ///
454    /// ```
455    /// use rtc::peer_connection::RTCPeerConnectionBuilder;
456    /// use rtc::peer_connection::configuration::{RTCConfigurationBuilder, RTCIceServer};
457    ///
458    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
459    /// let config = RTCConfigurationBuilder::new()
460    ///     .with_ice_servers(vec![RTCIceServer {
461    ///         urls: vec!["stun:stun.l.google.com:19302".to_string()],
462    ///         ..Default::default()
463    ///     }])
464    ///     .build();
465    ///
466    /// let pc = RTCPeerConnectionBuilder::new()
467    ///     .with_configuration(config)
468    ///     .build()?;
469    /// # Ok(())
470    /// # }
471    /// ```
472    pub fn with_configuration(mut self, configuration: RTCConfiguration) -> Self {
473        self.configuration = configuration;
474        self
475    }
476
477    /// Sets the MediaEngine for the peer connection.
478    ///
479    /// The media engine configures codecs and RTP header extensions.
480    ///
481    /// # Examples
482    ///
483    /// ```
484    /// use rtc::peer_connection::RTCPeerConnectionBuilder;
485    /// use rtc::peer_connection::configuration::media_engine::MediaEngine;
486    ///
487    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
488    /// let mut media_engine = MediaEngine::default();
489    /// media_engine.register_default_codecs()?;
490    ///
491    /// let pc = RTCPeerConnectionBuilder::new()
492    ///     .with_media_engine(media_engine)
493    ///     .build()?;
494    /// # Ok(())
495    /// # }
496    /// ```
497    pub fn with_media_engine(mut self, media_engine: MediaEngine) -> Self {
498        self.media_engine = media_engine;
499        self
500    }
501
502    /// Sets the SettingEngine for the peer connection.
503    ///
504    /// The setting engine configures low-level transport parameters including
505    /// timeouts, buffer sizes, ICE settings, and SCTP parameters.
506    ///
507    /// # Examples
508    ///
509    /// ```
510    /// use rtc::peer_connection::RTCPeerConnectionBuilder;
511    /// use rtc::peer_connection::configuration::setting_engine::SettingEngine;
512    /// use std::time::Duration;
513    ///
514    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
515    /// let mut setting_engine = SettingEngine::default();
516    /// setting_engine.set_ice_timeouts(
517    ///     Some(Duration::from_secs(30)),
518    ///     Some(Duration::from_secs(60)),
519    ///     Some(Duration::from_millis(100)),
520    /// );
521    ///
522    /// let pc = RTCPeerConnectionBuilder::new()
523    ///     .with_setting_engine(setting_engine)
524    ///     .build()?;
525    /// # Ok(())
526    /// # }
527    /// ```
528    pub fn with_setting_engine(mut self, setting_engine: SettingEngine) -> Self {
529        self.setting_engine = setting_engine;
530        self
531    }
532
533    /// Configures the peer connection with an interceptor registry.
534    ///
535    /// Interceptors process RTP/RTCP packets as they flow through the pipeline,
536    /// enabling features like:
537    /// - NACK (Negative Acknowledgment) for packet loss recovery
538    /// - TWCC (Transport-Wide Congestion Control) for bandwidth estimation
539    /// - RTCP Reports for quality statistics
540    ///
541    /// This method changes the interceptor type from `NoopInterceptor` to the
542    /// registry's interceptor type. It must be the last builder method called
543    /// before `build()` when used.
544    ///
545    /// # Type Parameters
546    ///
547    /// * `P` - The interceptor type produced by the registry
548    ///
549    /// # Examples
550    ///
551    /// ```
552    /// use rtc::peer_connection::RTCPeerConnectionBuilder;
553    /// use rtc::peer_connection::configuration::media_engine::MediaEngine;
554    /// use rtc::peer_connection::configuration::interceptor_registry::register_default_interceptors;
555    /// use rtc::interceptor::Registry;
556    ///
557    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
558    /// let mut media_engine = MediaEngine::default();
559    /// let registry = Registry::new();
560    /// let registry = register_default_interceptors(registry, &mut media_engine)?;
561    ///
562    /// let pc = RTCPeerConnectionBuilder::new()
563    ///     .with_media_engine(media_engine)
564    ///     .with_interceptor_registry(registry)
565    ///     .build()?;
566    /// # Ok(())
567    /// # }
568    /// ```
569    pub fn with_interceptor_registry<P>(
570        self,
571        interceptor_registry: Registry<P>,
572    ) -> RTCPeerConnectionBuilder<P>
573    where
574        P: Interceptor,
575    {
576        RTCPeerConnectionBuilder {
577            configuration: self.configuration,
578            media_engine: self.media_engine,
579            setting_engine: self.setting_engine,
580            interceptor: interceptor_registry.build(),
581        }
582    }
583
584    /// Builds the RTCPeerConnection with the configured settings.
585    ///
586    /// This method validates the configuration and creates a new peer connection.
587    /// If validation fails (e.g., expired certificates, invalid ICE servers),
588    /// an error is returned.
589    ///
590    /// # Errors
591    ///
592    /// Returns an error if:
593    /// - Certificates have expired
594    /// - ICE server URLs are invalid
595    /// - Other validation checks fail
596    ///
597    /// # Examples
598    ///
599    /// ```
600    /// use rtc::peer_connection::RTCPeerConnectionBuilder;
601    ///
602    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
603    /// let pc = RTCPeerConnectionBuilder::new().build()?;
604    /// # Ok(())
605    /// # }
606    /// ```
607    pub fn build(self) -> Result<RTCPeerConnection<I>> {
608        // This fork deliberately compiles rustls with the `ring` provider. Install
609        // it before any DTLS configuration is built so an rvoip-rtc consumer does
610        // not have to perform process-global rustls setup merely to create a peer
611        // connection. If the application already selected a provider, preserve it.
612        let _ = rustls::crypto::ring::default_provider().install_default();
613
614        RTCPeerConnection::new(
615            self.configuration,
616            self.media_engine,
617            self.setting_engine,
618            self.interceptor,
619        )
620    }
621}
622
623/// The `RTCPeerConnection` interface represents a WebRTC connection between the local computer
624/// and a remote peer. It provides methods to connect to a remote peer, maintain and monitor
625/// the connection, and close the connection once it's no longer needed.
626///
627/// This is a sans-I/O implementation following the [W3C WebRTC specification](https://www.w3.org/TR/webrtc/).
628///
629/// # Examples
630///
631/// ```
632/// use rtc::peer_connection::RTCPeerConnectionBuilder;
633///
634/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
635/// let mut pc = RTCPeerConnectionBuilder::new().build()?;
636/// # Ok(())
637/// # }
638/// ```
639pub struct RTCPeerConnection<I = NoopInterceptor>
640where
641    I: Interceptor,
642{
643    //////////////////////////////////////////////////
644    // PeerConnection WebRTC Spec Interface Definition
645    //////////////////////////////////////////////////
646    pub(crate) configuration: RTCConfiguration,
647    pub(crate) media_engine: MediaEngine,
648    pub(crate) setting_engine: SettingEngine,
649    pub(crate) interceptor: I,
650
651    local_description: Option<RTCSessionDescription>,
652    current_local_description: Option<RTCSessionDescription>,
653    pending_local_description: Option<RTCSessionDescription>,
654    remote_description: Option<RTCSessionDescription>,
655    current_remote_description: Option<RTCSessionDescription>,
656    pending_remote_description: Option<RTCSessionDescription>,
657
658    pub(crate) signaling_state: RTCSignalingState,
659    pub(crate) peer_connection_state: RTCPeerConnectionState,
660    can_trickle_ice_candidates: Option<bool>,
661
662    //////////////////////////////////////////////////
663    // PeerConnection Internal State Machine
664    //////////////////////////////////////////////////
665    pub(crate) pipeline_context: PipelineContext,
666    pub(crate) data_channels: HashMap<RTCDataChannelId, RTCDataChannelInternal>,
667    pub(super) rtp_transceivers: Vec<RTCRtpTransceiverInternal<I>>,
668
669    greater_mid: isize,
670    sdp_origin: Origin,
671    last_offer: String,
672    last_answer: String,
673
674    ice_restart_requested: Option<RTCOfferOptions>,
675    negotiation_needed_state: NegotiationNeededState,
676    is_negotiation_ongoing: bool,
677}
678
679impl<I> RTCPeerConnection<I>
680where
681    I: Interceptor,
682{
683    /// Creates an SDP offer to start a new WebRTC connection to a remote peer.
684    ///
685    /// The offer includes information about the attached media tracks, codecs and options supported
686    /// by the browser, and ICE candidates gathered by the ICE agent. This offer can be sent to a
687    /// remote peer over a signaling channel to establish a connection.
688    ///
689    /// # Arguments
690    ///
691    /// * `options` - Optional configuration for the offer, such as whether to restart ICE.
692    ///
693    /// # Returns
694    ///
695    /// Returns an `RTCSessionDescription` containing the SDP offer.
696    ///
697    /// # Errors
698    ///
699    /// Returns an error if:
700    /// - The peer connection is closed
701    /// - There's an error generating the SDP
702    ///
703    /// # Specification
704    ///
705    /// See [createOffer](https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-createoffer)
706    pub fn create_offer(
707        &mut self,
708        mut options: Option<RTCOfferOptions>,
709    ) -> Result<RTCSessionDescription> {
710        if self.peer_connection_state == RTCPeerConnectionState::Closed {
711            return Err(Error::ErrConnectionClosed);
712        }
713
714        let is_ice_restart_requested = self
715            .ice_restart_requested
716            .take()
717            .is_some_and(|options| options.ice_restart)
718            || options.take().is_some_and(|options| options.ice_restart);
719
720        if is_ice_restart_requested {
721            self.ice_restart()?;
722        }
723
724        // include unmatched local transceivers
725        // update the greater mid if the remote description provides a greater one
726        if let Some(d) = self.current_remote_description.as_ref()
727            && let Some(parsed) = &d.parsed
728        {
729            for media in &parsed.media_descriptions {
730                if let Some(mid) = get_mid_value(media) {
731                    if mid.is_empty() {
732                        continue;
733                    }
734                    let numeric_mid = match mid.parse::<isize>() {
735                        Ok(n) => n,
736                        Err(_) => continue,
737                    };
738                    if numeric_mid > self.greater_mid {
739                        self.greater_mid = numeric_mid;
740                    }
741                }
742            }
743        }
744        for transceiver in &mut self.rtp_transceivers {
745            if let Some(mid) = transceiver.mid()
746                && !mid.is_empty()
747            {
748                if let Ok(numeric_mid) = mid.parse::<isize>()
749                    && numeric_mid > self.greater_mid
750                {
751                    self.greater_mid = numeric_mid;
752                }
753            } else {
754                self.greater_mid += 1;
755                transceiver.set_mid(format!("{}", self.greater_mid))?;
756            }
757        }
758
759        let mut d = if self.current_remote_description.is_none() {
760            self.generate_unmatched_sdp()?
761        } else {
762            self.generate_matched_sdp(
763                true, /*includeUnmatched */
764                DEFAULT_DTLS_ROLE_OFFER.to_connection_role(),
765                false,
766            )?
767        };
768
769        update_sdp_origin(&mut self.sdp_origin, &mut d);
770
771        let sdp = d.marshal();
772
773        let offer = RTCSessionDescription {
774            sdp_type: RTCSdpType::Offer,
775            sdp,
776            parsed: Some(d),
777        };
778
779        self.last_offer.clone_from(&offer.sdp);
780
781        Ok(offer)
782    }
783
784    /// Creates an SDP answer in response to an offer received from a remote peer.
785    ///
786    /// The answer includes information about any media already attached to the session,
787    /// codecs and options supported by the browser, and ICE candidates gathered by the ICE agent.
788    ///
789    /// # Arguments
790    ///
791    /// * `options` - Optional configuration for the answer (currently unused).
792    ///
793    /// # Returns
794    ///
795    /// Returns an `RTCSessionDescription` containing the SDP answer.
796    ///
797    /// # Errors
798    ///
799    /// Returns an error if:
800    /// - No remote description has been set
801    /// - The peer connection is closed
802    /// - The signaling state is not `have-remote-offer` or `have-local-pranswer`
803    ///
804    /// # Specification
805    ///
806    /// See [createAnswer](https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-createanswer)
807    /// Creates an SDP answer in response to an offer from a remote peer.
808    ///
809    /// This method must be called after `set_remote_description()` has been called
810    /// with an offer. The answer describes which media formats and codecs this peer
811    /// will accept and how the connection will be established.
812    ///
813    /// # Parameters
814    ///
815    /// - `options`: Optional answer configuration. Currently not used but reserved
816    ///   for future extensions.
817    ///
818    /// # Returns
819    ///
820    /// Returns an `RTCSessionDescription` containing the SDP answer that should be
821    /// set as the local description and sent to the remote peer.
822    ///
823    /// # Errors
824    ///
825    /// Returns an error if:
826    /// - No remote description has been set (`ErrNoRemoteDescription`)
827    /// - The peer connection is closed (`ErrConnectionClosed`)
828    /// - The signaling state is incorrect (`ErrIncorrectSignalingState`)
829    /// - SDP generation fails
830    ///
831    /// # Signaling State Requirements
832    ///
833    /// This method can only be called when the signaling state is:
834    /// - `HaveRemoteOffer` - After receiving an initial offer
835    /// - `HaveLocalPranswer` - After sending a provisional answer
836    ///
837    /// # Examples
838    ///
839    /// ## Basic Answer Flow
840    ///
841    /// ```no_run
842    /// use rtc::peer_connection::RTCPeerConnectionBuilder;
843    /// use rtc::peer_connection::sdp::RTCSessionDescription;
844    ///
845    /// # fn example(remote_offer_sdp: String) -> Result<(), Box<dyn std::error::Error>> {
846    /// let mut pc = RTCPeerConnectionBuilder::new().build()?;
847    ///
848    /// // 1. Receive and set remote offer
849    /// let offer = RTCSessionDescription::offer(remote_offer_sdp)?;
850    /// pc.set_remote_description(offer)?;
851    ///
852    /// // 2. Create answer
853    /// let answer = pc.create_answer(None)?;
854    ///
855    /// // 3. Set as local description
856    /// pc.set_local_description(answer.clone())?;
857    ///
858    /// // 4. Send answer to remote peer
859    /// // signaling_channel.send(answer.sdp)?;
860    /// # Ok(())
861    /// # }
862    /// ```
863    ///
864    /// ## With Media Tracks
865    ///
866    /// ```no_run
867    /// use rtc::peer_connection::RTCPeerConnectionBuilder;
868    /// use rtc::peer_connection::sdp::RTCSessionDescription;
869    /// use rtc::media_stream::MediaStreamTrack;
870    ///
871    /// # fn example(
872    /// #     remote_offer_sdp: String,
873    /// #     audio_track: MediaStreamTrack,
874    /// # ) -> Result<(), Box<dyn std::error::Error>> {
875    /// let mut pc = RTCPeerConnectionBuilder::new().build()?;
876    ///
877    /// // Set remote offer
878    /// let offer = RTCSessionDescription::offer(remote_offer_sdp)?;
879    /// pc.set_remote_description(offer)?;
880    ///
881    /// // Add local track before creating answer
882    /// pc.add_track(audio_track)?;
883    ///
884    /// // Create answer (will include the track)
885    /// let answer = pc.create_answer(None)?;
886    /// pc.set_local_description(answer)?;
887    /// # Ok(())
888    /// # }
889    /// ```
890    ///
891    /// # DTLS Role Selection
892    ///
893    /// The answer automatically determines the appropriate DTLS role:
894    /// - Uses `answering_dtls_role` from settings if configured
895    /// - Defaults to `Client` (active) for lower latency
896    /// - Uses `Server` (passive) if remote is ICE-Lite
897    ///
898    /// # Specifications
899    ///
900    /// - [W3C RTCPeerConnection.createAnswer]
901    /// - [RFC 8829 Section 5.3] - Generating an Answer
902    ///
903    /// [W3C RTCPeerConnection.createAnswer]: https://w3c.github.io/webrtc-pc/#dom-rtcpeerconnection-createanswer
904    /// [RFC 8829 Section 5.3]: https://datatracker.ietf.org/doc/html/rfc8829#section-5.3
905    pub fn create_answer(
906        &mut self,
907        _options: Option<RTCAnswerOptions>,
908    ) -> Result<RTCSessionDescription> {
909        if self.remote_description().is_none() {
910            return Err(Error::ErrNoRemoteDescription);
911        }
912
913        if self.peer_connection_state == RTCPeerConnectionState::Closed {
914            return Err(Error::ErrConnectionClosed);
915        }
916
917        if self.signaling_state != RTCSignalingState::HaveRemoteOffer
918            && self.signaling_state != RTCSignalingState::HaveLocalPranswer
919        {
920            return Err(Error::ErrIncorrectSignalingState);
921        }
922
923        let mut connection_role = self.setting_engine.answering_dtls_role.to_connection_role();
924        if connection_role == ConnectionRole::Unspecified {
925            connection_role = DEFAULT_DTLS_ROLE_ANSWER.to_connection_role();
926
927            if let Some(remote_description) = self.remote_description()
928                && let Some(parsed) = remote_description.parsed.as_ref()
929                && is_lite_set(parsed)
930                && !self.setting_engine.candidates.ice_lite
931            {
932                connection_role = RTCDtlsRole::Server.to_connection_role();
933            }
934        }
935
936        let mut d = self.generate_matched_sdp(
937            false, /*includeUnmatched */
938            connection_role,
939            self.setting_engine.ignore_rid_pause_for_recv,
940        )?;
941
942        update_sdp_origin(&mut self.sdp_origin, &mut d);
943
944        let sdp = d.marshal();
945
946        let answer = RTCSessionDescription {
947            sdp_type: RTCSdpType::Answer,
948            sdp,
949            parsed: Some(d),
950        };
951
952        self.last_answer.clone_from(&answer.sdp);
953
954        Ok(answer)
955    }
956
957    /// Sets the local description as part of the offer/answer negotiation.
958    ///
959    /// This changes the local description associated with the connection. If the `sdp` field
960    /// is empty, an implicit description will be created based on the type.
961    ///
962    /// # Arguments
963    ///
964    /// * `local_description` - The local session description to set.
965    ///
966    /// # Errors
967    ///
968    /// Returns an error if:
969    /// - The peer connection is closed
970    /// - The SDP type is invalid
971    /// - The SDP cannot be parsed
972    ///
973    /// # Specification
974    ///
975    /// See [setLocalDescription](https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-setlocaldescription)
976    /// Sets the local description for this peer connection.
977    ///
978    /// This method applies a local SDP description (offer or answer) to the peer
979    /// connection, updating the local media and transport configuration. It must be
980    /// called after creating an offer or answer.
981    ///
982    /// # Parameters
983    ///
984    /// - `local_description`: The session description to set as the local description.
985    ///   This should be an offer or answer created by `create_offer()` or `create_answer()`.
986    ///
987    /// # Returns
988    ///
989    /// Returns `Ok(())` on success.
990    ///
991    /// # Errors
992    ///
993    /// Returns an error if:
994    /// - The peer connection is closed (`ErrConnectionClosed`)
995    /// - The SDP type is invalid for the current signaling state
996    /// - SDP parsing fails
997    /// - Transport configuration fails
998    ///
999    /// # Signaling State Transitions
1000    ///
1001    /// Setting the local description causes signaling state transitions:
1002    ///
1003    /// - **Offer**: `Stable` → `HaveLocalOffer`
1004    /// - **Answer**: `HaveRemoteOffer` → `Stable`
1005    /// - **Pranswer**: `HaveRemoteOffer` → `HaveLocalPranswer`
1006    ///
1007    /// # Examples
1008    ///
1009    /// ## Setting Local Offer
1010    ///
1011    /// ```no_run
1012    /// use rtc::peer_connection::RTCPeerConnectionBuilder;
1013    ///
1014    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
1015    /// let mut pc = RTCPeerConnectionBuilder::new().build()?;
1016    ///
1017    /// // Create offer
1018    /// let offer = pc.create_offer(None)?;
1019    ///
1020    /// // Set as local description
1021    /// pc.set_local_description(offer.clone())?;
1022    ///
1023    /// // Now send offer.sdp to remote peer via signaling
1024    /// // signaling_channel.send(offer.sdp)?;
1025    /// # Ok(())
1026    /// # }
1027    /// ```
1028    ///
1029    /// ## Setting Local Answer
1030    ///
1031    /// ```no_run
1032    /// use rtc::peer_connection::RTCPeerConnectionBuilder;
1033    /// use rtc::peer_connection::sdp::RTCSessionDescription;
1034    ///
1035    /// # fn example(remote_offer_sdp: String) -> Result<(), Box<dyn std::error::Error>> {
1036    /// let mut pc = RTCPeerConnectionBuilder::new().build()?;
1037    ///
1038    /// // Set remote offer first
1039    /// let offer = RTCSessionDescription::offer(remote_offer_sdp)?;
1040    /// pc.set_remote_description(offer)?;
1041    ///
1042    /// // Create and set local answer
1043    /// let answer = pc.create_answer(None)?;
1044    /// pc.set_local_description(answer.clone())?;
1045    ///
1046    /// // Send answer to remote peer
1047    /// // signaling_channel.send(answer.sdp)?;
1048    /// # Ok(())
1049    /// # }
1050    /// ```
1051    ///
1052    /// # Empty SDP Handling (JSEP 5.4)
1053    ///
1054    /// If the SDP string is empty, the last offer or answer is reused:
1055    /// - For offers: Uses the last generated offer
1056    /// - For answers: Uses the last generated answer
1057    ///
1058    /// This allows re-applying descriptions without regenerating SDP.
1059    ///
1060    /// # Media and Transport Activation
1061    ///
1062    /// When setting a local answer:
1063    /// - RTP transceivers are activated
1064    /// - SCTP transport is started for data channels
1065    /// - Media can begin flowing
1066    ///
1067    /// # Specifications
1068    ///
1069    /// - [W3C RTCPeerConnection.setLocalDescription]
1070    /// - [RFC 8829 Section 5.4] - Setting the Session Description
1071    ///
1072    /// [W3C RTCPeerConnection.setLocalDescription]: https://w3c.github.io/webrtc-pc/#dom-peerconnection-setlocaldescription
1073    /// [RFC 8829 Section 5.4]: https://datatracker.ietf.org/doc/html/rfc8829#section-5.4
1074    pub fn set_local_description(
1075        &mut self,
1076        mut local_description: RTCSessionDescription,
1077    ) -> Result<()> {
1078        if self.peer_connection_state == RTCPeerConnectionState::Closed {
1079            return Err(Error::ErrConnectionClosed);
1080        }
1081
1082        // JSEP 5.4
1083        if local_description.sdp.is_empty() {
1084            match local_description.sdp_type {
1085                RTCSdpType::Answer | RTCSdpType::Pranswer => {
1086                    local_description.sdp.clone_from(&self.last_answer);
1087                }
1088                RTCSdpType::Offer => {
1089                    local_description.sdp.clone_from(&self.last_offer);
1090                }
1091                RTCSdpType::Rollback => {
1092                    // WebRTC spec: rollback SDP is ignored, empty is allowed
1093                }
1094                _ => return Err(Error::ErrPeerConnSDPTypeInvalidValueSetLocalDescription),
1095            }
1096        }
1097
1098        // Parse SDP (skip for rollback as content is ignored per spec)
1099        if local_description.sdp_type != RTCSdpType::Rollback {
1100            local_description.parsed = Some(local_description.unmarshal()?);
1101        }
1102        self.set_description(&local_description, StateChangeOp::SetLocal)?;
1103
1104        let we_answer = local_description.sdp_type == RTCSdpType::Answer;
1105        if we_answer && let Some(parsed_local_description) = &local_description.parsed {
1106            // WebRTC Spec 1.0 https://www.w3.org/TR/webrtc/
1107            // Section 4.4.1.5
1108            for media in &parsed_local_description.media_descriptions {
1109                let mid_value = match get_mid_value(media) {
1110                    Some(mid) if !mid.is_empty() => mid,
1111                    _ => return Err(Error::ErrPeerConnLocalDescriptionWithoutMidValue),
1112                };
1113
1114                if media.media_name.media == MEDIA_SECTION_APPLICATION {
1115                    continue;
1116                }
1117
1118                let i = match RTCPeerConnection::find_by_mid(mid_value, &self.rtp_transceivers) {
1119                    Some(i) => i,
1120                    None => return Err(Error::ErrPeerConnTransceiverMidNil),
1121                };
1122
1123                let kind = RtpCodecKind::from(media.media_name.media.as_str());
1124                let mut direction = get_peer_direction(media);
1125                if kind == RtpCodecKind::Unspecified
1126                    || direction == RTCRtpTransceiverDirection::Unspecified
1127                {
1128                    continue;
1129                }
1130
1131                // If a transceiver is created by applying a remote description that has recvonly transceiver,
1132                // it will have no sender. In this case, the transceiver's current direction is set to inactive so
1133                // that the transceiver can be reused by next AddTrack.
1134                if direction == RTCRtpTransceiverDirection::Sendonly
1135                    && self.rtp_transceivers[i].sender().is_none()
1136                {
1137                    direction = RTCRtpTransceiverDirection::Inactive;
1138                }
1139
1140                self.rtp_transceivers[i].set_current_direction(direction);
1141            }
1142
1143            if let Some(remote_description) = self.remote_description().cloned()
1144                && let Some(parsed_remote_description) = remote_description.parsed.as_ref()
1145            {
1146                let (dtls_role, remote_caps, local_sctp_port, remote_sctp_port) = (
1147                    self.dtls_transport().role(),
1148                    SCTPTransportCapabilities {
1149                        max_message_size: get_application_media_section_max_message_size(
1150                            parsed_remote_description,
1151                        )
1152                        .unwrap_or(SctpMaxMessageSize::DEFAULT_MESSAGE_SIZE),
1153                    },
1154                    get_application_media_section_sctp_port(parsed_local_description)
1155                        .unwrap_or(5000),
1156                    get_application_media_section_sctp_port(parsed_remote_description)
1157                        .unwrap_or(5000),
1158                );
1159
1160                // we_answer: we first call set_remote_description,
1161                // then, we create_answer() and set_local_description() here
1162                // Now we should have done SDP negotiation.
1163                // Therefore, it is ready to start sctp and rtp.
1164                self.sctp_transport_mut().start(
1165                    dtls_role,
1166                    remote_caps,
1167                    local_sctp_port,
1168                    remote_sctp_port,
1169                )?;
1170                self.start_rtp(remote_description)?;
1171            }
1172        }
1173
1174        self.ice_transport_mut().ice_gathering_state = RTCIceGatheringState::Gathering;
1175
1176        Ok(())
1177    }
1178
1179    /// Returns the local session description.
1180    ///
1181    /// Returns `pending_local_description` if it is not null, otherwise returns
1182    /// `current_local_description`. This property is used to determine if
1183    /// `set_local_description` has already been called.
1184    ///
1185    /// # Specification
1186    ///
1187    /// See [localDescription](https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-localdescription)
1188    pub fn local_description(&self) -> Option<RTCSessionDescription> {
1189        if let Some(pending_local_description) = self.pending_local_description() {
1190            return Some(pending_local_description);
1191        }
1192        self.current_local_description()
1193    }
1194
1195    /// Returns the current local description as last successfully negotiated since
1196    /// the last negotiation completed.
1197    ///
1198    /// This represents the local description from the last offer/answer exchange that was
1199    /// successfully applied, not including any offers currently being negotiated.
1200    ///
1201    /// Returns `None` if there is no current local description (e.g., before initial negotiation).
1202    ///
1203    /// # Specification
1204    ///
1205    /// See [currentLocalDescription](https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-currentlocaldescription)
1206    pub fn current_local_description(&self) -> Option<RTCSessionDescription> {
1207        self.populate_local_candidates(self.current_local_description.as_ref())
1208    }
1209
1210    /// Returns the pending local description if it exists.
1211    ///
1212    /// This represents the local description from a call to `set_local_description()` whose
1213    /// corresponding remote description has not yet been applied. This is `None` if negotiation
1214    /// is not in progress or if a rollback has been performed.
1215    ///
1216    /// Returns `None` if there is no pending local description.
1217    ///
1218    /// # Specification
1219    ///
1220    /// See [pendingLocalDescription](https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-pendinglocaldescription)
1221    pub fn pending_local_description(&self) -> Option<RTCSessionDescription> {
1222        self.populate_local_candidates(self.pending_local_description.as_ref())
1223    }
1224
1225    /// Returns whether the remote peer supports trickle ICE.
1226    ///
1227    /// This value is determined from the remote SDP description after `set_remote_description()`
1228    /// is called. It checks for "trickle" in the "ice-options" attribute per
1229    /// RFC 8838 and RFC 9429 section 4.1.17.
1230    ///
1231    /// Returns:
1232    /// - `None` if no remote description has been set yet (unknown)
1233    /// - `Some(true)` if the remote peer indicated trickle ICE support
1234    /// - `Some(false)` if the remote peer did not indicate support
1235    ///
1236    /// # Specification
1237    ///
1238    /// See [canTrickleIceCandidates](https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-cantrickleicecandidates)
1239    pub fn can_trickle_ice_candidates(&self) -> Option<bool> {
1240        self.can_trickle_ice_candidates
1241    }
1242
1243    /// Sets the remote description as part of the offer/answer negotiation.
1244    ///
1245    /// This changes the remote description associated with the connection. This description
1246    /// specifies the properties of the remote end of the connection, including the media format.
1247    ///
1248    /// # Arguments
1249    ///
1250    /// * `remote_description` - The remote session description to set.
1251    ///
1252    /// # Errors
1253    ///
1254    /// Returns an error if:
1255    /// - The peer connection is closed
1256    /// - The SDP cannot be parsed
1257    /// - The media engine fails to update from the remote description
1258    ///
1259    /// # Specification
1260    ///
1261    /// See [setRemoteDescription](https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-setremotedescription)
1262    pub fn set_remote_description(
1263        &mut self,
1264        mut remote_description: RTCSessionDescription,
1265    ) -> Result<()> {
1266        if self.peer_connection_state == RTCPeerConnectionState::Closed {
1267            return Err(Error::ErrConnectionClosed);
1268        }
1269
1270        let is_renegotiation = self.current_remote_description.is_some();
1271
1272        // Parse SDP (skip for rollback as content is ignored per spec)
1273        if remote_description.sdp_type != RTCSdpType::Rollback {
1274            remote_description.parsed = Some(remote_description.unmarshal()?);
1275        }
1276        self.set_description(&remote_description, StateChangeOp::SetRemote)?;
1277
1278        if let Some(parsed_remote_description) = &remote_description.parsed {
1279            self.media_engine
1280                .update_from_remote_description(parsed_remote_description)?;
1281
1282            // Detect trickle ICE support from remote SDP (RFC 8838/RFC 9429 section 4.1.17)
1283            // Check for "trickle" in space-separated "ice-options" attribute values
1284            let has_trickle_ice = has_ice_trickle_option(parsed_remote_description);
1285
1286            match remote_description.sdp_type {
1287                RTCSdpType::Offer | RTCSdpType::Answer | RTCSdpType::Pranswer => {
1288                    self.can_trickle_ice_candidates = Some(has_trickle_ice);
1289                }
1290                _ => {
1291                    // Rollback or other types: reset to unknown
1292                    self.can_trickle_ice_candidates = None;
1293                }
1294            }
1295
1296            // Disable RTX/FEC on RTPSenders if the remote didn't support it
1297            for transceiver in &mut self.rtp_transceivers {
1298                if let Some(sender) = transceiver.sender_mut() {
1299                    let (is_rtx_enabled, is_fec_enabled) = (
1300                        self.media_engine
1301                            .is_rtx_enabled(sender.kind(), RTCRtpTransceiverDirection::Sendonly),
1302                        self.media_engine
1303                            .is_fec_enabled(sender.kind(), RTCRtpTransceiverDirection::Sendonly),
1304                    );
1305                    sender.configure_rtx_and_fec(is_rtx_enabled, is_fec_enabled);
1306                }
1307            }
1308
1309            let we_offer = remote_description.sdp_type == RTCSdpType::Answer;
1310
1311            // Extract media descriptions to avoid borrowing conflicts
1312            let media_descriptions = self
1313                .remote_description()
1314                .as_ref()
1315                .and_then(|r| r.parsed.as_ref())
1316                .map(|parsed| parsed.media_descriptions.clone());
1317
1318            if let Some(media_descriptions) = media_descriptions {
1319                if !we_offer {
1320                    for media in &media_descriptions {
1321                        let mid_value = match get_mid_value(media) {
1322                            Some(mid) if !mid.is_empty() => mid,
1323                            _ => return Err(Error::ErrPeerConnRemoteDescriptionWithoutMidValue),
1324                        };
1325
1326                        if media.media_name.media == MEDIA_SECTION_APPLICATION {
1327                            continue;
1328                        }
1329
1330                        let kind = RtpCodecKind::from(media.media_name.media.as_str());
1331                        let direction = get_peer_direction(media);
1332                        if kind == RtpCodecKind::Unspecified
1333                            || direction == RTCRtpTransceiverDirection::Unspecified
1334                        {
1335                            continue;
1336                        }
1337
1338                        let transceiver = if let Some(i) =
1339                            RTCPeerConnection::find_by_mid(mid_value, &self.rtp_transceivers)
1340                        {
1341                            if direction == RTCRtpTransceiverDirection::Inactive {
1342                                self.rtp_transceivers[i]
1343                                    .stop(&self.media_engine, &mut self.interceptor)?;
1344                            }
1345                            Some(&mut self.rtp_transceivers[i])
1346                        } else {
1347                            RTCPeerConnection::satisfy_type_and_direction(
1348                                kind,
1349                                direction,
1350                                &mut self.rtp_transceivers,
1351                            )
1352                        };
1353
1354                        if let Some(transceiver) = transceiver {
1355                            if direction == RTCRtpTransceiverDirection::Recvonly {
1356                                if transceiver.direction() == RTCRtpTransceiverDirection::Sendrecv {
1357                                    transceiver.set_direction(RTCRtpTransceiverDirection::Sendonly);
1358                                } else if transceiver.direction()
1359                                    == RTCRtpTransceiverDirection::Recvonly
1360                                {
1361                                    transceiver.set_direction(RTCRtpTransceiverDirection::Inactive);
1362                                }
1363                            } else if direction == RTCRtpTransceiverDirection::Sendrecv {
1364                                if transceiver.direction() == RTCRtpTransceiverDirection::Sendonly {
1365                                    transceiver.set_direction(RTCRtpTransceiverDirection::Sendrecv);
1366                                } else if transceiver.direction()
1367                                    == RTCRtpTransceiverDirection::Inactive
1368                                {
1369                                    transceiver.set_direction(RTCRtpTransceiverDirection::Recvonly);
1370                                }
1371                            } else if direction == RTCRtpTransceiverDirection::Sendonly
1372                                && transceiver.direction() == RTCRtpTransceiverDirection::Inactive
1373                            {
1374                                transceiver.set_direction(RTCRtpTransceiverDirection::Recvonly);
1375                            }
1376
1377                            transceiver.set_codec_preferences_from_remote_description(
1378                                media,
1379                                &self.media_engine,
1380                            )?;
1381
1382                            if transceiver.mid().is_none() {
1383                                transceiver.set_mid(mid_value.to_string())?;
1384                            }
1385                        } else {
1386                            let local_direction =
1387                                if direction == RTCRtpTransceiverDirection::Recvonly {
1388                                    RTCRtpTransceiverDirection::Sendonly
1389                                } else {
1390                                    RTCRtpTransceiverDirection::Recvonly
1391                                };
1392
1393                            let mut transceiver = RTCRtpTransceiverInternal::new(
1394                                kind,
1395                                None,
1396                                RTCRtpTransceiverInit {
1397                                    direction: local_direction,
1398                                    streams: vec![],
1399                                    send_encodings: vec![],
1400                                },
1401                            );
1402
1403                            transceiver.set_codec_preferences_from_remote_description(
1404                                media,
1405                                &self.media_engine,
1406                            )?;
1407
1408                            if transceiver.mid().is_none() {
1409                                transceiver.set_mid(mid_value.to_string())?;
1410                            }
1411
1412                            self.add_rtp_transceiver(transceiver);
1413                        }
1414                    }
1415                } else {
1416                    // we_offer
1417                    // WebRTC Spec 1.0 https://www.w3.org/TR/webrtc/
1418                    // 4.5.9.2
1419                    // This is an answer from the remote.
1420                    for media in &media_descriptions {
1421                        let mid_value = match get_mid_value(media) {
1422                            Some(mid) if !mid.is_empty() => mid,
1423                            _ => return Err(Error::ErrPeerConnRemoteDescriptionWithoutMidValue),
1424                        };
1425
1426                        if media.media_name.media == MEDIA_SECTION_APPLICATION {
1427                            continue;
1428                        }
1429
1430                        let kind = RtpCodecKind::from(media.media_name.media.as_str());
1431                        let mut direction = get_peer_direction(media);
1432                        if kind == RtpCodecKind::Unspecified
1433                            || direction == RTCRtpTransceiverDirection::Unspecified
1434                        {
1435                            continue;
1436                        }
1437
1438                        let transceiver = if let Some(i) =
1439                            RTCPeerConnection::find_by_mid(mid_value, &self.rtp_transceivers)
1440                        {
1441                            &mut self.rtp_transceivers[i]
1442                        } else {
1443                            return Err(Error::ErrPeerConnTransceiverMidNil);
1444                        };
1445
1446                        // reverse direction if it was a remote answer
1447                        if direction == RTCRtpTransceiverDirection::Sendonly {
1448                            direction = RTCRtpTransceiverDirection::Recvonly;
1449                        } else if direction == RTCRtpTransceiverDirection::Recvonly {
1450                            direction = RTCRtpTransceiverDirection::Sendonly;
1451                        }
1452
1453                        transceiver.set_current_direction(direction);
1454
1455                        transceiver.set_codec_preferences_from_remote_description(
1456                            media,
1457                            &self.media_engine,
1458                        )?;
1459                    }
1460                }
1461            }
1462
1463            let (remote_ufrag, remote_pwd, candidates) =
1464                extract_ice_details(parsed_remote_description)?;
1465
1466            if is_renegotiation
1467                && self
1468                    .ice_transport()
1469                    .have_remote_credentials_change(&remote_ufrag, &remote_pwd)
1470            {
1471                // An ICE Restart only happens implicitly for a set_remote_description of type offer
1472
1473                if !we_offer {
1474                    // Update stats with new ICE credentials after restart (may have been generated)
1475                    self.ice_restart()?;
1476                }
1477
1478                self.ice_transport_mut()
1479                    .set_remote_credentials(remote_ufrag.clone(), remote_pwd.clone())?;
1480            }
1481
1482            for candidate in candidates {
1483                self.ice_transport_mut().add_remote_candidate(candidate)?;
1484            }
1485
1486            if !is_renegotiation {
1487                let remote_is_lite = is_lite_set(parsed_remote_description);
1488
1489                let (remote_fingerprint, remote_fingerprint_hash) =
1490                    extract_fingerprint(parsed_remote_description)?;
1491
1492                // If one of the agents is lite and the other one is not, the lite agent must be the controlling agent.
1493                // If both or neither agents are lite the offering agent is controlling.
1494                // RFC 8445 S6.1.1
1495                let local_ice_role = if (we_offer
1496                    && remote_is_lite == self.setting_engine.candidates.ice_lite)
1497                    || (remote_is_lite && !self.setting_engine.candidates.ice_lite)
1498                {
1499                    RTCIceRole::Controlling
1500                } else {
1501                    RTCIceRole::Controlled
1502                };
1503
1504                let remote_dtls_role = RTCDtlsRole::from(parsed_remote_description);
1505                log::trace!(
1506                    "start_transports: local_ice_role={local_ice_role}, remote_dtls_role={remote_dtls_role}"
1507                );
1508
1509                self.start_transports(
1510                    local_ice_role,
1511                    RTCIceParameters {
1512                        username_fragment: remote_ufrag,
1513                        password: remote_pwd,
1514                        ice_lite: remote_is_lite,
1515                    },
1516                    DTLSParameters {
1517                        role: remote_dtls_role,
1518                        fingerprints: vec![RTCDtlsFingerprint {
1519                            algorithm: remote_fingerprint_hash,
1520                            value: remote_fingerprint,
1521                        }],
1522                    },
1523                )?;
1524            }
1525
1526            if we_offer
1527                && let Some(parsed_local_description) = self
1528                    .current_local_description
1529                    .as_ref()
1530                    .and_then(|desc| desc.parsed.as_ref())
1531            {
1532                let (dtls_role, remote_caps, local_sctp_port, remote_sctp_port) = (
1533                    self.dtls_transport().role(),
1534                    SCTPTransportCapabilities {
1535                        max_message_size: get_application_media_section_max_message_size(
1536                            parsed_remote_description,
1537                        )
1538                        .unwrap_or(SctpMaxMessageSize::DEFAULT_MESSAGE_SIZE),
1539                    },
1540                    get_application_media_section_sctp_port(parsed_local_description)
1541                        .unwrap_or(5000),
1542                    get_application_media_section_sctp_port(parsed_remote_description)
1543                        .unwrap_or(5000),
1544                );
1545
1546                // we_offer: we create_offer() and set_local_description() first
1547                // then, after call set_remote_description here,
1548                // Now we should have done SDP negotiation.
1549                // Therefore, it is ready to start sctp and rtp.
1550                self.sctp_transport_mut().start(
1551                    dtls_role,
1552                    remote_caps,
1553                    local_sctp_port,
1554                    remote_sctp_port,
1555                )?;
1556                self.start_rtp(remote_description)?;
1557            }
1558        }
1559
1560        Ok(())
1561    }
1562
1563    /// Returns the remote session description.
1564    ///
1565    /// Returns `pending_remote_description` if it is not null, otherwise returns
1566    /// `current_remote_description`. This property is used to determine if
1567    /// `set_remote_description` has already been called.
1568    ///
1569    /// # Specification
1570    ///
1571    /// See [remoteDescription](https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-remotedescription)
1572    pub fn remote_description(&self) -> Option<&RTCSessionDescription> {
1573        if self.pending_remote_description.is_some() {
1574            self.pending_remote_description.as_ref()
1575        } else {
1576            self.current_remote_description.as_ref()
1577        }
1578    }
1579
1580    /// Returns the current remote description as last successfully negotiated since
1581    /// the last negotiation completed.
1582    ///
1583    /// This represents the remote description from the last offer/answer exchange that was
1584    /// successfully applied, not including any offers currently being negotiated.
1585    ///
1586    /// Returns `None` if there is no current remote description (e.g., before initial negotiation).
1587    ///
1588    /// # Specification
1589    ///
1590    /// See [currentRemoteDescription](https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-currentremotedescription)
1591    pub fn current_remote_description(&self) -> Option<&RTCSessionDescription> {
1592        self.current_remote_description.as_ref()
1593    }
1594
1595    /// Returns the pending remote description if it exists.
1596    ///
1597    /// This represents the remote description from a call to `set_remote_description()` whose
1598    /// corresponding local description has not yet been applied. This is `None` if negotiation
1599    /// is not in progress or if a rollback has been performed.
1600    ///
1601    /// Returns `None` if there is no pending remote description.
1602    ///
1603    /// # Specification
1604    ///
1605    /// See [pendingRemoteDescription](https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-pendingremotedescription)
1606    pub fn pending_remote_description(&self) -> Option<&RTCSessionDescription> {
1607        self.pending_remote_description.as_ref()
1608    }
1609
1610    /// Adds a remote ICE candidate to the peer connection.
1611    ///
1612    /// This method provides a remote candidate to the ICE agent. When the remote peer
1613    /// gathers ICE candidates and sends them over the signaling channel, this method
1614    /// should be called to add each candidate.
1615    ///
1616    /// # Arguments
1617    ///
1618    /// * `remote_candidate` - The ICE candidate initialization data.
1619    ///
1620    /// # Errors
1621    ///
1622    /// Returns an error if:
1623    /// - No remote description has been set
1624    /// - The candidate string is invalid
1625    ///
1626    /// # Specification
1627    ///
1628    /// See [addIceCandidate](https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-addicecandidate)
1629    pub fn add_remote_candidate(&mut self, remote_candidate: RTCIceCandidateInit) -> Result<()> {
1630        if self.remote_description().is_none() {
1631            return Err(Error::ErrNoRemoteDescription);
1632        }
1633
1634        let candidate_value = match remote_candidate.candidate.strip_prefix("candidate:") {
1635            Some(s) => s,
1636            None => remote_candidate.candidate.as_str(),
1637        };
1638
1639        if !candidate_value.is_empty() {
1640            self.add_ice_remote_candidate(candidate_value)?;
1641        }
1642
1643        Ok(())
1644    }
1645
1646    /// Adds a local ICE candidate to the peer connection.
1647    ///
1648    /// This method adds a locally gathered ICE candidate. In a typical implementation,
1649    /// local candidates are generated by the ICE agent and passed to this method.
1650    ///
1651    /// # Arguments
1652    ///
1653    /// * `local_candidate` - The ICE candidate initialization data. For candidates of
1654    ///   type "srflx" (server reflexive) or "relay", the `url` field should contain
1655    ///   the STUN/TURN server URL used to gather the candidate.
1656    ///
1657    /// # Errors
1658    ///
1659    /// Returns an error if the candidate string is invalid.
1660    pub fn add_local_candidate(&mut self, local_candidate: RTCIceCandidateInit) -> Result<()> {
1661        let candidate_value = match local_candidate.candidate.strip_prefix("candidate:") {
1662            Some(s) => s,
1663            None => local_candidate.candidate.as_str(),
1664        };
1665
1666        if !candidate_value.is_empty() {
1667            self.add_ice_local_candidate(candidate_value, local_candidate.url.as_deref())?;
1668        } else {
1669            self.ice_transport_mut().ice_gathering_state = RTCIceGatheringState::Complete;
1670            // Emit OnIceGatheringStateChangeEvent
1671            self.pipeline_context.event_outs.push_back(
1672                RTCPeerConnectionEvent::OnIceGatheringStateChangeEvent(
1673                    RTCIceGatheringState::Complete,
1674                ),
1675            );
1676        }
1677
1678        Ok(())
1679    }
1680
1681    /// Tells the peer connection that ICE should be restarted.
1682    ///
1683    /// This method causes the next call to `create_offer` to generate an offer that
1684    /// will restart ICE. This is useful when network conditions change or the connection
1685    /// fails.
1686    ///
1687    /// # Specification
1688    ///
1689    /// See [restartIce](https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-restartice)
1690    pub fn restart_ice(&mut self) {
1691        self.ice_restart_requested = Some(RTCOfferOptions { ice_restart: true });
1692    }
1693
1694    /// Returns the current configuration of this peer connection.
1695    ///
1696    /// The returned reference is to the current configuration. To modify the configuration,
1697    /// use `set_configuration`.
1698    ///
1699    /// # Specification
1700    ///
1701    /// See [getConfiguration](https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-getconfiguration)
1702    pub fn get_configuration(&self) -> &RTCConfiguration {
1703        &self.configuration
1704    }
1705
1706    /// set_configuration updates the configuration of this PeerConnection object.
1707    pub fn set_configuration(&mut self, configuration: RTCConfiguration) -> Result<()> {
1708        // https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-setconfiguration (step #2)
1709        if self.peer_connection_state == RTCPeerConnectionState::Closed {
1710            return Err(Error::ErrConnectionClosed);
1711        }
1712
1713        // https://www.w3.org/TR/webrtc/#set-the-configuration (step #3)
1714        if !configuration.peer_identity.is_empty() {
1715            if configuration.peer_identity != self.configuration.peer_identity {
1716                return Err(Error::ErrModifyingPeerIdentity);
1717            }
1718            self.configuration.peer_identity = configuration.peer_identity;
1719        }
1720
1721        // https://www.w3.org/TR/webrtc/#set-the-configuration (step #4)
1722        if !configuration.certificates.is_empty() {
1723            if configuration.certificates.len() != self.configuration.certificates.len() {
1724                return Err(Error::ErrModifyingCertificates);
1725            }
1726
1727            self.configuration.certificates = configuration.certificates;
1728        }
1729
1730        // https://www.w3.org/TR/webrtc/#set-the-configuration (step #5)
1731
1732        if configuration.bundle_policy != self.configuration.bundle_policy {
1733            return Err(Error::ErrModifyingBundlePolicy);
1734        }
1735        self.configuration.bundle_policy = configuration.bundle_policy;
1736
1737        // https://www.w3.org/TR/webrtc/#set-the-configuration (step #6)
1738        if configuration.rtcp_mux_policy != self.configuration.rtcp_mux_policy {
1739            return Err(Error::ErrModifyingRTCPMuxPolicy);
1740        }
1741        self.configuration.rtcp_mux_policy = configuration.rtcp_mux_policy;
1742
1743        // https://www.w3.org/TR/webrtc/#set-the-configuration (step #7)
1744        if configuration.ice_candidate_pool_size != 0 {
1745            if self.configuration.ice_candidate_pool_size != configuration.ice_candidate_pool_size
1746                && self.local_description().is_some()
1747            {
1748                return Err(Error::ErrModifyingICECandidatePoolSize);
1749            }
1750            self.configuration.ice_candidate_pool_size = configuration.ice_candidate_pool_size;
1751        }
1752
1753        // https://www.w3.org/TR/webrtc/#set-the-configuration (step #8)
1754
1755        self.configuration.ice_transport_policy = configuration.ice_transport_policy;
1756
1757        // https://www.w3.org/TR/webrtc/#set-the-configuration (step #11)
1758        if !configuration.ice_servers.is_empty() {
1759            // https://www.w3.org/TR/webrtc/#set-the-configuration (step #11.3)
1760            for server in &configuration.ice_servers {
1761                server.validate()?;
1762            }
1763            self.configuration.ice_servers = configuration.ice_servers
1764        }
1765
1766        Ok(())
1767    }
1768
1769    /// create_data_channel creates a new DataChannel object with the given label
1770    /// and optional DataChannelInit used to configure properties of the
1771    /// underlying channel such as data reliability.
1772    pub fn create_data_channel(
1773        &mut self,
1774        label: &str,
1775        options: Option<RTCDataChannelInit>,
1776    ) -> Result<RTCDataChannel<'_, I>>
1777    where
1778        I: Interceptor,
1779    {
1780        // https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #2)
1781        if self.peer_connection_state == RTCPeerConnectionState::Closed {
1782            return Err(Error::ErrConnectionClosed);
1783        }
1784
1785        let mut params = DataChannelParameters {
1786            label: label.to_owned(),
1787            ..Default::default()
1788        };
1789
1790        let mut id = self.generate_data_channel_id()?;
1791
1792        // https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #19)
1793        if let Some(options) = options {
1794            // https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #16)
1795            if options.max_packet_life_time.is_some() && options.max_retransmits.is_some() {
1796                return Err(Error::ErrRetransmitsOrPacketLifeTime);
1797            }
1798
1799            // Ordered indicates if data is allowed to be delivered out of order. The
1800            // default value of true, guarantees that data will be delivered in order.
1801            // https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #9)
1802            params.ordered = options.ordered;
1803
1804            // https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #7)
1805            params.max_packet_life_time = options.max_packet_life_time;
1806
1807            // https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #8)
1808            params.max_retransmits = options.max_retransmits;
1809
1810            // https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #10)
1811            params.protocol = options.protocol;
1812
1813            // https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #11)
1814            if params.protocol.len() > 65535 {
1815                return Err(Error::ErrProtocolTooLarge);
1816            }
1817
1818            // https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #12)
1819            params.negotiated = options.negotiated;
1820
1821            if let Some(negotiated_id) = &params.negotiated {
1822                id = *negotiated_id;
1823            }
1824        }
1825
1826        let data_channel = RTCDataChannelInternal::new(id, params);
1827
1828        self.data_channels.insert(id, data_channel);
1829
1830        if let Some(association_handle) = self
1831            .pipeline_context
1832            .datachannel_handler_context
1833            .association_handle
1834        {
1835            let open_result = self
1836                .get_datachannel_handler()
1837                .open_data_channel(id, association_handle);
1838            if let Err(error) = open_result {
1839                self.data_channels.remove(&id);
1840                return Err(error);
1841            }
1842        }
1843
1844        self.trigger_negotiation_needed();
1845
1846        Ok(RTCDataChannel {
1847            id,
1848            peer_connection: self,
1849        })
1850    }
1851
1852    /// Returns an iterator over the `RTCRtpSender` objects.
1853    ///
1854    /// The `RTCRtpSender` objects represent the media streams that are being sent
1855    /// to the remote peer.
1856    ///
1857    /// # Specification
1858    ///
1859    /// See [getSenders](https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-getsenders)
1860    pub fn get_senders(&self) -> impl Iterator<Item = RTCRtpSenderId> + use<'_, I> {
1861        self.rtp_transceivers
1862            .iter()
1863            .enumerate()
1864            .filter(|(_, transceiver)| transceiver.direction().has_send())
1865            .map(|(id, _)| RTCRtpSenderId(id))
1866    }
1867
1868    /// Returns an iterator over the `RTCRtpReceiver` objects.
1869    ///
1870    /// The `RTCRtpReceiver` objects represent the media streams that are being received
1871    /// from the remote peer.
1872    ///
1873    /// # Specification
1874    ///
1875    /// See [getReceivers](https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-getreceivers)
1876    pub fn get_receivers(&self) -> impl Iterator<Item = RTCRtpReceiverId> + use<'_, I> {
1877        self.rtp_transceivers
1878            .iter()
1879            .enumerate()
1880            .filter(|(_, transceiver)| transceiver.direction().has_recv())
1881            .map(|(id, _)| RTCRtpReceiverId(id))
1882    }
1883
1884    /// Returns an iterator over the `RTCRtpTransceiver` objects.
1885    ///
1886    /// The `RTCRtpTransceiver` objects represent the combination of an `RTCRtpSender`
1887    /// and an `RTCRtpReceiver` that share a common mid.
1888    ///
1889    /// # Specification
1890    ///
1891    /// See [getTransceivers](https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-gettransceivers)
1892    pub fn get_transceivers(&self) -> impl Iterator<Item = RTCRtpTransceiverId> {
1893        0..self.rtp_transceivers.len()
1894    }
1895
1896    /// Adds a media track to the peer connection.
1897    ///
1898    /// This method adds a track to the connection, either by finding an existing transceiver
1899    /// that can be reused, or by creating a new transceiver. The track represents media
1900    /// (audio or video) that will be sent to the remote peer.
1901    ///
1902    /// # Arguments
1903    ///
1904    /// * `track` - The media stream track to add.
1905    ///
1906    /// # Returns
1907    ///
1908    /// Returns the ID of the `RTCRtpSender` that will send this track.
1909    ///
1910    /// # Errors
1911    ///
1912    /// Returns an error if the peer connection is closed.
1913    ///
1914    /// # Specification
1915    ///
1916    /// See [addTrack](https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-addtrack)
1917    pub fn add_track(&mut self, track: MediaStreamTrack) -> Result<RTCRtpSenderId> {
1918        if self.peer_connection_state == RTCPeerConnectionState::Closed {
1919            return Err(Error::ErrConnectionClosed);
1920        }
1921
1922        let send_encodings = self.send_encodings_from_track(&track);
1923        for (id, transceiver) in self.rtp_transceivers.iter_mut().enumerate() {
1924            if !transceiver.stopped()
1925                && transceiver.kind() == track.kind()
1926                && transceiver.sender().is_none()
1927            {
1928                let mut sender =
1929                    RTCRtpSenderInternal::new(track.kind(), track, vec![], send_encodings);
1930
1931                sender.set_codec_preferences(transceiver.get_codec_preferences().to_vec());
1932
1933                transceiver.sender_mut().replace(sender);
1934
1935                transceiver.set_direction(RTCRtpTransceiverDirection::from_send_recv(
1936                    true,
1937                    transceiver.direction().has_recv(),
1938                ));
1939
1940                self.trigger_negotiation_needed();
1941                return Ok(RTCRtpSenderId(id));
1942            }
1943        }
1944
1945        let transceiver = self.new_transceiver_from_track(
1946            track,
1947            RTCRtpTransceiverInit {
1948                direction: RTCRtpTransceiverDirection::Sendrecv,
1949                streams: vec![],
1950                send_encodings,
1951            },
1952        )?;
1953        Ok(RTCRtpSenderId(self.add_rtp_transceiver(transceiver)))
1954    }
1955
1956    /// Removes a track from the peer connection.
1957    ///
1958    /// This method stops an `RTCRtpSender` from sending media and marks its transceiver
1959    /// as no longer sending. This will trigger renegotiation.
1960    ///
1961    /// # Arguments
1962    ///
1963    /// * `sender_id` - The ID of the `RTCRtpSender` to remove.
1964    ///
1965    /// # Errors
1966    ///
1967    /// Returns an error if:
1968    /// - The peer connection is closed
1969    /// - The sender ID is invalid
1970    ///
1971    /// # Specification
1972    ///
1973    /// See [removeTrack](https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-removetrack)
1974    pub fn remove_track(&mut self, sender_id: RTCRtpSenderId) -> Result<()> {
1975        if self.peer_connection_state == RTCPeerConnectionState::Closed {
1976            return Err(Error::ErrConnectionClosed);
1977        }
1978
1979        if sender_id.0 >= self.rtp_transceivers.len() {
1980            return Err(Error::ErrRTPSenderNotExisted);
1981        }
1982
1983        // This also happens in `set_sending_track` but we need to make sure we do this
1984        // before we call sender.stop to avoid a race condition when removing tracks and
1985        // generating offers.
1986        let has_recv = self.rtp_transceivers[sender_id.0].direction().has_recv();
1987        self.rtp_transceivers[sender_id.0]
1988            .set_direction(RTCRtpTransceiverDirection::from_send_recv(false, has_recv));
1989
1990        if let Some(sender) = self.rtp_transceivers[sender_id.0].sender_mut()
1991            && sender
1992                .stop(&self.media_engine, &mut self.interceptor)
1993                .is_ok()
1994        {
1995            self.trigger_negotiation_needed();
1996        }
1997
1998        self.rtp_transceivers[sender_id.0].sender_mut().take();
1999
2000        Ok(())
2001    }
2002
2003    /// Creates a new `RTCRtpTransceiver` and adds it to the set of transceivers.
2004    ///
2005    /// This method creates a transceiver associated with the given track, which can be
2006    /// configured to send, receive, or both.
2007    ///
2008    /// # Arguments
2009    ///
2010    /// * `track` - The media stream track to associate with the transceiver.
2011    /// * `init` - Optional initialization parameters for the transceiver.
2012    ///
2013    /// # Returns
2014    ///
2015    /// Returns the ID of the created transceiver.
2016    ///
2017    /// # Errors
2018    ///
2019    /// Returns an error if the peer connection is closed.
2020    ///
2021    /// # Specification
2022    ///
2023    /// See [addTransceiver](https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-addtransceiver)
2024    pub fn add_transceiver_from_track(
2025        &mut self,
2026        track: MediaStreamTrack,
2027        init: Option<RTCRtpTransceiverInit>,
2028    ) -> Result<RTCRtpTransceiverId> {
2029        if self.peer_connection_state == RTCPeerConnectionState::Closed {
2030            return Err(Error::ErrConnectionClosed);
2031        }
2032
2033        if let Some(init) = init.as_ref()
2034            && !init.direction.has_send()
2035        {
2036            return Err(Error::ErrInvalidDirection);
2037        }
2038
2039        let transceiver = self.new_transceiver_from_track(
2040            track,
2041            if let Some(init) = init {
2042                init
2043            } else {
2044                RTCRtpTransceiverInit {
2045                    direction: RTCRtpTransceiverDirection::Sendrecv,
2046                    streams: vec![],
2047                    send_encodings: vec![],
2048                }
2049            },
2050        )?;
2051
2052        Ok(self.add_rtp_transceiver(transceiver))
2053    }
2054
2055    /// add_transceiver_from_kind Create a new RtpTransceiver and adds it to the set of transceivers.
2056    pub fn add_transceiver_from_kind(
2057        &mut self,
2058        kind: RtpCodecKind,
2059        init: Option<RTCRtpTransceiverInit>,
2060    ) -> Result<RTCRtpTransceiverId> {
2061        if self.peer_connection_state == RTCPeerConnectionState::Closed {
2062            return Err(Error::ErrConnectionClosed);
2063        }
2064
2065        let (direction, streams, send_encodings) = if let Some(init) = init {
2066            if init.direction.has_send() && init.send_encodings.is_empty() {
2067                return Err(Error::ErrInvalidDirection);
2068            }
2069
2070            (init.direction, init.streams, init.send_encodings)
2071        } else {
2072            (RTCRtpTransceiverDirection::Recvonly, vec![], vec![])
2073        };
2074
2075        let transceiver = match direction {
2076            RTCRtpTransceiverDirection::Sendonly | RTCRtpTransceiverDirection::Sendrecv => {
2077                let codecs = self.media_engine.get_codecs_by_kind(kind);
2078                let (encoding, code_match_result) =
2079                    encoding_parameters_fuzzy_search(&send_encodings, &codecs);
2080                if code_match_result != CodecMatch::None {
2081                    if encoding.rtp_coding_parameters.rid.is_empty()
2082                        && encoding.rtp_coding_parameters.ssrc.is_none()
2083                    {
2084                        return Err(Error::ErrRTPSenderNoBaseEncoding);
2085                    }
2086
2087                    let track = MediaStreamTrack::new(
2088                        math_rand_alpha(16), // MediaStreamId
2089                        math_rand_alpha(16), // MediaStreamTrackId
2090                        math_rand_alpha(16), // Label
2091                        kind,
2092                        vec![RTCRtpEncodingParameters {
2093                            rtp_coding_parameters: RTCRtpCodingParameters {
2094                                rid: encoding.rtp_coding_parameters.rid,
2095                                ssrc: if let Some(ssrc) = encoding.rtp_coding_parameters.ssrc {
2096                                    Some(ssrc)
2097                                } else {
2098                                    Some(rand::random::<u32>())
2099                                },
2100                                rtx: None,
2101                                fec: None,
2102                            },
2103                            codec: encoding.codec,
2104                            ..Default::default()
2105                        }],
2106                    );
2107                    self.new_transceiver_from_track(
2108                        track,
2109                        RTCRtpTransceiverInit {
2110                            direction,
2111                            streams,
2112                            send_encodings,
2113                        },
2114                    )?
2115                } else {
2116                    return Err(Error::ErrRTPSenderNoBaseEncoding);
2117                }
2118            }
2119            RTCRtpTransceiverDirection::Recvonly => RTCRtpTransceiverInternal::new(
2120                kind,
2121                None,
2122                RTCRtpTransceiverInit {
2123                    direction,
2124                    streams: vec![],
2125                    send_encodings: vec![],
2126                },
2127            ),
2128            _ => return Err(Error::ErrPeerConnAddTransceiverFromKindSupport),
2129        };
2130
2131        Ok(self.add_rtp_transceiver(transceiver))
2132    }
2133
2134    /// data_channel provides the access to RTCDataChannel object with the given id
2135    pub fn data_channel(&mut self, id: RTCDataChannelId) -> Option<RTCDataChannel<'_, I>>
2136    where
2137        I: Interceptor,
2138    {
2139        if self.data_channels.contains_key(&id) {
2140            Some(RTCDataChannel {
2141                id,
2142                peer_connection: self,
2143            })
2144        } else {
2145            None
2146        }
2147    }
2148
2149    /// rtp_sender provides the access to RTCRtpSender object with the given id
2150    pub fn rtp_sender(&mut self, id: RTCRtpSenderId) -> Option<RTCRtpSender<'_, I>>
2151    where
2152        I: Interceptor,
2153    {
2154        if id.0 < self.rtp_transceivers.len()
2155            && self.rtp_transceivers[id.0].direction().has_send()
2156            && self.rtp_transceivers[id.0].sender().is_some()
2157        {
2158            Some(RTCRtpSender {
2159                id,
2160                peer_connection: self,
2161            })
2162        } else {
2163            None
2164        }
2165    }
2166
2167    /// rtp_receiver provides the access to RTCRtpReceiver object with the given id
2168    pub fn rtp_receiver(&mut self, id: RTCRtpReceiverId) -> Option<RTCRtpReceiver<'_, I>>
2169    where
2170        I: Interceptor,
2171    {
2172        if id.0 < self.rtp_transceivers.len()
2173            && self.rtp_transceivers[id.0].direction().has_recv()
2174            && self.rtp_transceivers[id.0].receiver().is_some()
2175        {
2176            Some(RTCRtpReceiver {
2177                id,
2178                peer_connection: self,
2179            })
2180        } else {
2181            None
2182        }
2183    }
2184
2185    /// rtp_transceiver provides the access to RTCRtpTransceiver object with the given id
2186    pub fn rtp_transceiver(&mut self, id: RTCRtpTransceiverId) -> Option<RTCRtpTransceiver<'_, I>>
2187    where
2188        I: Interceptor,
2189    {
2190        if id < self.rtp_transceivers.len() {
2191            Some(RTCRtpTransceiver {
2192                id,
2193                peer_connection: self,
2194            })
2195        } else {
2196            None
2197        }
2198    }
2199
2200    /// Returns a snapshot of accumulated statistics.
2201    ///
2202    /// This method creates an immutable snapshot of WebRTC statistics
2203    /// at the given timestamp. When `selector` is `StatsSelector::None`,
2204    /// the returned `RTCStatsReport` contains statistics for all aspects
2205    /// of the peer connection. When a sender or receiver is specified,
2206    /// only statistics relevant to that sender/receiver are included.
2207    ///
2208    /// # Statistics included by selector
2209    ///
2210    /// - `StatsSelector::None` - All statistics for the entire connection
2211    /// - `StatsSelector::Sender(id)` - Outbound RTP streams for the sender
2212    ///   and all referenced stats (transport, codec, remote inbound, etc.)
2213    /// - `StatsSelector::Receiver(id)` - Inbound RTP streams for the receiver
2214    ///   and all referenced stats (transport, codec, remote outbound, etc.)
2215    ///
2216    /// # Arguments
2217    ///
2218    /// * `now` - The timestamp to use for all stats in the report. This is
2219    ///   passed explicitly to support deterministic testing.
2220    /// * `selector` - Controls which statistics are included in the report.
2221    ///
2222    /// # Returns
2223    ///
2224    /// An `RTCStatsReport` containing snapshots of the selected statistics.
2225    ///
2226    /// # Example
2227    ///
2228    /// ```no_run
2229    /// use std::time::Instant;
2230    /// use rtc::peer_connection::RTCPeerConnectionBuilder;
2231    /// use rtc::statistics::StatsSelector;
2232    ///
2233    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
2234    /// let mut pc = RTCPeerConnectionBuilder::new().build()?;
2235    ///
2236    /// // Get all stats
2237    /// let report = pc.get_stats(Instant::now(), StatsSelector::None);
2238    ///
2239    /// // Access peer connection stats
2240    /// if let Some(pc_stats) = report.peer_connection() {
2241    ///     println!("Data channels opened: {}", pc_stats.data_channels_opened);
2242    /// }
2243    ///
2244    /// // Iterate over inbound RTP streams
2245    /// for stream in report.inbound_rtp_streams() {
2246    ///     println!("SSRC {}: {} packets received", stream.received_rtp_stream_stats.rtp_stream_stats.ssrc, stream.received_rtp_stream_stats.packets_received);
2247    /// }
2248    /// # Ok(())
2249    /// # }
2250    /// ```
2251    ///
2252    /// # Specification
2253    ///
2254    /// See [getStats](https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-getstats) and
2255    /// [The stats selection algorithm](https://www.w3.org/TR/webrtc/#the-stats-selection-algorithm)
2256    pub fn get_stats(&mut self, now: Instant, selector: StatsSelector) -> RTCStatsReport {
2257        // Update ICE agent stats before taking snapshot
2258        self.update_ice_agent_stats();
2259        // Update codec stats from transceivers before taking snapshot
2260        self.update_codec_stats();
2261        self.pipeline_context
2262            .stats
2263            .snapshot_with_selector(now, selector)
2264    }
2265}
2266
2267#[cfg(test)]
2268mod data_channel_regression_tests {
2269    use super::*;
2270    use crate::data_channel::RTCDataChannelState;
2271    use crate::peer_connection::event::RTCEventInternal;
2272    use sansio::Protocol;
2273
2274    #[test]
2275    fn data_channel_created_after_sctp_handshake_is_opened_immediately() -> Result<()> {
2276        let mut peer_connection = RTCPeerConnectionBuilder::new().build()?;
2277
2278        peer_connection
2279            .get_datachannel_handler()
2280            .handle_event(RTCEventInternal::SCTPHandshakeComplete(42))?;
2281
2282        let data_channel_id = {
2283            let data_channel = peer_connection.create_data_channel("late-channel", None)?;
2284            assert_eq!(data_channel.ready_state(), RTCDataChannelState::Open);
2285            data_channel.id()
2286        };
2287
2288        let data_channel = peer_connection
2289            .data_channels
2290            .get(&data_channel_id)
2291            .expect("late-created DataChannel must remain registered");
2292        assert!(data_channel.data_channel.is_some());
2293        assert_eq!(
2294            peer_connection
2295                .pipeline_context
2296                .datachannel_handler_context
2297                .association_handle,
2298            Some(42)
2299        );
2300        assert!(
2301            !peer_connection
2302                .pipeline_context
2303                .datachannel_handler_context
2304                .write_outs
2305                .is_empty(),
2306            "opening the channel must enqueue its DCEP message"
2307        );
2308
2309        Ok(())
2310    }
2311}