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