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://www.w3.org/TR/webrtc/). It provides
5//! the core functionality for establishing peer-to-peer connections, negotiating
6//! media capabilities, and managing data channels.
7//!
8//! # Overview
9//!
10//! `RTCPeerConnection` is the central interface in WebRTC. It handles:
11//!
12//! - **Signaling**: Creating and exchanging SDP offers/answers
13//! - **ICE**: Gathering candidates and establishing connectivity
14//! - **Media**: Managing audio/video tracks and transceivers
15//! - **Data**: Creating and managing data channels
16//! - **Security**: DTLS encryption for all communication
17//!
18//! # Architecture
19//!
20//! This is a **sans-I/O** implementation, meaning it separates protocol logic
21//! from I/O operations. The application is responsible for:
22//!
23//! - Transmitting/receiving network packets
24//! - Managing the event loop
25//! - Handling signaling channel communication
26//!
27//! ## Sans-I/O Benefits
28//!
29//! - **Flexibility**: Keeps protocol logic independent of I/O scheduling; rvoip's
30//!   integration layer uses Tokio
31//! - **Testability**: Protocol logic can be tested without network I/O
32//! - **Control**: Application has full control over threading and scheduling
33//!
34//! # Connection Establishment
35//!
36//! The typical WebRTC connection flow:
37//!
38//! ```text
39//! Peer A (Offerer)              Signaling Server              Peer B (Answerer)
40//! ════════════════              ════════════════              ═══════════════════
41//!      │                               │                               │
42//!      │ 1. create_offer()             │                               │
43//!      │─────────────────┐             │                               │
44//!      │                 │             │                               │
45//!      │<────────────────┘             │                               │
46//!      │                               │                               │
47//!      │ 2. set_local_description()    │                               │
48//!      │─────────────────┐             │                               │
49//!      │                 │             │                               │
50//!      │<────────────────┘             │                               │
51//!      │                               │                               │
52//!      │ 3. send offer (via signaling) │                               │
53//!      │──────────────────────────────>│──────────────────────────────>│
54//!      │                               │                               │
55//!      │                               │  4. set_remote_description()  │
56//!      │                               │                  ┌────────────┤
57//!      │                               │                  │            │
58//!      │                               │                  └───────────>│
59//!      │                               │                               │
60//!      │                               │       5. create_answer()      │
61//!      │                               │                  ┌────────────┤
62//!      │                               │                  │            │
63//!      │                               │                  └───────────>│
64//!      │                               │                               │
65//!      │                               │  6. set_local_description()   │
66//!      │                               │                  ┌────────────┤
67//!      │                               │                  │            │
68//!      │                               │                  └───────────>│
69//!      │                               │                               │
70//!      │ 7. receive answer             │<──────────────────────────────│
71//!      │<──────────────────────────────┤                               │
72//!      │                               │                               │
73//!      │ 8. set_remote_description()   │                               │
74//!      │─────────────────┐             │                               │
75//!      │                 │             │                               │
76//!      │<────────────────┘             │                               │
77//!      │                               │                               │
78//!      │ 9. ICE candidates exchanged   │                               │
79//!      │<─────────────────────────────────────────────────────────────>│
80//!      │                               │                               │
81//!      │ 10. Media/data flows directly │                               │
82//!      │<═════════════════════════════════════════════════════════════>│
83//! ```
84//!
85//! # Examples
86//!
87//! ## Creating a Peer Connection
88//!
89//! ```
90//! # use std::time::Instant;
91//! use rtc::peer_connection::RTCPeerConnectionBuilder;
92//!
93//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
94//! // Create with default configuration
95//! let mut pc = RTCPeerConnectionBuilder::new().build(Instant::now())?;
96//! # Ok(())
97//! # }
98//! ```
99//!
100//! ## Creating an Offer (Initiating Peer)
101//!
102//! ```no_run
103//! # use std::time::Instant;
104//! use rtc::peer_connection::RTCPeerConnectionBuilder;
105//!
106//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
107//! let mut pc = RTCPeerConnectionBuilder::new().build(Instant::now())?;
108//!
109//! // Add media track or data channel first
110//! // pc.add_track(audio_track)?;
111//!
112//! // Create offer
113//! let offer = pc.create_offer(None)?;
114//!
115//! // Set as local description
116//! pc.set_local_description(Instant::now(), offer.clone())?;
117//!
118//! // Send offer.sdp to remote peer via signaling channel
119//! // signaling_channel.send(offer.sdp)?;
120//! # Ok(())
121//! # }
122//! ```
123//!
124//! ## Answering an Offer (Responding Peer)
125//!
126//! ```no_run
127//! # use std::time::Instant;
128//! use rtc::peer_connection::RTCPeerConnectionBuilder;
129//! use rtc::peer_connection::sdp::RTCSessionDescription;
130//!
131//! # fn example(remote_offer_sdp: String) -> Result<(), Box<dyn std::error::Error>> {
132//! let mut pc = RTCPeerConnectionBuilder::new().build(Instant::now())?;
133//!
134//! // Receive offer from remote peer
135//! let offer = RTCSessionDescription::offer(remote_offer_sdp)?;
136//!
137//! // Set as remote description
138//! pc.set_remote_description(Instant::now(), offer)?;
139//!
140//! // Create answer
141//! let answer = pc.create_answer(None)?;
142//!
143//! // Set as local description
144//! pc.set_local_description(Instant::now(), answer.clone())?;
145//!
146//! // Send answer.sdp to remote peer via signaling channel
147//! // signaling_channel.send(answer.sdp)?;
148//! # Ok(())
149//! # }
150//! ```
151//!
152//! ## Adding Media Tracks
153//!
154//! ```no_run
155//! # use std::time::Instant;
156//! use rtc::peer_connection::RTCPeerConnectionBuilder;
157//! use rtc::media_stream::MediaStreamTrack;
158//! use rtc::rtp_transceiver::rtp_sender::RtpCodecKind;
159//!
160//! # fn example(audio_track: MediaStreamTrack) -> Result<(), Box<dyn std::error::Error>> {
161//! let mut pc = RTCPeerConnectionBuilder::new().build(Instant::now())?;
162//!
163//! // Add an audio track
164//! let sender_id = pc.add_track(audio_track)?;
165//!
166//! // Or add a transceiver for receiving
167//! let transceiver_id = pc.add_transceiver_from_kind(RtpCodecKind::Video, None)?;
168//! # Ok(())
169//! # }
170//! ```
171//!
172//! ## Creating Data Channels
173//!
174//! ```no_run
175//! # use std::time::Instant;
176//! use rtc::peer_connection::RTCPeerConnectionBuilder;
177//! use rtc::data_channel::RTCDataChannelInit;
178//!
179//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
180//! let mut pc = RTCPeerConnectionBuilder::new().build(Instant::now())?;
181//!
182//! // Create a reliable, ordered data channel
183//! let init = RTCDataChannelInit {
184//!     ordered: true,
185//!     max_retransmits: None,
186//!     ..Default::default()
187//! };
188//!
189//! let channel_id = pc.create_data_channel("my-channel", Some(init))?;
190//! # Ok(())
191//! # }
192//! ```
193//!
194//! ## ICE Candidate Exchange
195//!
196//! ```no_run
197//! use rtc::peer_connection::{RTCPeerConnection, RTCPeerConnectionBuilder};
198//! use rtc::peer_connection::transport::RTCIceCandidateInit;
199//!
200//! # fn example(mut pc: RTCPeerConnection) -> Result<(), Box<dyn std::error::Error>> {
201//! // When local candidates are gathered, send to remote peer
202//! // (In sans-I/O, you'd poll for events to get candidates)
203//!
204//! // When receiving remote candidate from signaling channel
205//! let remote_candidate = RTCIceCandidateInit {
206//!     candidate: "candidate:1 1 UDP 2130706431 192.168.1.100 54321 typ host".to_string(),
207//!     ..Default::default()
208//! };
209//!
210//! pc.add_remote_candidate(remote_candidate)?;
211//! # Ok(())
212//! # }
213//! ```
214//!
215//! # State Management
216//!
217//! The peer connection maintains several state machines:
218//!
219//! - **Signaling State**: SDP negotiation progress (stable, have-local-offer, etc.)
220//! - **ICE Connection State**: Network connectivity status
221//! - **ICE Gathering State**: Candidate gathering progress
222//! - **Connection State**: Overall connection health
223//!
224//! Monitor these states through the event system (sans-I/O polling).
225//!
226//! # Thread Safety
227//!
228//! `RTCPeerConnection` is **not** thread-safe. The application must ensure
229//! exclusive access or use appropriate synchronization primitives.
230//!
231//! # Specification
232//!
233//! - [W3C WebRTC 1.0] - Main specification
234//! - [RFC 9429] - JSEP: JavaScript Session Establishment Protocol
235//! - [RFC 8866] - SDP: Session Description Protocol
236//! - [RFC 8445] - ICE: Interactive Connectivity Establishment
237//! - [RFC 8831] - WebRTC Data Channels
238//!
239//! [W3C WebRTC 1.0]: https://www.w3.org/TR/webrtc/
240//! [RFC 9429]: https://datatracker.ietf.org/doc/html/rfc9429
241//! [RFC 8866]: https://datatracker.ietf.org/doc/html/rfc8866
242//! [RFC 8445]: https://datatracker.ietf.org/doc/html/rfc8445
243//! [RFC 8831]: https://datatracker.ietf.org/doc/html/rfc8831
244
245pub mod certificate;
246pub mod configuration;
247pub mod event;
248pub(crate) mod handler;
249mod internal;
250pub mod message;
251pub mod sdp;
252pub mod state;
253pub mod transport;
254
255use crate::data_channel::init::RTCDataChannelInit;
256use crate::data_channel::parameters::DataChannelParameters;
257use crate::data_channel::registry::DataChannelRegistry;
258use crate::data_channel::state::RTCDataChannelState;
259use crate::data_channel::{RTCDataChannel, RTCDataChannelId, internal::RTCDataChannelInternal};
260use crate::media_stream::track::MediaStreamTrack;
261use crate::peer_connection::configuration::media_engine::MediaEngine;
262use crate::peer_connection::configuration::setting_engine::{SctpMaxMessageSize, SettingEngine};
263use crate::peer_connection::configuration::{
264    RTCConfiguration, RTCIceTransportPolicy,
265    offer_answer_options::{RTCAnswerOptions, RTCOfferOptions},
266};
267use crate::peer_connection::event::RTCPeerConnectionEvent;
268use crate::peer_connection::handler::PipelineContext;
269use crate::peer_connection::handler::dtls::DtlsHandlerContext;
270use crate::peer_connection::handler::ice::IceHandlerContext;
271use crate::peer_connection::handler::sctp::SctpHandlerContext;
272use crate::peer_connection::sdp::MediaDescriptionExt;
273use crate::peer_connection::sdp::session_description::RTCSessionDescription;
274use crate::peer_connection::sdp::{
275    extract_fingerprint, extract_ice_details, get_application_media,
276    get_application_media_section_max_message_size, get_application_media_section_sctp_port,
277    get_mid_value, get_peer_direction, has_ice_trickle_option, is_lite_set, sdp_type::RTCSdpType,
278    update_sdp_origin,
279};
280use crate::peer_connection::state::RTCIceGatheringState;
281use crate::peer_connection::state::ice_connection_state::RTCIceConnectionState;
282use crate::peer_connection::state::peer_connection_state::{
283    NegotiationNeededState, RTCPeerConnectionState,
284};
285use crate::peer_connection::state::signaling_state::{RTCSignalingState, StateChangeOp};
286use crate::peer_connection::transport::RTCSctpTransport;
287use crate::peer_connection::transport::dtls::fingerprint::RTCDtlsFingerprint;
288use crate::peer_connection::transport::dtls::parameters::RTCDtlsParameters;
289use crate::peer_connection::transport::dtls::role::{
290    DEFAULT_DTLS_ROLE_ANSWER, DEFAULT_DTLS_ROLE_OFFER, RTCDtlsRole,
291};
292use crate::peer_connection::transport::dtls::{DtlsTransport, RTCDtlsTransportConfig};
293use crate::peer_connection::transport::ice::IceTransport;
294use crate::peer_connection::transport::ice::candidate::RTCIceCandidateInit;
295use crate::peer_connection::transport::ice::parameters::RTCIceParameters;
296use crate::peer_connection::transport::ice::role::RTCIceRole;
297use crate::peer_connection::transport::sctp::SctpTransport;
298use crate::peer_connection::transport::sctp::capabilities::SCTPTransportCapabilities;
299use crate::rtp_transceiver::direction::RTCRtpTransceiverDirection;
300use crate::rtp_transceiver::rtp_receiver::RTCRtpReceiver;
301use crate::rtp_transceiver::rtp_sender::RTCRtpCodecParameters;
302use crate::rtp_transceiver::rtp_sender::RTCRtpSender;
303use crate::rtp_transceiver::rtp_sender::internal::RTCRtpSenderInternal;
304use crate::rtp_transceiver::rtp_sender::rtp_codec::{
305    CodecMatch, RtpCodecKind, codec_parameters_fuzzy_search,
306};
307use crate::rtp_transceiver::{
308    RTCRtpReceiverId, RTCRtpSenderId, RTCRtpTransceiver, RTCRtpTransceiverId,
309    RTCRtpTransceiverInit, internal::RTCRtpTransceiverInternal,
310};
311use crate::statistics::StatsSelector;
312use crate::statistics::accumulator::RTCStatsAccumulator;
313use crate::statistics::report::RTCStatsReport;
314use ::sdp::description::session::Origin;
315use ::sdp::util::ConnectionRole;
316use ice::AgentConfig;
317use ice::candidate::{Candidate, unmarshal_candidate};
318use interceptor::{Interceptor, Registry};
319use shared::error::{Error, Result};
320use shared::util::math_rand_alpha;
321use std::time::Instant;
322
323/// Builder for creating RTCPeerConnection instances.
324///
325/// This builder provides a fluent API for configuring peer connections with:
326/// - ICE servers (STUN/TURN) via [`RTCConfiguration`]
327/// - Media codecs and RTP extensions via [`MediaEngine`]
328/// - Low-level transport settings via [`SettingEngine`]
329/// - RTP/RTCP interceptors for NACK, TWCC, and RTCP reports
330///
331/// # Examples
332///
333/// ## Basic peer connection
334///
335/// ```
336/// # use std::time::Instant;
337/// use rtc::peer_connection::RTCPeerConnectionBuilder;
338///
339/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
340/// let pc = RTCPeerConnectionBuilder::new().build(Instant::now())?;
341/// # Ok(())
342/// # }
343/// ```
344///
345/// ## With ICE servers
346///
347/// ```
348/// # use std::time::Instant;
349/// use rtc::peer_connection::RTCPeerConnectionBuilder;
350/// use rtc::peer_connection::configuration::{RTCConfigurationBuilder, RTCIceServer};
351///
352/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
353/// let pc = RTCPeerConnectionBuilder::new()
354///     .with_configuration(
355///         RTCConfigurationBuilder::new()
356///             .with_ice_servers(vec![RTCIceServer {
357///                 urls: vec!["stun:stun.l.google.com:19302".to_string()],
358///                 ..Default::default()
359///             }])
360///             .build()
361///     )
362///     .build(Instant::now())?;
363/// # Ok(())
364/// # }
365/// ```
366///
367/// ## With custom media engine
368///
369/// ```
370/// # use std::time::Instant;
371/// use rtc::peer_connection::RTCPeerConnectionBuilder;
372/// use rtc::peer_connection::configuration::media_engine::MediaEngine;
373///
374/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
375/// let mut media_engine = MediaEngine::default();
376/// media_engine.register_default_codecs()?;
377///
378/// let pc = RTCPeerConnectionBuilder::new()
379///     .with_media_engine(media_engine)
380///     .build(Instant::now())?;
381/// # Ok(())
382/// # }
383/// ```
384///
385/// ## With interceptors
386///
387/// ```
388/// # use std::time::Instant;
389/// use rtc::peer_connection::RTCPeerConnectionBuilder;
390/// use rtc::peer_connection::configuration::media_engine::MediaEngine;
391/// use rtc::peer_connection::configuration::interceptor_registry::{
392///     Registry, register_default_interceptors,
393/// };
394///
395/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
396/// let mut media_engine = MediaEngine::default();
397/// let registry = Registry::new();
398/// let registry = register_default_interceptors(registry, &mut media_engine)?;
399///
400/// let pc = RTCPeerConnectionBuilder::new()
401///     .with_media_engine(media_engine)
402///     .with_interceptor_registry(registry)
403///     .build(Instant::now())?;
404/// # Ok(())
405/// # }
406/// ```
407#[derive(Default)]
408pub struct RTCPeerConnectionBuilder {
409    configuration: RTCConfiguration,
410    media_engine: MediaEngine,
411    setting_engine: SettingEngine,
412    interceptor_registry: Registry,
413}
414
415impl RTCPeerConnectionBuilder {
416    /// Creates a new RTCPeerConnectionBuilder with default configuration.
417    ///
418    /// The default builder includes:
419    /// - Empty ICE server list
420    /// - Default MediaEngine (no codecs registered)
421    /// - Default SettingEngine (standard timeouts and limits)
422    /// - NoopInterceptor (no RTP/RTCP processing)
423    ///
424    /// Use `with_*` methods to customize configuration before calling `build()`.
425    ///
426    /// # Examples
427    ///
428    /// ```
429    /// # use std::time::Instant;
430    /// use rtc::peer_connection::RTCPeerConnectionBuilder;
431    ///
432    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
433    /// let pc = RTCPeerConnectionBuilder::new().build(Instant::now())?;
434    /// # Ok(())
435    /// # }
436    /// ```
437    pub fn new() -> Self {
438        Self::default()
439    }
440}
441
442impl RTCPeerConnectionBuilder {
443    /// Sets the RTCConfiguration for the peer connection.
444    ///
445    /// The configuration includes ICE servers, transport policies, bundle policies,
446    /// RTCP mux policies, and certificates.
447    ///
448    /// # Examples
449    ///
450    /// ```
451    /// # use std::time::Instant;
452    /// use rtc::peer_connection::RTCPeerConnectionBuilder;
453    /// use rtc::peer_connection::configuration::{RTCConfigurationBuilder, RTCIceServer};
454    ///
455    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
456    /// let config = RTCConfigurationBuilder::new()
457    ///     .with_ice_servers(vec![RTCIceServer {
458    ///         urls: vec!["stun:stun.l.google.com:19302".to_string()],
459    ///         ..Default::default()
460    ///     }])
461    ///     .build();
462    ///
463    /// let pc = RTCPeerConnectionBuilder::new()
464    ///     .with_configuration(config)
465    ///     .build(Instant::now())?;
466    /// # Ok(())
467    /// # }
468    /// ```
469    pub fn with_configuration(mut self, configuration: RTCConfiguration) -> Self {
470        self.configuration = configuration;
471        self
472    }
473
474    /// Sets the MediaEngine for the peer connection.
475    ///
476    /// The media engine configures codecs and RTP header extensions.
477    ///
478    /// # Examples
479    ///
480    /// ```
481    /// # use std::time::Instant;
482    /// use rtc::peer_connection::RTCPeerConnectionBuilder;
483    /// use rtc::peer_connection::configuration::media_engine::MediaEngine;
484    ///
485    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
486    /// let mut media_engine = MediaEngine::default();
487    /// media_engine.register_default_codecs()?;
488    ///
489    /// let pc = RTCPeerConnectionBuilder::new()
490    ///     .with_media_engine(media_engine)
491    ///     .build(Instant::now())?;
492    /// # Ok(())
493    /// # }
494    /// ```
495    pub fn with_media_engine(mut self, media_engine: MediaEngine) -> Self {
496        self.media_engine = media_engine;
497        self
498    }
499
500    /// Sets the SettingEngine for the peer connection.
501    ///
502    /// The setting engine configures low-level transport parameters including
503    /// timeouts, buffer sizes, ICE settings, and SCTP parameters.
504    ///
505    /// # Examples
506    ///
507    /// ```
508    /// # use std::time::Instant;
509    /// use rtc::peer_connection::RTCPeerConnectionBuilder;
510    /// use rtc::peer_connection::configuration::setting_engine::SettingEngineBuilder;
511    /// use std::time::Duration;
512    ///
513    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
514    /// let setting_engine = SettingEngineBuilder::new()
515    ///     .with_ice_timeouts(
516    ///         Some(Duration::from_secs(30)),
517    ///         Some(Duration::from_secs(60)),
518    ///         Some(Duration::from_millis(100)),
519    ///     )
520    ///     .build();
521    ///
522    /// let pc = RTCPeerConnectionBuilder::new()
523    ///     .with_setting_engine(setting_engine)
524    ///     .build(Instant::now())?;
525    /// # Ok(())
526    /// # }
527    /// ```
528    pub fn with_setting_engine(mut self, setting_engine: SettingEngine) -> Self {
529        self.setting_engine = setting_engine;
530        self
531    }
532
533    /// Configures the peer connection with an interceptor registry.
534    ///
535    /// Interceptors process RTP/RTCP packets as they flow through the pipeline,
536    /// enabling features like:
537    /// - NACK (Negative Acknowledgment) for packet loss recovery
538    /// - TWCC (Transport-Wide Congestion Control) for bandwidth estimation
539    /// - RTCP Reports for quality statistics
540    ///
541    /// This method replaces the builder's interceptor type — `NoopInterceptor` by default —
542    /// with the registry's, so it returns a `RTCPeerConnectionBuilder<P>` rather than
543    /// `Self`. Every other builder setting is carried over, and the remaining setters are
544    /// available on the returned builder, so this does not have to be the last call before
545    /// `build()`; it is simply the only one that changes the builder's type.
546    ///
547    /// # Type Parameters
548    ///
549    /// * `P` - The interceptor type produced by the registry
550    ///
551    /// # Examples
552    ///
553    /// ```
554    /// # use std::time::Instant;
555    /// use rtc::peer_connection::RTCPeerConnectionBuilder;
556    /// use rtc::peer_connection::configuration::media_engine::MediaEngine;
557    /// use rtc::peer_connection::configuration::interceptor_registry::{
558    ///     Registry, register_default_interceptors,
559    /// };
560    ///
561    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
562    /// let mut media_engine = MediaEngine::default();
563    /// let registry = Registry::new();
564    /// let registry = register_default_interceptors(registry, &mut media_engine)?;
565    ///
566    /// let pc = RTCPeerConnectionBuilder::new()
567    ///     .with_media_engine(media_engine)
568    ///     .with_interceptor_registry(registry)
569    ///     .build(Instant::now())?;
570    /// # Ok(())
571    /// # }
572    /// ```
573    ///
574    /// # One connection type, whatever the chain
575    ///
576    /// A chain is a flat list of interceptors, so the connection has one concrete type whatever
577    /// the list contains. That is what lets a non-generic struct own one, or two connections with
578    /// *different* chains share a collection:
579    ///
580    /// ```
581    /// # use std::time::Instant;
582    /// use rtc::peer_connection::configuration::interceptor_registry::{
583    ///     Registry, register_default_interceptors,
584    /// };
585    /// use rtc::peer_connection::configuration::media_engine::MediaEngine;
586    /// use rtc::peer_connection::{RTCPeerConnection, RTCPeerConnectionBuilder};
587    ///
588    /// struct Session {
589    ///     peer_connection: RTCPeerConnection, // no type parameter
590    /// }
591    ///
592    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
593    /// let mut media_engine = MediaEngine::default();
594    /// let registry =
595    ///     register_default_interceptors(Registry::new(), &mut media_engine)?;
596    ///
597    /// let session = Session {
598    ///     peer_connection: RTCPeerConnectionBuilder::new()
599    ///         .with_media_engine(media_engine)
600    ///         .with_interceptor_registry(registry)
601    ///         .build(Instant::now())?,
602    /// };
603    /// # Ok(())
604    /// # }
605    /// ```
606    ///
607    /// The registry is assembled into the chain by [`build`](RTCPeerConnectionBuilder::build),
608    /// so it stays a list — inspectable, extendable — right up until the connection is made.
609    pub fn with_interceptor_registry(mut self, interceptor_registry: Registry) -> Self {
610        self.interceptor_registry = interceptor_registry;
611        self
612    }
613
614    /// Builds the RTCPeerConnection with the configured settings.
615    ///
616    /// This method validates the configuration and creates a new peer connection.
617    /// If validation fails (e.g., expired certificates, invalid ICE servers),
618    /// an error is returned.
619    ///
620    /// # Errors
621    ///
622    /// Returns an error if:
623    /// - Certificates have expired
624    /// - ICE server URLs are invalid
625    /// - Other validation checks fail
626    ///
627    /// # Examples
628    ///
629    /// ```
630    /// # use std::time::Instant;
631    /// use rtc::peer_connection::RTCPeerConnectionBuilder;
632    ///
633    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
634    /// let pc = RTCPeerConnectionBuilder::new().build(Instant::now())?;
635    /// # Ok(())
636    /// # }
637    /// ```
638    pub fn build(self, now: Instant) -> Result<RTCPeerConnection> {
639        RTCPeerConnection::new(
640            now,
641            self.configuration,
642            self.media_engine,
643            self.setting_engine,
644            // The registry is a list until here; `build` freezes it into the chain.
645            Box::new(self.interceptor_registry.build()),
646        )
647    }
648}
649
650/// The `RTCPeerConnection` interface represents a WebRTC connection between the local computer
651/// and a remote peer. It provides methods to connect to a remote peer, maintain and monitor
652/// the connection, and close the connection once it's no longer needed.
653///
654/// This is a sans-I/O implementation following the [W3C WebRTC specification](https://www.w3.org/TR/webrtc/).
655///
656/// # Driving the connection
657///
658/// This type performs **no I/O and reads no clock**. It never opens a socket, never sleeps, and
659/// never calls `Instant::now()` on your behalf: every method that needs the time takes it as an
660/// argument. Progress happens only when you feed it something. That is what makes a whole
661/// session reproducible in a test with no socket and no sleep.
662///
663/// The driving methods come from the [`sansio::Protocol`] trait, so **the trait must be in scope**
664/// (`use rtc::sansio::Protocol;`) or none of them will resolve:
665///
666/// | Method | Direction | What it does |
667/// | --- | --- | --- |
668/// | [`handle_read`] | in | Feed one received datagram, tagged with its 5-tuple and arrival instant |
669/// | [`poll_write`] | out | Take the next packet to put on the wire; drain until `None` |
670/// | [`poll_read`] | out | Take the next inbound RTP/RTCP/data-channel message for the application |
671/// | [`poll_event`] | out | Take the next state change or notification |
672/// | [`poll_timeout`] | out | Next deadline for retransmissions, keepalives and ICE checks |
673/// | [`handle_timeout`] | in | Report that a deadline has passed |
674/// | [`handle_write`] | in | Queue an outbound RTP/RTCP/data-channel message |
675/// | [`close`] | in | Shut the connection down |
676///
677/// Nothing is sent eagerly: `handle_read`, `handle_timeout`, `handle_write` and the negotiation
678/// methods all *queue* packets, so drain `poll_write` after any of them.
679///
680/// [`handle_event`] also exists on the trait, but [`RTCEvent`] is uninhabited — no value of it can
681/// be constructed, so there is nothing to call it with. It reserves the signature for the first
682/// inbound event variant.
683///
684/// # Back-pressure
685///
686/// [`poll_read`] is the throttle. Undrained data-channel messages leave bytes in SCTP's reassembly
687/// queue, which lowers the receiver-window credit advertised in every SACK, which tells the peer to
688/// slow down. **Declining to call `poll_read` is how back-pressure is applied**; resume when the
689/// application catches up. Media is never throttled this way: RTP arrives over SRTP and is subject
690/// to none of SCTP's flow control, and `poll_read` interleaves the two by the instant each packet
691/// was observed, so a stalled data channel cannot starve video.
692///
693/// # ICE candidates
694///
695/// Because there is no I/O here, there is no candidate gathering either: the application owns the
696/// sockets, so it owns gathering. Hand every local candidate to [`Self::add_local_candidate`], and
697/// finish with an empty candidate string to signal end-of-gathering — see that method for the
698/// details.
699///
700/// # Examples
701///
702/// ```
703/// # use std::time::Instant;
704/// use rtc::peer_connection::RTCPeerConnectionBuilder;
705///
706/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
707/// let mut pc = RTCPeerConnectionBuilder::new().build(Instant::now())?;
708/// # Ok(())
709/// # }
710/// ```
711///
712/// A complete event loop is shown in the [crate-level documentation](crate).
713///
714/// [`sansio::Protocol`]: sansio::Protocol
715/// [`handle_read`]: sansio::Protocol::handle_read
716/// [`poll_write`]: sansio::Protocol::poll_write
717/// [`poll_read`]: sansio::Protocol::poll_read
718/// [`poll_event`]: sansio::Protocol::poll_event
719/// [`poll_timeout`]: sansio::Protocol::poll_timeout
720/// [`handle_timeout`]: sansio::Protocol::handle_timeout
721/// [`handle_write`]: sansio::Protocol::handle_write
722/// [`handle_event`]: sansio::Protocol::handle_event
723/// [`close`]: sansio::Protocol::close
724/// [`RTCEvent`]: crate::peer_connection::event::RTCEvent
725pub struct RTCPeerConnection {
726    //////////////////////////////////////////////////
727    // PeerConnection WebRTC Spec Interface Definition
728    //////////////////////////////////////////////////
729    pub(crate) configuration: RTCConfiguration,
730    pub(crate) media_engine: MediaEngine,
731    pub(crate) setting_engine: SettingEngine,
732    pub(crate) interceptor: Box<dyn Interceptor>,
733
734    local_description: Option<RTCSessionDescription>,
735    current_local_description: Option<RTCSessionDescription>,
736    pending_local_description: Option<RTCSessionDescription>,
737    remote_description: Option<RTCSessionDescription>,
738    current_remote_description: Option<RTCSessionDescription>,
739    pending_remote_description: Option<RTCSessionDescription>,
740
741    pub(crate) signaling_state: RTCSignalingState,
742    pub(crate) peer_connection_state: RTCPeerConnectionState,
743    can_trickle_ice_candidates: Option<bool>,
744
745    //////////////////////////////////////////////////
746    // PeerConnection Internal State Machine
747    //////////////////////////////////////////////////
748    pub(crate) pipeline_context: PipelineContext,
749    pub(crate) data_channels: DataChannelRegistry,
750    pub(super) rtp_transceivers: Vec<RTCRtpTransceiverInternal>,
751
752    greater_mid: isize,
753    sdp_origin: Origin,
754    last_offer: String,
755    last_answer: String,
756
757    ice_restart_requested: Option<RTCOfferOptions>,
758    negotiation_needed_state: NegotiationNeededState,
759    is_negotiation_ongoing: bool,
760}
761
762impl RTCPeerConnection {
763    /// Creates an SDP offer to start a new WebRTC connection to a remote peer.
764    ///
765    /// The offer includes information about the attached media tracks, codecs and options supported
766    /// by the browser, and ICE candidates gathered by the ICE agent. This offer can be sent to a
767    /// remote peer over a signaling channel to establish a connection.
768    ///
769    /// # Parameters
770    ///
771    /// * `options` - Optional configuration for the offer, such as whether to restart ICE.
772    ///
773    /// # Returns
774    ///
775    /// Returns an `RTCSessionDescription` containing the SDP offer.
776    ///
777    /// # Errors
778    ///
779    /// Returns an error if:
780    /// - The peer connection is closed
781    /// - There's an error generating the SDP
782    ///
783    /// # Specification
784    ///
785    /// See [createOffer](https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-createoffer)
786    pub fn create_offer(
787        &mut self,
788        mut options: Option<RTCOfferOptions>,
789    ) -> Result<RTCSessionDescription> {
790        if self.peer_connection_state == RTCPeerConnectionState::Closed {
791            return Err(Error::ErrConnectionClosed);
792        }
793
794        // Staging, not restarting: the offer must advertise fresh ICE credentials, but JSEP
795        // requires `createOffer` to be free of side effects, and inbound STUN is still being
796        // validated against the current ufrag/pwd. `set_local_description` applies the restart.
797        let is_ice_restart_requested = self
798            .ice_restart_requested
799            .take()
800            .is_some_and(|options| options.ice_restart)
801            || options.take().is_some_and(|options| options.ice_restart);
802
803        if is_ice_restart_requested {
804            self.stage_ice_restart()?;
805        }
806
807        // include unmatched local transceivers
808        // update the greater mid if the remote description provides a greater one
809        if let Some(d) = self.current_remote_description.as_ref()
810            && let Some(parsed) = &d.parsed
811        {
812            for media in &parsed.media_descriptions {
813                if let Some(mid) = get_mid_value(media) {
814                    if mid.is_empty() {
815                        continue;
816                    }
817                    let numeric_mid = match mid.parse::<isize>() {
818                        Ok(n) => n,
819                        Err(_) => continue,
820                    };
821                    if numeric_mid > self.greater_mid {
822                        self.greater_mid = numeric_mid;
823                    }
824                }
825            }
826        }
827        for transceiver in &mut self.rtp_transceivers {
828            if let Some(mid) = transceiver.mid()
829                && !mid.is_empty()
830            {
831                if let Ok(numeric_mid) = mid.parse::<isize>()
832                    && numeric_mid > self.greater_mid
833                {
834                    self.greater_mid = numeric_mid;
835                }
836            } else {
837                self.greater_mid += 1;
838                transceiver.set_mid(format!("{}", self.greater_mid))?;
839            }
840        }
841
842        let mut d = if self.current_remote_description.is_none() {
843            self.generate_unmatched_sdp()?
844        } else {
845            self.generate_matched_sdp(
846                true, /*includeUnmatched */
847                DEFAULT_DTLS_ROLE_OFFER.to_connection_role(),
848                false,
849            )?
850        };
851
852        update_sdp_origin(&mut self.sdp_origin, &mut d);
853
854        let sdp = d.marshal();
855
856        let offer = RTCSessionDescription {
857            sdp_type: RTCSdpType::Offer,
858            sdp,
859            parsed: Some(d),
860        };
861
862        self.last_offer.clone_from(&offer.sdp);
863
864        Ok(offer)
865    }
866
867    /// Creates an SDP answer in response to an offer from a remote peer.
868    ///
869    /// This method must be called after `set_remote_description()` has been called
870    /// with an offer. The answer describes which media formats and codecs this peer
871    /// will accept and how the connection will be established.
872    ///
873    /// # Parameters
874    ///
875    /// - `options`: Optional answer configuration. Currently not used but reserved
876    ///   for future extensions.
877    ///
878    /// # Returns
879    ///
880    /// Returns an `RTCSessionDescription` containing the SDP answer that should be
881    /// set as the local description and sent to the remote peer.
882    ///
883    /// # Errors
884    ///
885    /// Returns an error if:
886    /// - No remote description has been set (`ErrNoRemoteDescription`)
887    /// - The peer connection is closed (`ErrConnectionClosed`)
888    /// - The signaling state is incorrect (`ErrIncorrectSignalingState`)
889    /// - SDP generation fails
890    ///
891    /// # Signaling State Requirements
892    ///
893    /// This method can only be called when the signaling state is:
894    /// - `HaveRemoteOffer` - After receiving an initial offer
895    /// - `HaveLocalPranswer` - After sending a provisional answer
896    ///
897    /// # Examples
898    ///
899    /// ## Basic Answer Flow
900    ///
901    /// ```no_run
902    /// # use std::time::Instant;
903    /// use rtc::peer_connection::RTCPeerConnectionBuilder;
904    /// use rtc::peer_connection::sdp::RTCSessionDescription;
905    ///
906    /// # fn example(remote_offer_sdp: String) -> Result<(), Box<dyn std::error::Error>> {
907    /// let mut pc = RTCPeerConnectionBuilder::new().build(Instant::now())?;
908    ///
909    /// // 1. Receive and set remote offer
910    /// let offer = RTCSessionDescription::offer(remote_offer_sdp)?;
911    /// pc.set_remote_description(Instant::now(), offer)?;
912    ///
913    /// // 2. Create answer
914    /// let answer = pc.create_answer(None)?;
915    ///
916    /// // 3. Set as local description
917    /// pc.set_local_description(Instant::now(), answer.clone())?;
918    ///
919    /// // 4. Send answer to remote peer
920    /// // signaling_channel.send(answer.sdp)?;
921    /// # Ok(())
922    /// # }
923    /// ```
924    ///
925    /// ## With Media Tracks
926    ///
927    /// ```no_run
928    /// # use std::time::Instant;
929    /// use rtc::peer_connection::RTCPeerConnectionBuilder;
930    /// use rtc::peer_connection::sdp::RTCSessionDescription;
931    /// use rtc::media_stream::MediaStreamTrack;
932    ///
933    /// # fn example(
934    /// #     remote_offer_sdp: String,
935    /// #     audio_track: MediaStreamTrack,
936    /// # ) -> Result<(), Box<dyn std::error::Error>> {
937    /// let mut pc = RTCPeerConnectionBuilder::new().build(Instant::now())?;
938    ///
939    /// // Set remote offer
940    /// let offer = RTCSessionDescription::offer(remote_offer_sdp)?;
941    /// pc.set_remote_description(Instant::now(), offer)?;
942    ///
943    /// // Add local track before creating answer
944    /// pc.add_track(audio_track)?;
945    ///
946    /// // Create answer (will include the track)
947    /// let answer = pc.create_answer(None)?;
948    /// pc.set_local_description(Instant::now(), answer)?;
949    /// # Ok(())
950    /// # }
951    /// ```
952    ///
953    /// # DTLS Role Selection
954    ///
955    /// The answer automatically determines the appropriate DTLS role:
956    /// - Uses `answering_dtls_role` from settings if configured
957    /// - Defaults to `Client` (active) for lower latency
958    /// - Uses `Server` (passive) if remote is ICE-Lite
959    ///
960    /// # Specification
961    ///
962    /// - [W3C RTCPeerConnection.createAnswer]
963    /// - [RFC 9429 Section 5.3] - Generating an Answer
964    ///
965    /// [W3C RTCPeerConnection.createAnswer]: https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-createanswer
966    /// [RFC 9429 Section 5.3]: https://datatracker.ietf.org/doc/html/rfc9429#section-5.3
967    pub fn create_answer(
968        &mut self,
969        _options: Option<RTCAnswerOptions>,
970    ) -> Result<RTCSessionDescription> {
971        if self.remote_description().is_none() {
972            return Err(Error::ErrNoRemoteDescription);
973        }
974
975        if self.peer_connection_state == RTCPeerConnectionState::Closed {
976            return Err(Error::ErrConnectionClosed);
977        }
978
979        if self.signaling_state != RTCSignalingState::HaveRemoteOffer
980            && self.signaling_state != RTCSignalingState::HaveLocalPranswer
981        {
982            return Err(Error::ErrIncorrectSignalingState);
983        }
984
985        let mut connection_role = self.setting_engine.answering_dtls_role.to_connection_role();
986        // RFC 5763 §5: "The answerer MUST use either a setup attribute value of setup:active or
987        // setup:passive." `actpass` is an offer-only value, so an answering role of
988        // `RTCDtlsRole::Auto` — which maps to it — means "no preference" and has to be resolved
989        // to a concrete role here, exactly like `Unspecified`.
990        //
991        // Letting `actpass` through leaves the role genuinely unnegotiated: the answerer falls
992        // back to its own `answering_dtls_role`, and the offerer, seeing no explicit role in the
993        // answer, falls back to *its* configured role. When those agree — e.g. an offerer pinned
994        // to `Client` answered by a peer configured `Auto` — both endpoints become the DTLS
995        // client, both wait for a ClientHello, and the handshake never completes.
996        if matches!(
997            connection_role,
998            ConnectionRole::Unspecified | ConnectionRole::Actpass
999        ) {
1000            connection_role = DEFAULT_DTLS_ROLE_ANSWER.to_connection_role();
1001
1002            if let Some(remote_description) = self.remote_description()
1003                && let Some(parsed) = remote_description.parsed.as_ref()
1004                && is_lite_set(parsed)
1005                && !self.setting_engine.candidates.ice_lite
1006            {
1007                connection_role = RTCDtlsRole::Server.to_connection_role();
1008            }
1009        }
1010
1011        let mut d = self.generate_matched_sdp(
1012            false, /*includeUnmatched */
1013            connection_role,
1014            self.setting_engine.ignore_rid_pause_for_recv,
1015        )?;
1016
1017        update_sdp_origin(&mut self.sdp_origin, &mut d);
1018
1019        let sdp = d.marshal();
1020
1021        let answer = RTCSessionDescription {
1022            sdp_type: RTCSdpType::Answer,
1023            sdp,
1024            parsed: Some(d),
1025        };
1026
1027        self.last_answer.clone_from(&answer.sdp);
1028
1029        Ok(answer)
1030    }
1031
1032    /// Sets the local description for this peer connection.
1033    ///
1034    /// This method applies a local SDP description (offer or answer) to the peer
1035    /// connection, updating the local media and transport configuration. It must be
1036    /// called after creating an offer or answer.
1037    ///
1038    /// # Parameters
1039    ///
1040    /// - `local_description`: The session description to set as the local description.
1041    ///   This should be an offer or answer created by `create_offer()` or `create_answer()`.
1042    ///
1043    /// # Returns
1044    ///
1045    /// Returns `Ok(())` on success.
1046    ///
1047    /// # Errors
1048    ///
1049    /// Returns an error if:
1050    /// - The peer connection is closed (`ErrConnectionClosed`)
1051    /// - The SDP type is invalid for the current signaling state
1052    /// - SDP parsing fails
1053    /// - Transport configuration fails
1054    ///
1055    /// # Signaling State Transitions
1056    ///
1057    /// Setting the local description causes signaling state transitions:
1058    ///
1059    /// - **Offer**: `Stable` → `HaveLocalOffer`
1060    /// - **Answer**: `HaveRemoteOffer` → `Stable`
1061    /// - **Pranswer**: `HaveRemoteOffer` → `HaveLocalPranswer`
1062    ///
1063    /// # Examples
1064    ///
1065    /// ## Setting Local Offer
1066    ///
1067    /// ```no_run
1068    /// # use std::time::Instant;
1069    /// use rtc::peer_connection::RTCPeerConnectionBuilder;
1070    ///
1071    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
1072    /// let mut pc = RTCPeerConnectionBuilder::new().build(Instant::now())?;
1073    ///
1074    /// // Create offer
1075    /// let offer = pc.create_offer(None)?;
1076    ///
1077    /// // Set as local description
1078    /// pc.set_local_description(Instant::now(), offer.clone())?;
1079    ///
1080    /// // Now send offer.sdp to remote peer via signaling
1081    /// // signaling_channel.send(offer.sdp)?;
1082    /// # Ok(())
1083    /// # }
1084    /// ```
1085    ///
1086    /// ## Setting Local Answer
1087    ///
1088    /// ```no_run
1089    /// # use std::time::Instant;
1090    /// use rtc::peer_connection::RTCPeerConnectionBuilder;
1091    /// use rtc::peer_connection::sdp::RTCSessionDescription;
1092    ///
1093    /// # fn example(remote_offer_sdp: String) -> Result<(), Box<dyn std::error::Error>> {
1094    /// let mut pc = RTCPeerConnectionBuilder::new().build(Instant::now())?;
1095    ///
1096    /// // Set remote offer first
1097    /// let offer = RTCSessionDescription::offer(remote_offer_sdp)?;
1098    /// pc.set_remote_description(Instant::now(), offer)?;
1099    ///
1100    /// // Create and set local answer
1101    /// let answer = pc.create_answer(None)?;
1102    /// pc.set_local_description(Instant::now(), answer.clone())?;
1103    ///
1104    /// // Send answer to remote peer
1105    /// // signaling_channel.send(answer.sdp)?;
1106    /// # Ok(())
1107    /// # }
1108    /// ```
1109    ///
1110    /// # Empty SDP Handling (JSEP 5.4)
1111    ///
1112    /// If the SDP string is empty, the last offer or answer is reused:
1113    /// - For offers: Uses the last generated offer
1114    /// - For answers: Uses the last generated answer
1115    ///
1116    /// This allows re-applying descriptions without regenerating SDP.
1117    ///
1118    /// # Media and Transport Activation
1119    ///
1120    /// When setting a local answer:
1121    /// - RTP transceivers are activated
1122    /// - SCTP transport is started for data channels
1123    /// - Media can begin flowing
1124    ///
1125    /// # Specification
1126    ///
1127    /// - [W3C RTCPeerConnection.setLocalDescription]
1128    /// - [RFC 9429 Section 5.9] - Applying a Local Description
1129    ///
1130    /// [W3C RTCPeerConnection.setLocalDescription]: https://www.w3.org/TR/webrtc/#dom-peerconnection-setlocaldescription
1131    /// [RFC 9429 Section 5.9]: https://datatracker.ietf.org/doc/html/rfc9429#section-5.9
1132    pub fn set_local_description(
1133        &mut self,
1134        now: Instant,
1135        mut local_description: RTCSessionDescription,
1136    ) -> Result<()> {
1137        if self.peer_connection_state == RTCPeerConnectionState::Closed {
1138            return Err(Error::ErrConnectionClosed);
1139        }
1140
1141        // Apply an ICE restart staged by `create_offer`. A no-op if none was staged, so an offer
1142        // that was created and then discarded leaves the existing session untouched.
1143        if self.ice_transport().has_pending_restart() {
1144            self.apply_ice_restart(now)?;
1145        }
1146
1147        // JSEP 5.4
1148        if local_description.sdp.is_empty() {
1149            match local_description.sdp_type {
1150                RTCSdpType::Answer | RTCSdpType::Pranswer => {
1151                    local_description.sdp.clone_from(&self.last_answer);
1152                }
1153                RTCSdpType::Offer => {
1154                    local_description.sdp.clone_from(&self.last_offer);
1155                }
1156                RTCSdpType::Rollback => {
1157                    // WebRTC spec: rollback SDP is ignored, empty is allowed
1158                }
1159                _ => return Err(Error::ErrPeerConnSDPTypeInvalidValueSetLocalDescription),
1160            }
1161        }
1162
1163        // Parse SDP (skip for rollback as content is ignored per spec)
1164        if local_description.sdp_type != RTCSdpType::Rollback {
1165            local_description.parsed = Some(local_description.unmarshal()?);
1166        }
1167        self.set_description(&local_description, StateChangeOp::SetLocal)?;
1168
1169        let we_answer = local_description.sdp_type == RTCSdpType::Answer;
1170        if we_answer && let Some(parsed_local_description) = &local_description.parsed {
1171            // WebRTC Spec 1.0 https://www.w3.org/TR/webrtc/
1172            // Section 4.4.1.5
1173            for media in &parsed_local_description.media_descriptions {
1174                let mid_value = match get_mid_value(media) {
1175                    Some(mid) if !mid.is_empty() => mid,
1176                    _ => return Err(Error::ErrPeerConnLocalDescriptionWithoutMidValue),
1177                };
1178
1179                if media.is_webrtc_datachannel() {
1180                    continue;
1181                }
1182
1183                let i = match RTCPeerConnection::find_by_mid(mid_value, &self.rtp_transceivers) {
1184                    Some(i) => i,
1185                    None => return Err(Error::ErrPeerConnTransceiverMidNil),
1186                };
1187
1188                let kind = RtpCodecKind::from(media.media_name.media.as_str());
1189                let mut direction = get_peer_direction(media);
1190                if kind == RtpCodecKind::Unspecified
1191                    || direction == RTCRtpTransceiverDirection::Unspecified
1192                {
1193                    continue;
1194                }
1195
1196                // If a transceiver is created by applying a remote description that has recvonly transceiver,
1197                // it will have no sender. In this case, the transceiver's current direction is set to inactive so
1198                // that the transceiver can be reused by next AddTrack.
1199                if direction == RTCRtpTransceiverDirection::Sendonly
1200                    && self.rtp_transceivers[i].sender().is_none()
1201                {
1202                    direction = RTCRtpTransceiverDirection::Inactive;
1203                }
1204
1205                self.rtp_transceivers[i].set_current_direction(direction);
1206            }
1207
1208            if let Some(remote_description) = self.remote_description().cloned()
1209                && let Some(parsed_remote_description) = remote_description.parsed.as_ref()
1210            {
1211                // only start sctp transport if application media has been negotiated
1212                if let (Some(local_application_media), Some(remote_application_media)) = (
1213                    get_application_media(parsed_local_description),
1214                    get_application_media(parsed_remote_description),
1215                ) {
1216                    let (dtls_role, remote_caps, local_sctp_port, remote_sctp_port) = (
1217                        self.dtls_transport().role(),
1218                        SCTPTransportCapabilities {
1219                            max_message_size: get_application_media_section_max_message_size(
1220                                remote_application_media,
1221                            )
1222                            .unwrap_or(SctpMaxMessageSize::DEFAULT_MESSAGE_SIZE),
1223                        },
1224                        get_application_media_section_sctp_port(local_application_media)
1225                            .unwrap_or(5000),
1226                        get_application_media_section_sctp_port(remote_application_media)
1227                            .unwrap_or(5000),
1228                    );
1229
1230                    // we_answer: we first call set_remote_description,
1231                    // then, we create_answer() and set_local_description() here
1232                    // Now we should have done SDP negotiation.
1233                    // Therefore, it is ready to start sctp and rtp.
1234                    self.sctp_transport_mut().start(
1235                        dtls_role,
1236                        remote_caps,
1237                        local_sctp_port,
1238                        remote_sctp_port,
1239                    )?;
1240                }
1241                self.start_rtp(remote_description)?;
1242            }
1243        }
1244
1245        self.ice_transport_mut().ice_gathering_state = RTCIceGatheringState::Gathering;
1246
1247        Ok(())
1248    }
1249
1250    /// Returns the local session description.
1251    ///
1252    /// Returns `pending_local_description` if it is not null, otherwise returns
1253    /// `current_local_description`. This property is used to determine if
1254    /// `set_local_description` has already been called.
1255    ///
1256    /// # Specification
1257    ///
1258    /// See [localDescription](https://www.w3.org/TR/webrtc/#dom-peerconnection-localdescription)
1259    pub fn local_description(&self) -> Option<RTCSessionDescription> {
1260        if let Some(pending_local_description) = self.pending_local_description() {
1261            return Some(pending_local_description);
1262        }
1263        self.current_local_description()
1264    }
1265
1266    /// Returns the current local description as last successfully negotiated since
1267    /// the last negotiation completed.
1268    ///
1269    /// This represents the local description from the last offer/answer exchange that was
1270    /// successfully applied, not including any offers currently being negotiated.
1271    ///
1272    /// Returns `None` if there is no current local description (e.g., before initial negotiation).
1273    ///
1274    /// # Specification
1275    ///
1276    /// See [currentLocalDescription](https://www.w3.org/TR/webrtc/#dom-peerconnection-currentlocaldesc)
1277    pub fn current_local_description(&self) -> Option<RTCSessionDescription> {
1278        self.populate_local_candidates(self.current_local_description.as_ref())
1279    }
1280
1281    /// Returns the pending local description if it exists.
1282    ///
1283    /// This represents the local description from a call to `set_local_description()` whose
1284    /// corresponding remote description has not yet been applied. This is `None` if negotiation
1285    /// is not in progress or if a rollback has been performed.
1286    ///
1287    /// Returns `None` if there is no pending local description.
1288    ///
1289    /// # Specification
1290    ///
1291    /// See [pendingLocalDescription](https://www.w3.org/TR/webrtc/#dom-peerconnection-pendinglocaldesc)
1292    pub fn pending_local_description(&self) -> Option<RTCSessionDescription> {
1293        self.populate_local_candidates(self.pending_local_description.as_ref())
1294    }
1295
1296    /// Returns whether the remote peer supports trickle ICE.
1297    ///
1298    /// This value is determined from the remote SDP description after `set_remote_description()`
1299    /// is called. It checks for "trickle" in the "ice-options" attribute per
1300    /// RFC 8838 and RFC 9429 section 4.1.17.
1301    ///
1302    /// Returns:
1303    /// - `None` if no remote description has been set yet (unknown)
1304    /// - `Some(true)` if the remote peer indicated trickle ICE support
1305    /// - `Some(false)` if the remote peer did not indicate support
1306    ///
1307    /// # Specification
1308    ///
1309    /// See [canTrickleIceCandidates](https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-cantrickleicecandidates)
1310    pub fn can_trickle_ice_candidates(&self) -> Option<bool> {
1311        self.can_trickle_ice_candidates
1312    }
1313
1314    /// Sets the remote description as part of the offer/answer negotiation.
1315    ///
1316    /// This changes the remote description associated with the connection. This description
1317    /// specifies the properties of the remote end of the connection, including the media format.
1318    ///
1319    /// # Parameters
1320    ///
1321    /// * `remote_description` - The remote session description to set.
1322    ///
1323    /// # Errors
1324    ///
1325    /// Returns an error if:
1326    /// - The peer connection is closed
1327    /// - The SDP cannot be parsed
1328    /// - The media engine fails to update from the remote description
1329    ///
1330    /// # Specification
1331    ///
1332    /// See [setRemoteDescription](https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-setremotedescription!overload-1)
1333    pub fn set_remote_description(
1334        &mut self,
1335        now: Instant,
1336        mut remote_description: RTCSessionDescription,
1337    ) -> Result<()> {
1338        if self.peer_connection_state == RTCPeerConnectionState::Closed {
1339            return Err(Error::ErrConnectionClosed);
1340        }
1341
1342        let is_renegotiation = self.current_remote_description.is_some();
1343
1344        // Parse SDP (skip for rollback as content is ignored per spec)
1345        if remote_description.sdp_type != RTCSdpType::Rollback {
1346            remote_description.parsed = Some(remote_description.unmarshal()?);
1347        }
1348        self.set_description(&remote_description, StateChangeOp::SetRemote)?;
1349
1350        if let Some(parsed_remote_description) = &remote_description.parsed {
1351            self.media_engine
1352                .update_from_remote_description(parsed_remote_description)?;
1353
1354            // Detect trickle ICE support from remote SDP (RFC 8838/RFC 9429 section 4.1.17)
1355            // Check for "trickle" in space-separated "ice-options" attribute values
1356            let has_trickle_ice = has_ice_trickle_option(parsed_remote_description);
1357
1358            match remote_description.sdp_type {
1359                RTCSdpType::Offer | RTCSdpType::Answer | RTCSdpType::Pranswer => {
1360                    self.can_trickle_ice_candidates = Some(has_trickle_ice);
1361                }
1362                _ => {
1363                    // Rollback or other types: reset to unknown
1364                    self.can_trickle_ice_candidates = None;
1365                }
1366            }
1367
1368            // Disable RTX/FEC on RTPSenders if the remote didn't support it
1369            for transceiver in &mut self.rtp_transceivers {
1370                if let Some(sender) = transceiver.sender_mut() {
1371                    let (is_rtx_enabled, is_fec_enabled) = (
1372                        self.media_engine
1373                            .is_rtx_enabled(sender.kind(), RTCRtpTransceiverDirection::Sendonly),
1374                        self.media_engine
1375                            .is_fec_enabled(sender.kind(), RTCRtpTransceiverDirection::Sendonly),
1376                    );
1377                    sender.configure_rtx_and_fec(is_rtx_enabled, is_fec_enabled);
1378                }
1379            }
1380
1381            let we_offer = remote_description.sdp_type == RTCSdpType::Answer;
1382
1383            // Extract media descriptions to avoid borrowing conflicts
1384            let media_descriptions = self
1385                .remote_description()
1386                .as_ref()
1387                .and_then(|r| r.parsed.as_ref())
1388                .map(|parsed| parsed.media_descriptions.clone());
1389
1390            if let Some(media_descriptions) = media_descriptions {
1391                if !we_offer {
1392                    for media in &media_descriptions {
1393                        let mid_value = match get_mid_value(media) {
1394                            Some(mid) if !mid.is_empty() => mid,
1395                            _ => return Err(Error::ErrPeerConnRemoteDescriptionWithoutMidValue),
1396                        };
1397
1398                        if media.is_webrtc_datachannel() {
1399                            continue;
1400                        }
1401
1402                        let kind = RtpCodecKind::from(media.media_name.media.as_str());
1403                        let direction = get_peer_direction(media);
1404                        if kind == RtpCodecKind::Unspecified
1405                            || direction == RTCRtpTransceiverDirection::Unspecified
1406                        {
1407                            continue;
1408                        }
1409
1410                        let transceiver = if let Some(i) =
1411                            RTCPeerConnection::find_by_mid(mid_value, &self.rtp_transceivers)
1412                        {
1413                            if direction == RTCRtpTransceiverDirection::Inactive {
1414                                self.rtp_transceivers[i]
1415                                    .stop(&self.media_engine, &mut self.interceptor)?;
1416                            }
1417                            Some(&mut self.rtp_transceivers[i])
1418                        } else {
1419                            RTCPeerConnection::satisfy_type_and_direction(
1420                                kind,
1421                                direction,
1422                                &mut self.rtp_transceivers,
1423                            )
1424                        };
1425
1426                        if let Some(transceiver) = transceiver {
1427                            if direction == RTCRtpTransceiverDirection::Recvonly {
1428                                if transceiver.direction() == RTCRtpTransceiverDirection::Sendrecv {
1429                                    transceiver.set_direction(RTCRtpTransceiverDirection::Sendonly);
1430                                } else if transceiver.direction()
1431                                    == RTCRtpTransceiverDirection::Recvonly
1432                                {
1433                                    transceiver.set_direction(RTCRtpTransceiverDirection::Inactive);
1434                                }
1435                            } else if direction == RTCRtpTransceiverDirection::Sendrecv {
1436                                if transceiver.direction() == RTCRtpTransceiverDirection::Sendonly {
1437                                    transceiver.set_direction(RTCRtpTransceiverDirection::Sendrecv);
1438                                } else if transceiver.direction()
1439                                    == RTCRtpTransceiverDirection::Inactive
1440                                {
1441                                    transceiver.set_direction(RTCRtpTransceiverDirection::Recvonly);
1442                                }
1443                            } else if direction == RTCRtpTransceiverDirection::Sendonly
1444                                && transceiver.direction() == RTCRtpTransceiverDirection::Inactive
1445                            {
1446                                transceiver.set_direction(RTCRtpTransceiverDirection::Recvonly);
1447                            }
1448
1449                            transceiver.set_codec_preferences_from_remote_description(
1450                                media,
1451                                &self.media_engine,
1452                            )?;
1453
1454                            if transceiver.mid().is_none() {
1455                                transceiver.set_mid(mid_value.to_string())?;
1456                            }
1457                        } else {
1458                            let local_direction =
1459                                if direction == RTCRtpTransceiverDirection::Recvonly {
1460                                    RTCRtpTransceiverDirection::Sendonly
1461                                } else {
1462                                    RTCRtpTransceiverDirection::Recvonly
1463                                };
1464
1465                            let mut transceiver = RTCRtpTransceiverInternal::new(
1466                                kind,
1467                                None,
1468                                RTCRtpTransceiverInit {
1469                                    direction: local_direction,
1470                                    streams: vec![],
1471                                    send_encodings: vec![],
1472                                },
1473                            );
1474
1475                            transceiver.set_codec_preferences_from_remote_description(
1476                                media,
1477                                &self.media_engine,
1478                            )?;
1479
1480                            if transceiver.mid().is_none() {
1481                                transceiver.set_mid(mid_value.to_string())?;
1482                            }
1483
1484                            // Mark as implicitly created by a remote offer so that, if this offer
1485                            // is later rolled back, the transceiver is stopped and removed
1486                            // (RFC 9429, Section 5.7) — unless a track is attached via add_track.
1487                            transceiver.set_created_by_remote_description(true);
1488
1489                            self.add_rtp_transceiver(transceiver);
1490                        }
1491                    }
1492                } else {
1493                    // we_offer
1494                    // WebRTC Spec 1.0 https://www.w3.org/TR/webrtc/
1495                    // 4.5.9.2
1496                    // This is an answer from the remote.
1497                    for media in &media_descriptions {
1498                        let mid_value = match get_mid_value(media) {
1499                            Some(mid) if !mid.is_empty() => mid,
1500                            _ => return Err(Error::ErrPeerConnRemoteDescriptionWithoutMidValue),
1501                        };
1502
1503                        if media.is_webrtc_datachannel() {
1504                            continue;
1505                        }
1506
1507                        let kind = RtpCodecKind::from(media.media_name.media.as_str());
1508                        let mut direction = get_peer_direction(media);
1509                        if kind == RtpCodecKind::Unspecified
1510                            || direction == RTCRtpTransceiverDirection::Unspecified
1511                        {
1512                            continue;
1513                        }
1514
1515                        let transceiver = if let Some(i) =
1516                            RTCPeerConnection::find_by_mid(mid_value, &self.rtp_transceivers)
1517                        {
1518                            &mut self.rtp_transceivers[i]
1519                        } else {
1520                            return Err(Error::ErrPeerConnTransceiverMidNil);
1521                        };
1522
1523                        // reverse direction if it was a remote answer
1524                        if direction == RTCRtpTransceiverDirection::Sendonly {
1525                            direction = RTCRtpTransceiverDirection::Recvonly;
1526                        } else if direction == RTCRtpTransceiverDirection::Recvonly {
1527                            direction = RTCRtpTransceiverDirection::Sendonly;
1528                        }
1529
1530                        transceiver.set_current_direction(direction);
1531
1532                        transceiver.set_codec_preferences_from_remote_description(
1533                            media,
1534                            &self.media_engine,
1535                        )?;
1536                    }
1537                }
1538            }
1539
1540            let (remote_ufrag, remote_pwd, candidates) =
1541                extract_ice_details(parsed_remote_description)?;
1542
1543            if is_renegotiation
1544                && self
1545                    .ice_transport()
1546                    .have_remote_credentials_change(&remote_ufrag, &remote_pwd)
1547            {
1548                // An ICE Restart only happens implicitly for a set_remote_description of type offer
1549
1550                if !we_offer {
1551                    // The answerer restarts in one step: it has `now`, and the answer it generates
1552                    // next must already carry the new local credentials.
1553                    self.stage_ice_restart()?;
1554                    self.apply_ice_restart(now)?;
1555                }
1556
1557                self.ice_transport_mut()
1558                    .set_remote_credentials(remote_ufrag.clone(), remote_pwd.clone())?;
1559            }
1560
1561            for candidate in candidates {
1562                self.ice_transport_mut().add_remote_candidate(candidate)?;
1563            }
1564
1565            if !is_renegotiation {
1566                let remote_is_lite = is_lite_set(parsed_remote_description);
1567
1568                let (remote_fingerprint, remote_fingerprint_hash) =
1569                    extract_fingerprint(parsed_remote_description)?;
1570
1571                // If one of the agents is lite and the other one is not, the lite agent must be the controlling agent.
1572                // If both or neither agents are lite the offering agent is controlling.
1573                // RFC 8445 S6.1.1
1574                let local_ice_role = if (we_offer
1575                    && remote_is_lite == self.setting_engine.candidates.ice_lite)
1576                    || (remote_is_lite && !self.setting_engine.candidates.ice_lite)
1577                {
1578                    RTCIceRole::Controlling
1579                } else {
1580                    RTCIceRole::Controlled
1581                };
1582
1583                let remote_dtls_role = RTCDtlsRole::from(parsed_remote_description);
1584                log::trace!(
1585                    "start_transports: local_ice_role={local_ice_role}, remote_dtls_role={remote_dtls_role}"
1586                );
1587
1588                self.start_transports(
1589                    now,
1590                    local_ice_role,
1591                    RTCIceParameters {
1592                        username_fragment: remote_ufrag,
1593                        password: remote_pwd,
1594                        ice_lite: remote_is_lite,
1595                    },
1596                    RTCDtlsParameters {
1597                        role: remote_dtls_role,
1598                        fingerprints: vec![RTCDtlsFingerprint {
1599                            algorithm: remote_fingerprint_hash,
1600                            value: remote_fingerprint,
1601                        }],
1602                    },
1603                )?;
1604            }
1605
1606            if we_offer
1607                && let Some(parsed_local_description) = self
1608                    .current_local_description
1609                    .as_ref()
1610                    .and_then(|desc| desc.parsed.as_ref())
1611            {
1612                // only start sctp transport if application media has been negotiated
1613                if let (Some(local_application_media), Some(remote_application_media)) = (
1614                    get_application_media(parsed_local_description),
1615                    get_application_media(parsed_remote_description),
1616                ) {
1617                    let (dtls_role, remote_caps, local_sctp_port, remote_sctp_port) = (
1618                        self.dtls_transport().role(),
1619                        SCTPTransportCapabilities {
1620                            max_message_size: get_application_media_section_max_message_size(
1621                                remote_application_media,
1622                            )
1623                            .unwrap_or(SctpMaxMessageSize::DEFAULT_MESSAGE_SIZE),
1624                        },
1625                        get_application_media_section_sctp_port(local_application_media)
1626                            .unwrap_or(5000),
1627                        get_application_media_section_sctp_port(remote_application_media)
1628                            .unwrap_or(5000),
1629                    );
1630
1631                    // we_offer: we create_offer() and set_local_description() first
1632                    // then, after call set_remote_description here,
1633                    // Now we should have done SDP negotiation.
1634                    // Therefore, it is ready to start sctp and rtp.
1635                    self.sctp_transport_mut().start(
1636                        dtls_role,
1637                        remote_caps,
1638                        local_sctp_port,
1639                        remote_sctp_port,
1640                    )?;
1641                }
1642                self.start_rtp(remote_description)?;
1643            }
1644        }
1645
1646        Ok(())
1647    }
1648
1649    /// Returns the remote session description.
1650    ///
1651    /// Returns `pending_remote_description` if it is not null, otherwise returns
1652    /// `current_remote_description`. This property is used to determine if
1653    /// `set_remote_description` has already been called.
1654    ///
1655    /// # Specification
1656    ///
1657    /// See [remoteDescription](https://www.w3.org/TR/webrtc/#dom-peerconnection-remotedescription)
1658    pub fn remote_description(&self) -> Option<&RTCSessionDescription> {
1659        if self.pending_remote_description.is_some() {
1660            self.pending_remote_description.as_ref()
1661        } else {
1662            self.current_remote_description.as_ref()
1663        }
1664    }
1665
1666    /// Returns the current remote description as last successfully negotiated since
1667    /// the last negotiation completed.
1668    ///
1669    /// This represents the remote description from the last offer/answer exchange that was
1670    /// successfully applied, not including any offers currently being negotiated.
1671    ///
1672    /// Returns `None` if there is no current remote description (e.g., before initial negotiation).
1673    ///
1674    /// # Specification
1675    ///
1676    /// See [currentRemoteDescription](https://www.w3.org/TR/webrtc/#dom-peerconnection-currentremotedesc)
1677    pub fn current_remote_description(&self) -> Option<&RTCSessionDescription> {
1678        self.current_remote_description.as_ref()
1679    }
1680
1681    /// Returns the pending remote description if it exists.
1682    ///
1683    /// This represents the remote description from a call to `set_remote_description()` whose
1684    /// corresponding local description has not yet been applied. This is `None` if negotiation
1685    /// is not in progress or if a rollback has been performed.
1686    ///
1687    /// Returns `None` if there is no pending remote description.
1688    ///
1689    /// # Specification
1690    ///
1691    /// See [pendingRemoteDescription](https://www.w3.org/TR/webrtc/#dom-peerconnection-pendingremotedesc)
1692    pub fn pending_remote_description(&self) -> Option<&RTCSessionDescription> {
1693        self.pending_remote_description.as_ref()
1694    }
1695
1696    /// Adds a remote ICE candidate to the peer connection.
1697    ///
1698    /// This method provides a remote candidate to the ICE agent. When the remote peer
1699    /// gathers ICE candidates and sends them over the signaling channel, this method
1700    /// should be called to add each candidate.
1701    ///
1702    /// # Parameters
1703    ///
1704    /// * `remote_candidate` - The ICE candidate initialization data.
1705    ///
1706    /// # Errors
1707    ///
1708    /// Returns an error if:
1709    /// - No remote description has been set
1710    /// - The candidate string is invalid
1711    ///
1712    /// # Specification
1713    ///
1714    /// See [addIceCandidate](https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-addicecandidate!overload-1)
1715    pub fn add_remote_candidate(&mut self, remote_candidate: RTCIceCandidateInit) -> Result<()> {
1716        if self.remote_description().is_none() {
1717            return Err(Error::ErrNoRemoteDescription);
1718        }
1719
1720        let candidate_value = match remote_candidate.candidate.strip_prefix("candidate:") {
1721            Some(s) => s,
1722            None => remote_candidate.candidate.as_str(),
1723        };
1724
1725        if !candidate_value.is_empty() {
1726            self.add_ice_remote_candidate(candidate_value)?;
1727        }
1728
1729        Ok(())
1730    }
1731
1732    /// Adds a local ICE candidate to the peer connection.
1733    ///
1734    /// This has no W3C counterpart: a browser's ICE agent gathers its own candidates, but this
1735    /// crate performs no I/O, so the application owns the sockets and therefore owns gathering.
1736    /// Every local candidate the connection is to advertise must be handed to this method.
1737    ///
1738    /// # Signalling the end of gathering
1739    ///
1740    /// An **empty candidate string** is the end-of-gathering sentinel. It advertises no
1741    /// candidate; it moves the ICE gathering state to [`RTCIceGatheringState::Complete`] and
1742    /// emits [`RTCPeerConnectionEvent::OnIceGatheringStateChangeEvent`] with that state. No
1743    /// other call reaches `Complete`, so a caller that never sends it leaves the connection
1744    /// reporting `Gathering` forever. Send it once, after the last real candidate:
1745    ///
1746    /// ```no_run
1747    /// # use std::time::Instant;
1748    /// # use rtc::peer_connection::RTCPeerConnectionBuilder;
1749    /// use rtc::peer_connection::transport::RTCIceCandidateInit;
1750    ///
1751    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
1752    /// let mut pc = RTCPeerConnectionBuilder::new().build(Instant::now())?;
1753    /// // ... add every gathered candidate first ...
1754    /// pc.add_local_candidate(RTCIceCandidateInit::default())?;
1755    /// # Ok(())
1756    /// # }
1757    /// ```
1758    ///
1759    /// # Parameters
1760    ///
1761    /// - `local_candidate`: The ICE candidate initialization data, or a value whose `candidate`
1762    ///   field is empty to signal end-of-gathering. For candidates of type `srflx` (server
1763    ///   reflexive) or `relay`, set `url` to the STUN/TURN server the candidate was gathered
1764    ///   from, so that `getStats` attributes it correctly.
1765    ///
1766    /// # Errors
1767    ///
1768    /// Returns an error if a non-empty candidate string cannot be parsed.
1769    ///
1770    /// [`RTCIceGatheringState::Complete`]: crate::peer_connection::state::RTCIceGatheringState::Complete
1771    /// [`RTCPeerConnectionEvent::OnIceGatheringStateChangeEvent`]: crate::peer_connection::event::RTCPeerConnectionEvent::OnIceGatheringStateChangeEvent
1772    pub fn add_local_candidate(&mut self, local_candidate: RTCIceCandidateInit) -> Result<()> {
1773        let candidate_value = match local_candidate.candidate.strip_prefix("candidate:") {
1774            Some(s) => s,
1775            None => local_candidate.candidate.as_str(),
1776        };
1777
1778        if !candidate_value.is_empty() {
1779            self.add_ice_local_candidate(candidate_value, local_candidate.url.as_deref())?;
1780        } else {
1781            self.ice_transport_mut().ice_gathering_state = RTCIceGatheringState::Complete;
1782            // Emit OnIceGatheringStateChangeEvent
1783            self.pipeline_context.event_outs.push_back(
1784                RTCPeerConnectionEvent::OnIceGatheringStateChangeEvent(
1785                    RTCIceGatheringState::Complete,
1786                ),
1787            );
1788        }
1789
1790        Ok(())
1791    }
1792
1793    /// Tells the peer connection that ICE should be restarted.
1794    ///
1795    /// This method causes the next call to `create_offer` to generate an offer that
1796    /// will restart ICE. This is useful when network conditions change or the connection
1797    /// fails.
1798    ///
1799    /// # Specification
1800    ///
1801    /// See [restartIce](https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-restartice)
1802    pub fn restart_ice(&mut self) {
1803        self.ice_restart_requested = Some(RTCOfferOptions { ice_restart: true });
1804    }
1805
1806    /// Returns the current configuration of this peer connection.
1807    ///
1808    /// The returned reference is to the current configuration. To modify the configuration,
1809    /// use `set_configuration`.
1810    ///
1811    /// # Specification
1812    ///
1813    /// See [getConfiguration](https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-getconfiguration)
1814    pub fn get_configuration(&self) -> &RTCConfiguration {
1815        &self.configuration
1816    }
1817
1818    /// Updates the configuration of this peer connection.
1819    ///
1820    /// Only the fields the W3C algorithm permits changing after construction are applied;
1821    /// attempting to change the peer identity or the certificate set is an error.
1822    ///
1823    /// # Parameters
1824    ///
1825    /// - `configuration`: The configuration to apply.
1826    ///
1827    /// # Errors
1828    ///
1829    /// Returns an error if:
1830    /// - The peer connection is closed (`ErrConnectionClosed`)
1831    /// - The peer identity differs from the one already set (`ErrModifyingPeerIdentity`)
1832    /// - The number of certificates differs from the one already set (`ErrModifyingCertificates`)
1833    ///
1834    /// # Specification
1835    ///
1836    /// See [setConfiguration](https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-setconfiguration)
1837    pub fn set_configuration(&mut self, configuration: RTCConfiguration) -> Result<()> {
1838        // https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-setconfiguration (step #2)
1839        if self.peer_connection_state == RTCPeerConnectionState::Closed {
1840            return Err(Error::ErrConnectionClosed);
1841        }
1842
1843        // https://www.w3.org/TR/webrtc/#set-the-configuration (step #3)
1844        if !configuration.peer_identity.is_empty() {
1845            if configuration.peer_identity != self.configuration.peer_identity {
1846                return Err(Error::ErrModifyingPeerIdentity);
1847            }
1848            self.configuration.peer_identity = configuration.peer_identity;
1849        }
1850
1851        // https://www.w3.org/TR/webrtc/#set-the-configuration (step #4)
1852        if !configuration.certificates.is_empty() {
1853            if configuration.certificates.len() != self.configuration.certificates.len() {
1854                return Err(Error::ErrModifyingCertificates);
1855            }
1856
1857            self.configuration.certificates = configuration.certificates;
1858        }
1859
1860        // https://www.w3.org/TR/webrtc/#set-the-configuration (step #5)
1861
1862        if configuration.bundle_policy != self.configuration.bundle_policy {
1863            return Err(Error::ErrModifyingBundlePolicy);
1864        }
1865        self.configuration.bundle_policy = configuration.bundle_policy;
1866
1867        // https://www.w3.org/TR/webrtc/#set-the-configuration (step #6)
1868        if configuration.rtcp_mux_policy != self.configuration.rtcp_mux_policy {
1869            return Err(Error::ErrModifyingRTCPMuxPolicy);
1870        }
1871        self.configuration.rtcp_mux_policy = configuration.rtcp_mux_policy;
1872
1873        // https://www.w3.org/TR/webrtc/#set-the-configuration (step #7)
1874        if configuration.ice_candidate_pool_size != 0 {
1875            if self.configuration.ice_candidate_pool_size != configuration.ice_candidate_pool_size
1876                && self.local_description().is_some()
1877            {
1878                return Err(Error::ErrModifyingICECandidatePoolSize);
1879            }
1880            self.configuration.ice_candidate_pool_size = configuration.ice_candidate_pool_size;
1881        }
1882
1883        // https://www.w3.org/TR/webrtc/#set-the-configuration (step #8)
1884
1885        self.configuration.ice_transport_policy = configuration.ice_transport_policy;
1886
1887        // https://www.w3.org/TR/webrtc/#set-the-configuration (step #11)
1888        if !configuration.ice_servers.is_empty() {
1889            // https://www.w3.org/TR/webrtc/#set-the-configuration (step #11.3)
1890            for server in &configuration.ice_servers {
1891                server.validate()?;
1892            }
1893            self.configuration.ice_servers = configuration.ice_servers
1894        }
1895
1896        Ok(())
1897    }
1898
1899    /// Creates a new data channel with the given label.
1900    ///
1901    /// The returned handle borrows the peer connection. To reach the channel again later,
1902    /// keep its [`RTCDataChannelId`] (from [`RTCDataChannel::id`]) and pass it to
1903    /// [`Self::data_channel`].
1904    ///
1905    /// A channel created here is not immediately usable: unless it was negotiated
1906    /// out-of-band, its SCTP stream is established by the in-band DCEP handshake, and sending
1907    /// before then fails. Wait for [`RTCDataChannelEvent::OnOpen`].
1908    ///
1909    /// # Parameters
1910    ///
1911    /// - `label`: The channel label. Labels need not be unique.
1912    /// - `options`: Optional configuration such as ordering, reliability and out-of-band
1913    ///   negotiation. Defaults are used when `None`.
1914    ///
1915    /// # Errors
1916    ///
1917    /// Returns an error if:
1918    /// - The peer connection is closed (`ErrConnectionClosed`)
1919    /// - The label or sub-protocol exceeds the length the DCEP OPEN message can carry
1920    ///
1921    /// # Specification
1922    ///
1923    /// See [createDataChannel](https://www.w3.org/TR/webrtc/#dom-peerconnection-createdatachannel)
1924    ///
1925    /// [`RTCDataChannelId`]: crate::data_channel::RTCDataChannelId
1926    /// [`RTCDataChannel::id`]: crate::data_channel::RTCDataChannel::id
1927    /// [`RTCDataChannelEvent::OnOpen`]: crate::peer_connection::event::RTCDataChannelEvent::OnOpen
1928    pub fn create_data_channel(
1929        &mut self,
1930        label: &str,
1931        options: Option<RTCDataChannelInit>,
1932    ) -> Result<RTCDataChannel<'_>> {
1933        // https://www.w3.org/TR/webrtc/#peer-to-peer-data-api (Step #2)
1934        if self.peer_connection_state == RTCPeerConnectionState::Closed {
1935            return Err(Error::ErrConnectionClosed);
1936        }
1937
1938        let mut params = DataChannelParameters {
1939            label: label.to_owned(),
1940            ..Default::default()
1941        };
1942
1943        // `None` means "the dictionary defaults", which is what `RTCDataChannelInit::default()`
1944        // spells out. Taking that route rather than leaving `params` on its derived default
1945        // keeps a single definition of those defaults — notably `ordered`, which is `true`.
1946        let options = options.unwrap_or_default();
1947
1948        // https://www.w3.org/TR/webrtc/#peer-to-peer-data-api (Step #16)
1949        if options.max_packet_life_time.is_some() && options.max_retransmits.is_some() {
1950            return Err(Error::ErrRetransmitsOrPacketLifeTime);
1951        }
1952
1953        // Ordered indicates if data is allowed to be delivered out of order. The
1954        // default value of true, guarantees that data will be delivered in order.
1955        // https://www.w3.org/TR/webrtc/#peer-to-peer-data-api (Step #9)
1956        params.ordered = options.ordered;
1957
1958        // https://www.w3.org/TR/webrtc/#peer-to-peer-data-api (Step #7)
1959        params.max_packet_life_time = options.max_packet_life_time;
1960
1961        // https://www.w3.org/TR/webrtc/#peer-to-peer-data-api (Step #8)
1962        params.max_retransmits = options.max_retransmits;
1963
1964        // https://www.w3.org/TR/webrtc/#peer-to-peer-data-api (Step #10)
1965        params.protocol = options.protocol;
1966
1967        // https://www.w3.org/TR/webrtc/#peer-to-peer-data-api (Step #11)
1968        if params.protocol.len() > 65535 {
1969            return Err(Error::ErrProtocolTooLarge);
1970        }
1971
1972        // https://www.w3.org/TR/webrtc/#peer-to-peer-data-api (Step #12)
1973        //
1974        // `negotiated` doubles as the out-of-band stream id. When it is set the id is fixed by
1975        // the application and known now; when it is not, the channel is announced in-band and
1976        // its stream id has to wait for the DTLS role, per RFC 8832 §6. Nothing is guessed
1977        // here — see `assign_stream_ids`.
1978        params.negotiated = options.negotiated;
1979
1980        // The registry assigns the handle. Note this happens before any dial: the channel is
1981        // addressable from the moment it exists, whether or not it has a stream id yet.
1982        let id = self
1983            .data_channels
1984            .insert(RTCDataChannelInternal::new(params));
1985
1986        // https://www.w3.org/TR/webrtc/#peer-to-peer-data-api (Step #23)
1987        // Open the channel's data transport immediately when an SCTP association already
1988        // exists. The DTLS role is necessarily resolved by then, so a stream id can be
1989        // assigned right here rather than waiting for a connected procedure that has passed.
1990        //
1991        // The role guard is not redundant with the association check. In practice an
1992        // association only exists once a description has been applied, which resolves the
1993        // role — but if it somehow is not resolved, there is no correct parity to pick, and
1994        // "wait for the connected procedure" is the right answer rather than an error. That is
1995        // the ordinary path for every channel created before negotiation.
1996        let dtls_role = self.dtls_transport().role();
1997        if let Some(handle) = self
1998            .sctp_transport()
1999            .sctp_associations
2000            .keys()
2001            .next()
2002            .copied()
2003            && matches!(dtls_role, RTCDtlsRole::Client | RTCDtlsRole::Server)
2004        {
2005            let max_channels = self.sctp_transport().max_channels();
2006            self.data_channels
2007                .assign_stream_ids(dtls_role, max_channels)?;
2008
2009            let data_channel = self
2010                .data_channels
2011                .get_mut(&id)
2012                .ok_or(Error::ErrDataChannelNotExisted)?;
2013            if data_channel.ready_state == RTCDataChannelState::Connecting
2014                && data_channel.data_channel.is_none()
2015            {
2016                data_channel.dial(handle.0)?;
2017            }
2018        }
2019
2020        self.trigger_negotiation_needed();
2021
2022        Ok(RTCDataChannel {
2023            id,
2024            peer_connection: self,
2025        })
2026    }
2027
2028    /// Returns an iterator over the `RTCRtpSender` objects.
2029    ///
2030    /// The `RTCRtpSender` objects represent the media streams that are being sent
2031    /// to the remote peer.
2032    ///
2033    /// # Specification
2034    ///
2035    /// See [getSenders](https://www.w3.org/TR/webrtc/#dom-peerconnection-getsenders)
2036    pub fn get_senders(&self) -> impl Iterator<Item = RTCRtpSenderId> + use<'_> {
2037        self.rtp_transceivers
2038            .iter()
2039            .enumerate()
2040            .filter(|(_, transceiver)| transceiver.direction().has_send())
2041            .map(|(id, _)| RTCRtpSenderId(id))
2042    }
2043
2044    /// Returns an iterator over the `RTCRtpReceiver` objects.
2045    ///
2046    /// The `RTCRtpReceiver` objects represent the media streams that are being received
2047    /// from the remote peer.
2048    ///
2049    /// # Specification
2050    ///
2051    /// See [getReceivers](https://www.w3.org/TR/webrtc/#dom-peerconnection-getreceivers)
2052    pub fn get_receivers(&self) -> impl Iterator<Item = RTCRtpReceiverId> + use<'_> {
2053        self.rtp_transceivers
2054            .iter()
2055            .enumerate()
2056            .filter(|(_, transceiver)| transceiver.direction().has_recv())
2057            .map(|(id, _)| RTCRtpReceiverId(id))
2058    }
2059
2060    /// Returns an iterator over the `RTCRtpTransceiver` objects.
2061    ///
2062    /// The `RTCRtpTransceiver` objects represent the combination of an `RTCRtpSender`
2063    /// and an `RTCRtpReceiver` that share a common mid.
2064    ///
2065    /// # Specification
2066    ///
2067    /// See [getTransceivers](https://www.w3.org/TR/webrtc/#dom-peerconnection-gettranseceivers)
2068    pub fn get_transceivers(&self) -> impl Iterator<Item = RTCRtpTransceiverId> {
2069        0..self.rtp_transceivers.len()
2070    }
2071
2072    /// Adds a media track to the peer connection.
2073    ///
2074    /// This method adds a track to the connection, either by finding an existing transceiver
2075    /// that can be reused, or by creating a new transceiver. The track represents media
2076    /// (audio or video) that will be sent to the remote peer.
2077    ///
2078    /// # Parameters
2079    ///
2080    /// * `track` - The media stream track to add.
2081    ///
2082    /// # Returns
2083    ///
2084    /// Returns the ID of the `RTCRtpSender` that will send this track.
2085    ///
2086    /// # Errors
2087    ///
2088    /// Returns an error if the peer connection is closed.
2089    ///
2090    /// # Specification
2091    ///
2092    /// See [addTrack](https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-addtrack)
2093    pub fn add_track(&mut self, track: MediaStreamTrack) -> Result<RTCRtpSenderId> {
2094        if self.peer_connection_state == RTCPeerConnectionState::Closed {
2095            return Err(Error::ErrConnectionClosed);
2096        }
2097
2098        let send_encodings = self.send_encodings_from_track(&track);
2099        let (track, send_encodings, codec_preferences) =
2100            self.normalize_sender_track(track, send_encodings)?;
2101        for (id, transceiver) in self.rtp_transceivers.iter_mut().enumerate() {
2102            if !transceiver.stopped()
2103                && transceiver.kind() == track.kind()
2104                && transceiver.sender().is_none()
2105            {
2106                let mut sender =
2107                    RTCRtpSenderInternal::new(track.kind(), track, vec![], send_encodings);
2108
2109                if transceiver.get_codec_preferences().is_empty() && !codec_preferences.is_empty() {
2110                    transceiver.set_codec_preferences(codec_preferences, &self.media_engine)?;
2111                }
2112
2113                sender.set_codec_preferences(transceiver.get_codec_preferences().to_vec());
2114
2115                transceiver.sender_mut().replace(sender);
2116
2117                transceiver.set_direction(RTCRtpTransceiverDirection::from_send_recv(
2118                    true,
2119                    transceiver.direction().has_recv(),
2120                ));
2121
2122                self.trigger_negotiation_needed();
2123                return Ok(RTCRtpSenderId(id));
2124            }
2125        }
2126
2127        let mut transceiver = self.new_transceiver_from_track(
2128            track,
2129            RTCRtpTransceiverInit {
2130                direction: RTCRtpTransceiverDirection::Sendrecv,
2131                streams: vec![],
2132                send_encodings,
2133            },
2134        )?;
2135        if !codec_preferences.is_empty() {
2136            transceiver.set_codec_preferences(codec_preferences, &self.media_engine)?;
2137        }
2138        Ok(RTCRtpSenderId(self.add_rtp_transceiver(transceiver)))
2139    }
2140
2141    /// Removes a track from the peer connection.
2142    ///
2143    /// This method stops an `RTCRtpSender` from sending media and marks its transceiver
2144    /// as no longer sending. This will trigger renegotiation.
2145    ///
2146    /// # Parameters
2147    ///
2148    /// * `sender_id` - The ID of the `RTCRtpSender` to remove.
2149    ///
2150    /// # Errors
2151    ///
2152    /// Returns an error if:
2153    /// - The peer connection is closed
2154    /// - The sender ID is invalid
2155    ///
2156    /// # Specification
2157    ///
2158    /// See [removeTrack](https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-removetrack)
2159    pub fn remove_track(&mut self, sender_id: RTCRtpSenderId) -> Result<()> {
2160        if self.peer_connection_state == RTCPeerConnectionState::Closed {
2161            return Err(Error::ErrConnectionClosed);
2162        }
2163
2164        if sender_id.0 >= self.rtp_transceivers.len() {
2165            return Err(Error::ErrRTPSenderNotExisted);
2166        }
2167
2168        // This also happens in `set_sending_track` but we need to make sure we do this
2169        // before we call sender.stop to avoid a race condition when removing tracks and
2170        // generating offers.
2171        let has_recv = self.rtp_transceivers[sender_id.0].direction().has_recv();
2172        self.rtp_transceivers[sender_id.0]
2173            .set_direction(RTCRtpTransceiverDirection::from_send_recv(false, has_recv));
2174
2175        if let Some(sender) = self.rtp_transceivers[sender_id.0].sender_mut()
2176            && sender
2177                .stop(&self.media_engine, &mut self.interceptor)
2178                .is_ok()
2179        {
2180            self.trigger_negotiation_needed();
2181        }
2182
2183        self.rtp_transceivers[sender_id.0].sender_mut().take();
2184
2185        Ok(())
2186    }
2187
2188    /// Creates a new `RTCRtpTransceiver` and adds it to the set of transceivers.
2189    ///
2190    /// This method creates a transceiver associated with the given track, which can be
2191    /// configured to send, receive, or both.
2192    ///
2193    /// # Parameters
2194    ///
2195    /// * `track` - The media stream track to associate with the transceiver.
2196    /// * `init` - Optional initialization parameters for the transceiver.
2197    ///
2198    /// # Returns
2199    ///
2200    /// Returns the ID of the created transceiver.
2201    ///
2202    /// # Errors
2203    ///
2204    /// Returns an error if the peer connection is closed.
2205    ///
2206    /// # Specification
2207    ///
2208    /// See [addTransceiver](https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-addtransceiver)
2209    pub fn add_transceiver_from_track(
2210        &mut self,
2211        track: MediaStreamTrack,
2212        init: Option<RTCRtpTransceiverInit>,
2213    ) -> Result<RTCRtpTransceiverId> {
2214        if self.peer_connection_state == RTCPeerConnectionState::Closed {
2215            return Err(Error::ErrConnectionClosed);
2216        }
2217
2218        if let Some(init) = init.as_ref()
2219            && !init.direction.has_send()
2220        {
2221            return Err(Error::ErrInvalidDirection);
2222        }
2223
2224        let mut init = if let Some(init) = init {
2225            init
2226        } else {
2227            RTCRtpTransceiverInit {
2228                direction: RTCRtpTransceiverDirection::Sendrecv,
2229                streams: vec![],
2230                send_encodings: vec![],
2231            }
2232        };
2233
2234        let send_encodings = if init.send_encodings.is_empty() {
2235            self.send_encodings_from_track(&track)
2236        } else {
2237            init.send_encodings.clone()
2238        };
2239        let (track, send_encodings, codec_preferences) =
2240            self.normalize_sender_track(track, send_encodings)?;
2241        init.send_encodings = send_encodings;
2242
2243        let mut transceiver = self.new_transceiver_from_track(track, init)?;
2244        if !codec_preferences.is_empty() {
2245            transceiver.set_codec_preferences(codec_preferences, &self.media_engine)?;
2246        }
2247
2248        Ok(self.add_rtp_transceiver(transceiver))
2249    }
2250
2251    /// Creates a new transceiver for the given media kind and adds it to the set of
2252    /// transceivers.
2253    ///
2254    /// # Parameters
2255    ///
2256    /// - `kind`: Audio or video.
2257    /// - `init`: Optional direction and encoding parameters; defaults are used when `None`.
2258    ///
2259    /// # Errors
2260    ///
2261    /// Returns an error if:
2262    /// - The peer connection is closed (`ErrConnectionClosed`)
2263    /// - The requested direction is not supported for a transceiver created this way
2264    /// - No codec is registered in the media engine for `kind`
2265    ///
2266    /// # Specification
2267    ///
2268    /// See [addTransceiver](https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-addtransceiver)
2269    pub fn add_transceiver_from_kind(
2270        &mut self,
2271        kind: RtpCodecKind,
2272        init: Option<RTCRtpTransceiverInit>,
2273    ) -> Result<RTCRtpTransceiverId> {
2274        if self.peer_connection_state == RTCPeerConnectionState::Closed {
2275            return Err(Error::ErrConnectionClosed);
2276        }
2277
2278        let init = if let Some(init) = init {
2279            if init.direction.has_send() && init.send_encodings.is_empty() {
2280                return Err(Error::ErrInvalidDirection);
2281            }
2282
2283            init
2284        } else {
2285            RTCRtpTransceiverInit {
2286                direction: RTCRtpTransceiverDirection::Recvonly,
2287                streams: vec![],
2288                send_encodings: vec![],
2289            }
2290        };
2291
2292        let transceiver = match init.direction {
2293            RTCRtpTransceiverDirection::Sendonly | RTCRtpTransceiverDirection::Sendrecv => {
2294                let mut init = init;
2295                let track = MediaStreamTrack::new(
2296                    math_rand_alpha(16), // MediaStreamId
2297                    math_rand_alpha(16), // MediaStreamTrackId
2298                    math_rand_alpha(16), // Label
2299                    kind,
2300                    init.send_encodings.clone(),
2301                );
2302                let (track, send_encodings, codec_preferences) =
2303                    self.normalize_sender_track(track, init.send_encodings)?;
2304                init.send_encodings = send_encodings;
2305
2306                let mut transceiver = self.new_transceiver_from_track(track, init)?;
2307                if !codec_preferences.is_empty() {
2308                    transceiver.set_codec_preferences(codec_preferences, &self.media_engine)?;
2309                }
2310                transceiver
2311            }
2312            RTCRtpTransceiverDirection::Recvonly => {
2313                RTCRtpTransceiverInternal::new(kind, None, init)
2314            }
2315            _ => return Err(Error::ErrPeerConnAddTransceiverFromKindSupport),
2316        };
2317
2318        Ok(self.add_rtp_transceiver(transceiver))
2319    }
2320
2321    /// Returns a handle to the [`RTCDataChannel`] with the given id, or `None` if no such
2322    /// channel exists on this peer connection.
2323    ///
2324    /// [`RTCDataChannel`]: crate::data_channel::RTCDataChannel
2325    pub fn data_channel(&mut self, id: RTCDataChannelId) -> Option<RTCDataChannel<'_>> {
2326        if self.data_channels.contains(&id) {
2327            Some(RTCDataChannel {
2328                id,
2329                peer_connection: self,
2330            })
2331        } else {
2332            None
2333        }
2334    }
2335
2336    /// The SCTP transport over which data channels are carried.
2337    ///
2338    /// `None` until SCTP has been negotiated — that is, until a description establishing an
2339    /// SCTP association has been applied by both sides. A connection carrying only media never
2340    /// has one.
2341    ///
2342    /// This is the **only** transport accessor on `RTCPeerConnection`, matching the W3C
2343    /// interface, which exposes `sctp` and nothing else. The DTLS and ICE transports are
2344    /// reached by walking from here (or from a sender or receiver):
2345    ///
2346    /// ```text
2347    /// pc.sctp()?.transport().ice_transport()
2348    /// ```
2349    ///
2350    /// ## Specifications
2351    ///
2352    /// * [W3C](https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-sctp)
2353    pub fn sctp(&self) -> Option<RTCSctpTransport<'_>> {
2354        if self.sctp_transport().is_started {
2355            Some(RTCSctpTransport {
2356                peer_connection: self,
2357            })
2358        } else {
2359            None
2360        }
2361    }
2362
2363    /// Returns a handle to the [`RTCRtpSender`] with the given id, or `None` if no such
2364    /// sender exists on this peer connection.
2365    ///
2366    /// [`RTCRtpSender`]: crate::rtp_transceiver::rtp_sender::RTCRtpSender
2367    pub fn rtp_sender(&mut self, id: RTCRtpSenderId) -> Option<RTCRtpSender<'_>> {
2368        if id.0 < self.rtp_transceivers.len()
2369            && self.rtp_transceivers[id.0].direction().has_send()
2370            && self.rtp_transceivers[id.0].sender().is_some()
2371        {
2372            Some(RTCRtpSender {
2373                id,
2374                peer_connection: self,
2375            })
2376        } else {
2377            None
2378        }
2379    }
2380
2381    /// Returns a handle to the [`RTCRtpReceiver`] with the given id, or `None` if no such
2382    /// receiver exists on this peer connection.
2383    ///
2384    /// [`RTCRtpReceiver`]: crate::rtp_transceiver::rtp_receiver::RTCRtpReceiver
2385    pub fn rtp_receiver(&mut self, id: RTCRtpReceiverId) -> Option<RTCRtpReceiver<'_>> {
2386        if id.0 < self.rtp_transceivers.len()
2387            && self.rtp_transceivers[id.0].direction().has_recv()
2388            && self.rtp_transceivers[id.0].receiver().is_some()
2389        {
2390            Some(RTCRtpReceiver {
2391                id,
2392                peer_connection: self,
2393            })
2394        } else {
2395            None
2396        }
2397    }
2398
2399    /// Returns a handle to the [`RTCRtpTransceiver`] with the given id, or `None` if no such
2400    /// transceiver exists on this peer connection.
2401    ///
2402    /// [`RTCRtpTransceiver`]: crate::rtp_transceiver::RTCRtpTransceiver
2403    pub fn rtp_transceiver(&mut self, id: RTCRtpTransceiverId) -> Option<RTCRtpTransceiver<'_>> {
2404        if id < self.rtp_transceivers.len() {
2405            Some(RTCRtpTransceiver {
2406                id,
2407                peer_connection: self,
2408            })
2409        } else {
2410            None
2411        }
2412    }
2413
2414    /// Returns a snapshot of accumulated statistics.
2415    ///
2416    /// This method creates an immutable snapshot of WebRTC statistics
2417    /// at the given timestamp. When `selector` is `StatsSelector::None`,
2418    /// the returned `RTCStatsReport` contains statistics for all aspects
2419    /// of the peer connection. When a sender or receiver is specified,
2420    /// only statistics relevant to that sender/receiver are included.
2421    ///
2422    /// # Statistics included by selector
2423    ///
2424    /// - `StatsSelector::None` - All statistics for the entire connection
2425    /// - `StatsSelector::Sender(id)` - Outbound RTP streams for the sender
2426    ///   and all referenced stats (transport, codec, remote inbound, etc.)
2427    /// - `StatsSelector::Receiver(id)` - Inbound RTP streams for the receiver
2428    ///   and all referenced stats (transport, codec, remote outbound, etc.)
2429    ///
2430    /// # Parameters
2431    ///
2432    /// * `now` - The timestamp to use for all stats in the report. This is
2433    ///   passed explicitly to support deterministic testing.
2434    /// * `selector` - Controls which statistics are included in the report.
2435    ///
2436    /// # Returns
2437    ///
2438    /// An `RTCStatsReport` containing snapshots of the selected statistics.
2439    ///
2440    /// # Examples
2441    ///
2442    /// ```no_run
2443    /// use std::time::Instant;
2444    /// use rtc::peer_connection::RTCPeerConnectionBuilder;
2445    /// use rtc::statistics::StatsSelector;
2446    ///
2447    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
2448    /// let mut pc = RTCPeerConnectionBuilder::new().build(Instant::now())?;
2449    ///
2450    /// // Get all stats
2451    /// let report = pc.get_stats(Instant::now(), StatsSelector::None);
2452    ///
2453    /// // Access peer connection stats
2454    /// if let Some(pc_stats) = report.peer_connection() {
2455    ///     println!("Data channels opened: {}", pc_stats.data_channels_opened);
2456    /// }
2457    ///
2458    /// // Iterate over inbound RTP streams
2459    /// for stream in report.inbound_rtp_streams() {
2460    ///     println!("SSRC {}: {} packets received", stream.received_rtp_stream_stats.rtp_stream_stats.ssrc, stream.received_rtp_stream_stats.packets_received);
2461    /// }
2462    /// # Ok(())
2463    /// # }
2464    /// ```
2465    ///
2466    /// # Specification
2467    ///
2468    /// See [getStats](https://www.w3.org/TR/webrtc/#widl-RTCPeerConnection-getStats-Promise-RTCStatsReport--MediaStreamTrack-selector) and
2469    /// [The stats selection algorithm](https://www.w3.org/TR/webrtc/#the-stats-selection-algorithm)
2470    pub fn get_stats(&mut self, now: Instant, selector: StatsSelector) -> RTCStatsReport {
2471        // Update ICE agent stats before taking snapshot
2472        self.update_ice_agent_stats(now);
2473        // Update codec stats from transceivers before taking snapshot
2474        self.update_codec_stats();
2475        self.pipeline_context
2476            .stats
2477            .snapshot_with_selector(now, selector)
2478    }
2479}
2480
2481#[cfg(test)]
2482mod tests {
2483    use super::*;
2484    use crate::data_channel::state::RTCDataChannelState;
2485    use crate::peer_connection::configuration::setting_engine::SctpMaxMessageSize;
2486    use crate::peer_connection::configuration::setting_engine::SettingEngineBuilder;
2487    use crate::peer_connection::transport::RTCIceComponent;
2488    use crate::peer_connection::transport::dtls::state::RTCDtlsTransportState;
2489    use sctp::AssociationHandle;
2490
2491    #[test]
2492    fn with_sctp_receive_buffer_size_sets_and_clamps() {
2493        let setting_engine = SettingEngineBuilder::new()
2494            .with_sctp_max_receive_buffer_size(200_000)
2495            .build();
2496
2497        let builder = RTCPeerConnectionBuilder::new().with_setting_engine(setting_engine);
2498        assert_eq!(
2499            builder.setting_engine.sctp_max_receive_buffer_size,
2500            Some(200_000)
2501        );
2502
2503        // Values below the RFC 9260 §3.3.2 floor (1500 bytes), including 0, are clamped up so
2504        // they cannot break the SCTP handshake.
2505        for input in [0u32, 500, 1499] {
2506            let setting_engine = SettingEngineBuilder::new()
2507                .with_sctp_max_receive_buffer_size(input)
2508                .build();
2509            let builder = RTCPeerConnectionBuilder::new().with_setting_engine(setting_engine);
2510            assert_eq!(
2511                builder.setting_engine.sctp_max_receive_buffer_size,
2512                Some(1500),
2513                "input {input} should clamp up to the 1500-byte floor"
2514            );
2515        }
2516    }
2517
2518    // The graph the spec exposes: `pc.sctp` is the only way in, and the rest is walked.
2519    #[test]
2520    fn sctp_is_none_until_sctp_is_negotiated() {
2521        let pc = RTCPeerConnectionBuilder::new()
2522            .build(Instant::now())
2523            .unwrap();
2524        assert!(
2525            pc.sctp().is_none(),
2526            "nothing has been negotiated, so there is no SCTP transport to expose"
2527        );
2528    }
2529
2530    #[test]
2531    fn the_transport_graph_is_walkable_and_ids_identify() {
2532        let mut pc = RTCPeerConnectionBuilder::new()
2533            .build(Instant::now())
2534            .unwrap();
2535        // `start()` is what negotiation calls once both descriptions carry an m=application
2536        // section; it is the predicate `sctp()` keys off.
2537        pc.sctp_transport_mut()
2538            .start(
2539                RTCDtlsRole::Client,
2540                crate::peer_connection::transport::sctp::capabilities::SCTPTransportCapabilities {
2541                    max_message_size: 0,
2542                },
2543                5000,
2544                5000,
2545            )
2546            .expect("start");
2547
2548        let sctp = pc.sctp().expect("SCTP is negotiated");
2549        let dtls = sctp.transport();
2550        let ice = dtls.ice_transport();
2551
2552        // Three transports, three identities.
2553        assert_ne!(sctp.id(), dtls.id());
2554        assert_ne!(dtls.id(), ice.id());
2555        assert_ne!(sctp.id(), ice.id());
2556
2557        // Ids are stored, not minted per call: walking twice yields the same identity.
2558        let dtls_again = pc.sctp().unwrap().transport();
2559        assert_eq!(dtls.id(), dtls_again.id());
2560        assert_eq!(ice.id(), dtls_again.ice_transport().id());
2561
2562        // The default configuration caps messages at 64 KiB and the peer advertised no limit,
2563        // so the negotiated value is this endpoint's cap.
2564        assert_eq!(Some(65536), sctp.max_message_size());
2565        // No association yet, so no negotiated stream count.
2566        assert_eq!(None, sctp.max_channels());
2567        assert_eq!(RTCIceComponent::Rtp, ice.component());
2568    }
2569
2570    // W3C types `maxMessageSize` `unrestricted double` so that an implementation with no limit
2571    // can report +Infinity. This one always has a limit — the working buffer is a real
2572    // allocation — so a configuration naming no limit resolves to the implementation ceiling,
2573    // and the value reported is the value enforced.
2574    #[test]
2575    fn max_message_size_with_no_configured_limit_reports_the_ceiling() {
2576        let setting_engine = SettingEngineBuilder::new()
2577            .with_sctp_max_message_size(SctpMaxMessageSize::Bounded(0))
2578            .build();
2579        let mut pc = RTCPeerConnectionBuilder::new()
2580            .with_setting_engine(setting_engine)
2581            .build(Instant::now())
2582            .unwrap();
2583        pc.sctp_transport_mut()
2584            .start(
2585                RTCDtlsRole::Client,
2586                crate::peer_connection::transport::sctp::capabilities::SCTPTransportCapabilities {
2587                    max_message_size: 0,
2588                },
2589                5000,
2590                5000,
2591            )
2592            .expect("start");
2593
2594        assert_eq!(
2595            Some(SctpMaxMessageSize::MAX_MESSAGE_SIZE),
2596            pc.sctp().expect("negotiated").max_message_size()
2597        );
2598    }
2599
2600    // `RTCRtpSender.transport` / `RTCRtpReceiver.transport` come from the per-object
2601    // `[[SenderTransport]]` / `[[ReceiverTransport]]` slots, filled when the transceiver is
2602    // associated by negotiation. Before that the spec reports null.
2603    #[test]
2604    fn sender_and_receiver_transport_are_none_until_the_transceiver_is_associated() {
2605        let mut pc = media_pc();
2606        // `add_track` creates a sendrecv transceiver, so this one has both a sender and a
2607        // receiver while still being unassociated.
2608        let track = MediaStreamTrack::new(
2609            "stream".to_owned(),
2610            "track".to_owned(),
2611            "label".to_owned(),
2612            RtpCodecKind::Audio,
2613            vec![],
2614        );
2615        let sender_id = pc.add_track(track).expect("add track");
2616        let receiver_id = RTCRtpReceiverId::from(sender_id.0);
2617
2618        assert!(pc.rtp_transceivers[sender_id.0].mid().is_none());
2619        assert!(
2620            pc.rtp_sender(sender_id)
2621                .expect("sender")
2622                .transport()
2623                .is_none(),
2624            "an unassociated sender has a null transport"
2625        );
2626        assert!(
2627            pc.rtp_receiver(receiver_id)
2628                .expect("receiver")
2629                .transport()
2630                .is_none(),
2631            "an unassociated receiver has a null transport"
2632        );
2633
2634        // Applying a local offer associates the transceiver. This is the offerer's window: a mid
2635        // exists, but no answer has arrived so DTLS has not started — and a browser reports a
2636        // transport here, which is why the predicate is association rather than "DTLS is up".
2637        let offer = pc.create_offer(None).expect("create offer");
2638        pc.set_local_description(Instant::now(), offer)
2639            .expect("set local description");
2640        assert!(pc.rtp_transceivers[sender_id.0].mid().is_some());
2641        assert!(
2642            !pc.dtls_transport().is_started(),
2643            "no answer yet, so DTLS has not been brought up"
2644        );
2645
2646        let sender_transport_id = pc
2647            .rtp_sender(sender_id)
2648            .expect("sender")
2649            .transport()
2650            .expect("an associated sender has a transport")
2651            .id();
2652        let receiver_transport_id = pc
2653            .rtp_receiver(receiver_id)
2654            .expect("receiver")
2655            .transport()
2656            .expect("an associated receiver has a transport")
2657            .id();
2658
2659        // Under bundling both directions share one DTLS transport, as the spec says...
2660        assert_eq!(sender_transport_id, receiver_transport_id);
2661        // ...and it is the same transport the rest of the graph names.
2662        assert_eq!(sender_transport_id, pc.dtls_transport().id);
2663        // Its state is `New` until the handshake begins: a transport that exists but has not
2664        // connected, exactly as a browser reports in this window.
2665        assert_eq!(RTCDtlsTransportState::New, pc.dtls_transport().state());
2666    }
2667
2668    // `with_discard_local_candidates_during_ice_restart` has to reach `apply_restart`, not just
2669    // land in the struct. Applying a restart with it set must empty the local candidates the
2670    // agent had gathered; with it unset they survive.
2671    //
2672    // This is the setting that makes a socket-rebinding ICE restart work (webrtc#868): retained
2673    // candidates name addresses nothing is bound to any more, so checks written for them go
2674    // nowhere and the restarted generation never leaves `Checking`.
2675    #[test]
2676    fn discard_local_candidates_during_ice_restart_reaches_apply_restart() {
2677        fn restart_with(discard: bool) -> usize {
2678            let setting_engine = SettingEngineBuilder::new()
2679                .with_discard_local_candidates_during_ice_restart(discard)
2680                .build();
2681            let mut pc = RTCPeerConnectionBuilder::new()
2682                .with_setting_engine(setting_engine)
2683                .build(Instant::now())
2684                .unwrap();
2685
2686            // Gather one host candidate so there is something to keep or drop.
2687            pc.add_local_candidate(RTCIceCandidateInit {
2688                candidate: "candidate:1 1 udp 2130706431 127.0.0.1 5000 typ host".to_owned(),
2689                ..Default::default()
2690            })
2691            .expect("add local candidate");
2692            assert_eq!(
2693                1,
2694                pc.ice_transport().get_local_candidates().unwrap().len(),
2695                "precondition: the agent holds the gathered candidate"
2696            );
2697
2698            pc.ice_transport_mut()
2699                .generate_restart_credentials(
2700                    "newufrag".to_owned(),
2701                    "newpasswordlongenough".to_owned(),
2702                )
2703                .expect("stage restart");
2704            pc.apply_ice_restart(Instant::now())
2705                .expect("apply ice restart");
2706
2707            pc.ice_transport().get_local_candidates().unwrap().len()
2708        }
2709
2710        assert_eq!(
2711            0,
2712            restart_with(true),
2713            "with discard enabled the stale generation's candidates are dropped"
2714        );
2715        assert_eq!(
2716            1,
2717            restart_with(false),
2718            "the default keeps them, which is the pre-existing behaviour"
2719        );
2720    }
2721
2722    // Two connections must never report the same transport as each other's. This is the case a
2723    // per-connection counter or a small-integer scheme gets wrong.
2724    #[test]
2725    fn transports_of_two_peer_connections_are_never_equal() {
2726        let mut ids = vec![];
2727        for _ in 0..2 {
2728            let mut pc = RTCPeerConnectionBuilder::new()
2729                .build(Instant::now())
2730                .unwrap();
2731            pc.sctp_transport_mut()
2732                .start(
2733                    RTCDtlsRole::Client,
2734                    crate::peer_connection::transport::sctp::capabilities::SCTPTransportCapabilities {
2735                        max_message_size: 0,
2736                    },
2737                    5000,
2738                    5000,
2739                )
2740                .expect("start");
2741            let sctp = pc.sctp().expect("SCTP is negotiated");
2742            ids.push((
2743                sctp.id(),
2744                sctp.transport().id(),
2745                sctp.transport().ice_transport().id(),
2746            ));
2747        }
2748
2749        let (a_sctp, a_dtls, a_ice) = ids[0];
2750        let (b_sctp, b_dtls, b_ice) = ids[1];
2751        assert_ne!(a_sctp, b_sctp);
2752        assert_ne!(a_dtls, b_dtls);
2753        assert_ne!(a_ice, b_ice);
2754    }
2755
2756    #[test]
2757    fn create_data_channel_dials_immediately_when_sctp_association_present() {
2758        let mut pc = RTCPeerConnectionBuilder::new()
2759            .build(Instant::now())
2760            .unwrap();
2761
2762        // Simulate an SCTP association so create_data_channel sees a transport
2763        // that is ready to open streams, and the resolved DTLS role that always accompanies
2764        // one in practice — the association is built by `SCTPTransport::start`, which runs
2765        // after `prepare_transport` has settled the role. Without it there is no correct
2766        // stream-id parity to pick and the channel would rightly defer (RFC 8832 §6).
2767        pc.dtls_transport_mut().dtls_role = RTCDtlsRole::Client;
2768        pc.sctp_transport_mut()
2769            .sctp_associations
2770            .insert(AssociationHandle(0), sctp::Association::default());
2771
2772        let _dc = pc.create_data_channel("test", None).unwrap();
2773
2774        let internal = pc
2775            .data_channels
2776            .values()
2777            .next()
2778            .expect("data channel must be stored internally");
2779        assert!(internal.data_channel.is_some());
2780        assert_eq!(
2781            internal.ready_state,
2782            RTCDataChannelState::Connecting,
2783            "a dialed in-band channel stays Connecting until its DATA_CHANNEL_ACK arrives"
2784        );
2785        assert_eq!(
2786            internal.stream_id,
2787            Some(0),
2788            "the DTLS client must take an even stream id (RFC 8832 §6)"
2789        );
2790    }
2791
2792    /// The mirror of the case above: with no resolved DTLS role there is no correct parity, so
2793    /// the channel is created without a stream id and waits for the connected procedure rather
2794    /// than being dialed or rejected.
2795    #[test]
2796    fn create_data_channel_defers_stream_id_when_dtls_role_unresolved() {
2797        let mut pc = RTCPeerConnectionBuilder::new()
2798            .build(Instant::now())
2799            .unwrap();
2800        pc.sctp_transport_mut()
2801            .sctp_associations
2802            .insert(AssociationHandle(0), sctp::Association::default());
2803
2804        let dc = pc.create_data_channel("test", None).unwrap();
2805        let id = dc.id();
2806
2807        let internal = pc.data_channels.get(&id).unwrap();
2808        assert_eq!(internal.stream_id, None, "no parity is knowable yet");
2809        assert!(
2810            internal.data_channel.is_none(),
2811            "a channel with no stream id cannot be dialed"
2812        );
2813    }
2814
2815    // ---- Rollback (RFC 9429, Section 5.7) ----
2816
2817    use crate::peer_connection::configuration::media_engine::MediaEngine;
2818    use crate::rtp_transceiver::RTCRtpTransceiverInit;
2819
2820    fn media_pc() -> RTCPeerConnection {
2821        let mut me = MediaEngine::default();
2822        me.register_default_codecs().unwrap();
2823        RTCPeerConnectionBuilder::new()
2824            .with_media_engine(me)
2825            .build(Instant::now())
2826            .unwrap()
2827    }
2828
2829    /// Builds an audio+video offer from a freshly-created peer connection.
2830    fn audio_video_offer() -> RTCSessionDescription {
2831        let mut offerer = media_pc();
2832        offerer
2833            .add_transceiver_from_kind(
2834                RtpCodecKind::Audio,
2835                Some(RTCRtpTransceiverInit {
2836                    direction: RTCRtpTransceiverDirection::Recvonly,
2837                    streams: vec![],
2838                    send_encodings: vec![],
2839                }),
2840            )
2841            .unwrap();
2842        offerer
2843            .add_transceiver_from_kind(
2844                RtpCodecKind::Video,
2845                Some(RTCRtpTransceiverInit {
2846                    direction: RTCRtpTransceiverDirection::Recvonly,
2847                    streams: vec![],
2848                    send_encodings: vec![],
2849                }),
2850            )
2851            .unwrap();
2852        offerer.create_offer(None).unwrap()
2853    }
2854
2855    fn rollback() -> RTCSessionDescription {
2856        RTCSessionDescription {
2857            sdp_type: RTCSdpType::Rollback,
2858            sdp: String::new(),
2859            parsed: None,
2860        }
2861    }
2862
2863    #[test]
2864    fn set_remote_rollback_removes_transceivers_created_by_remote_offer() {
2865        let offer = audio_video_offer();
2866
2867        let mut pc = media_pc();
2868        pc.set_remote_description(Instant::now(), offer).unwrap();
2869
2870        // Applying the remote offer implicitly creates two transceivers, each associated
2871        // with an "m=" section.
2872        assert_eq!(pc.rtp_transceivers.len(), 2);
2873        assert_eq!(pc.signaling_state, RTCSignalingState::HaveRemoteOffer);
2874        assert!(pc.rtp_transceivers.iter().all(|t| t.mid().is_some()));
2875
2876        // Rolling back the offer must stop and remove those transceivers and return to stable.
2877        pc.set_remote_description(Instant::now(), rollback())
2878            .unwrap();
2879
2880        assert_eq!(pc.signaling_state, RTCSignalingState::Stable);
2881        assert!(
2882            pc.rtp_transceivers.is_empty(),
2883            "transceivers created by a rolled-back remote offer must be removed"
2884        );
2885    }
2886
2887    #[test]
2888    fn set_local_rollback_disassociates_but_keeps_app_created_transceivers() {
2889        // A locally-initiated offer: the transceivers are created by the application, so
2890        // rolling back the local offer via set_local_description must disassociate them
2891        // (clear their mids) but must NOT remove them. This exercises the same rollback
2892        // cleanup path as set_remote_description, per RFC 9429 Section 5.7.
2893        let mut pc = media_pc();
2894        pc.add_transceiver_from_kind(
2895            RtpCodecKind::Audio,
2896            Some(RTCRtpTransceiverInit {
2897                direction: RTCRtpTransceiverDirection::Recvonly,
2898                streams: vec![],
2899                send_encodings: vec![],
2900            }),
2901        )
2902        .unwrap();
2903
2904        let offer = pc.create_offer(None).unwrap();
2905        pc.set_local_description(Instant::now(), offer).unwrap();
2906        assert_eq!(pc.signaling_state, RTCSignalingState::HaveLocalOffer);
2907        assert_eq!(pc.rtp_transceivers.len(), 1);
2908        assert!(pc.rtp_transceivers[0].mid().is_some());
2909
2910        pc.set_local_description(Instant::now(), rollback())
2911            .unwrap();
2912
2913        assert_eq!(pc.signaling_state, RTCSignalingState::Stable);
2914        assert_eq!(
2915            pc.rtp_transceivers.len(),
2916            1,
2917            "application-created transceivers must not be removed by rollback"
2918        );
2919        assert!(
2920            pc.rtp_transceivers[0].mid().is_none(),
2921            "rolled-back transceiver must be disassociated from its m= section"
2922        );
2923    }
2924
2925    #[test]
2926    fn rollback_keeps_transceiver_with_track_attached_via_add_track() {
2927        let offer = audio_video_offer();
2928
2929        let mut pc = media_pc();
2930        pc.set_remote_description(Instant::now(), offer).unwrap();
2931        assert_eq!(pc.rtp_transceivers.len(), 2);
2932
2933        // Attach a local track. add_track reuses the sender-less audio transceiver that was
2934        // created by the remote offer, giving it a sender.
2935        let track = MediaStreamTrack::new(
2936            "stream".to_owned(),
2937            "track".to_owned(),
2938            "label".to_owned(),
2939            RtpCodecKind::Audio,
2940            vec![],
2941        );
2942        pc.add_track(track).unwrap();
2943
2944        pc.set_remote_description(Instant::now(), rollback())
2945            .unwrap();
2946
2947        assert_eq!(pc.signaling_state, RTCSignalingState::Stable);
2948        // The video transceiver (no track) is removed; the audio transceiver with the attached
2949        // track is kept but disassociated (mid cleared) so a future offer can re-add it.
2950        assert_eq!(
2951            pc.rtp_transceivers.len(),
2952            1,
2953            "transceiver with a track attached via add_track must not be removed"
2954        );
2955        let kept = &pc.rtp_transceivers[0];
2956        assert_eq!(kept.kind(), RtpCodecKind::Audio);
2957        assert!(kept.sender().is_some());
2958        assert!(
2959            kept.mid().is_none(),
2960            "kept transceiver must be disassociated from its m= section on rollback"
2961        );
2962    }
2963
2964    #[test]
2965    fn rollback_keeps_transceiver_negotiated_by_a_previous_exchange() {
2966        // First, complete a full offer/answer so an incoming transceiver becomes part of the
2967        // stable state (its mid is recorded in the current remote description).
2968        let offer = audio_video_offer();
2969        let mut pc = media_pc();
2970        pc.set_remote_description(Instant::now(), offer).unwrap();
2971        assert_eq!(pc.rtp_transceivers.len(), 2);
2972        let answer = pc.create_answer(None).unwrap();
2973        pc.set_local_description(Instant::now(), answer).unwrap();
2974        assert_eq!(pc.signaling_state, RTCSignalingState::Stable);
2975        let negotiated_mids: Vec<_> = pc
2976            .rtp_transceivers
2977            .iter()
2978            .map(|t| t.mid().clone())
2979            .collect();
2980        assert!(negotiated_mids.iter().all(|m| m.is_some()));
2981
2982        // Now a renegotiation arrives and is rolled back. The transceivers negotiated by the
2983        // FIRST exchange must survive with their mids intact — rollback only undoes the pending
2984        // (second) transaction, not committed state.
2985        let reoffer = audio_video_offer();
2986        pc.set_remote_description(Instant::now(), reoffer).unwrap();
2987        assert_eq!(pc.signaling_state, RTCSignalingState::HaveRemoteOffer);
2988
2989        pc.set_remote_description(Instant::now(), rollback())
2990            .unwrap();
2991
2992        assert_eq!(pc.signaling_state, RTCSignalingState::Stable);
2993        assert_eq!(
2994            pc.rtp_transceivers.len(),
2995            2,
2996            "previously-negotiated transceivers must not be removed by a renegotiation rollback"
2997        );
2998        let mids_after: Vec<_> = pc
2999            .rtp_transceivers
3000            .iter()
3001            .map(|t| t.mid().clone())
3002            .collect();
3003        assert_eq!(
3004            mids_after, negotiated_mids,
3005            "previously-negotiated transceivers must keep their mid across rollback"
3006        );
3007    }
3008
3009    #[test]
3010    fn add_track_then_rollback_remote_offer_then_create_offer_includes_track() {
3011        // RFC 9429, Section 5.7: "an application may call addTrack, then call
3012        // setRemoteDescription with an offer, then roll back that offer, then call createOffer
3013        // and have an "m=" section for the added track appear in the generated offer."
3014        let mut pc = media_pc();
3015
3016        // 1. addTrack — creates a local sendrecv audio transceiver with a sender.
3017        let track = MediaStreamTrack::new(
3018            "stream".to_owned(),
3019            "track".to_owned(),
3020            "label".to_owned(),
3021            RtpCodecKind::Audio,
3022            vec![],
3023        );
3024        pc.add_track(track).unwrap();
3025        assert_eq!(pc.rtp_transceivers.len(), 1);
3026
3027        // 2. setRemoteDescription with a remote (video-only) offer. This reuses no existing
3028        //    transceiver (different kind), so it creates a second, remote-originated one.
3029        let mut video_offerer = media_pc();
3030        video_offerer
3031            .add_transceiver_from_kind(
3032                RtpCodecKind::Video,
3033                Some(RTCRtpTransceiverInit {
3034                    direction: RTCRtpTransceiverDirection::Recvonly,
3035                    streams: vec![],
3036                    send_encodings: vec![],
3037                }),
3038            )
3039            .unwrap();
3040        let remote_offer = video_offerer.create_offer(None).unwrap();
3041        pc.set_remote_description(Instant::now(), remote_offer)
3042            .unwrap();
3043        assert_eq!(pc.signaling_state, RTCSignalingState::HaveRemoteOffer);
3044        // The audio transceiver (with our track) got associated with the offer's m= section.
3045        assert!(
3046            pc.rtp_transceivers
3047                .iter()
3048                .any(|t| t.kind() == RtpCodecKind::Audio && t.sender().is_some())
3049        );
3050
3051        // 3. Roll back that offer.
3052        pc.set_remote_description(Instant::now(), rollback())
3053            .unwrap();
3054        assert_eq!(pc.signaling_state, RTCSignalingState::Stable);
3055
3056        // The audio transceiver with the attached track must survive (disassociated), while the
3057        // remote-created video transceiver must be gone.
3058        assert_eq!(
3059            pc.rtp_transceivers.len(),
3060            1,
3061            "the add_track transceiver must survive rollback; the remote one must be removed"
3062        );
3063        let kept = &pc.rtp_transceivers[0];
3064        assert_eq!(kept.kind(), RtpCodecKind::Audio);
3065        assert!(kept.sender().is_some());
3066        assert!(kept.mid().is_none(), "must be disassociated after rollback");
3067
3068        // 4. createOffer — an m= section for the added (audio) track must appear.
3069        let offer = pc.create_offer(None).unwrap();
3070        assert_eq!(
3071            offer.sdp.matches("m=audio").count(),
3072            1,
3073            "createOffer after rollback must emit an m=audio section for the added track"
3074        );
3075        // The transceiver has been re-associated (given a mid) for the new offer.
3076        assert!(pc.rtp_transceivers[0].mid().is_some());
3077    }
3078
3079    #[test]
3080    fn add_track_then_rollback_local_offer_then_answer_remote_still_renegotiates_track() {
3081        // Polite-peer glare scenario (RFC 9429, Section 5.7): the application calls addTrack and
3082        // sends its own offer, then a remote offer arrives (collision). The polite peer rolls
3083        // back its local offer, applies the remote offer, and answers it. The locally-added
3084        // track was never negotiated, so it must still be pending and appear in a subsequent
3085        // offer — mirroring the RFC's addTrack/rollback/createOffer guarantee for the local case.
3086        let mut pc = media_pc();
3087
3088        // 1. addTrack (audio) — local sendrecv audio transceiver with a sender.
3089        let track = MediaStreamTrack::new(
3090            "stream".to_owned(),
3091            "track".to_owned(),
3092            "label".to_owned(),
3093            RtpCodecKind::Audio,
3094            vec![],
3095        );
3096        pc.add_track(track).unwrap();
3097
3098        // 2. set_local_description(our offer) — enters have-local-offer, audio gets a mid.
3099        let local_offer = pc.create_offer(None).unwrap();
3100        pc.set_local_description(Instant::now(), local_offer)
3101            .unwrap();
3102        assert_eq!(pc.signaling_state, RTCSignalingState::HaveLocalOffer);
3103        assert!(pc.rtp_transceivers[0].mid().is_some());
3104
3105        // 3. A remote (video) offer arrives — glare.
3106        let mut video_offerer = media_pc();
3107        video_offerer
3108            .add_transceiver_from_kind(
3109                RtpCodecKind::Video,
3110                Some(RTCRtpTransceiverInit {
3111                    direction: RTCRtpTransceiverDirection::Recvonly,
3112                    streams: vec![],
3113                    send_encodings: vec![],
3114                }),
3115            )
3116            .unwrap();
3117        let remote_offer = video_offerer.create_offer(None).unwrap();
3118
3119        // 4. Roll back our local offer (via set_local_description, the polite-peer path).
3120        pc.set_local_description(Instant::now(), rollback())
3121            .unwrap();
3122        assert_eq!(pc.signaling_state, RTCSignalingState::Stable);
3123        // Our audio transceiver survives (has a track/sender) but is disassociated.
3124        assert_eq!(pc.rtp_transceivers.len(), 1);
3125        assert_eq!(pc.rtp_transceivers[0].kind(), RtpCodecKind::Audio);
3126        assert!(pc.rtp_transceivers[0].sender().is_some());
3127        assert!(pc.rtp_transceivers[0].mid().is_none());
3128
3129        // 5. Apply the remote offer, then answer it.
3130        pc.set_remote_description(Instant::now(), remote_offer)
3131            .unwrap();
3132        assert_eq!(pc.signaling_state, RTCSignalingState::HaveRemoteOffer);
3133        let answer = pc.create_answer(None).unwrap();
3134        // The answer only covers the remote's video m= section; our audio track is not yet
3135        // negotiated, so it must NOT appear in the answer.
3136        assert_eq!(answer.sdp.matches("m=video").count(), 1);
3137        assert_eq!(answer.sdp.matches("m=audio").count(), 0);
3138        pc.set_local_description(Instant::now(), answer).unwrap();
3139        assert_eq!(pc.signaling_state, RTCSignalingState::Stable);
3140
3141        // 6. The locally-added track was never negotiated, so a follow-up offer must include an
3142        //    m=audio section for it (alongside the now-negotiated video section).
3143        let followup_offer = pc.create_offer(None).unwrap();
3144        assert_eq!(
3145            followup_offer.sdp.matches("m=audio").count(),
3146            1,
3147            "the added track must appear in the offer generated after rollback + answer"
3148        );
3149        assert_eq!(followup_offer.sdp.matches("m=video").count(), 1);
3150        assert!(
3151            pc.rtp_transceivers
3152                .iter()
3153                .find(|t| t.kind() == RtpCodecKind::Audio)
3154                .unwrap()
3155                .mid()
3156                .is_some(),
3157            "audio transceiver must be re-associated for the follow-up offer"
3158        );
3159    }
3160}