Skip to main content

rustrtc/
config.rs

1use crate::media::depacketizer::{DefaultDepacketizerFactory, DepacketizerFactory};
2#[cfg(feature = "std")]
3#[cfg(feature = "std")]
4use crate::peer_connection::{RtpReceiverInterceptor, RtpSenderInterceptor};
5use crate::prelude::*;
6
7/// Spawn-pinning handle. std: tokio runtime handle; no_std: unused
8/// placeholder (embassy tasks are spawned by the embedder's executor).
9#[cfg(feature = "std")]
10pub type RuntimeHandle = tokio::runtime::Handle;
11#[cfg(not(feature = "std"))]
12#[derive(Debug, Clone, Default)]
13pub struct RuntimeHandle;
14use alloc::sync::Arc;
15use core::fmt::{Debug, Formatter};
16use serde::{Deserialize, Serialize};
17
18/// Describes how credentials are conveyed for a given ICE server.
19#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
20#[serde(rename_all = "lowercase")]
21pub enum IceCredentialType {
22    #[default]
23    Password,
24    Oauth,
25}
26
27/// Mirrors the W3C `RTCIceServer` dictionary.
28#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
29pub struct IceServer {
30    pub urls: Vec<String>,
31    pub username: Option<String>,
32    pub credential: Option<String>,
33    #[serde(default)]
34    pub credential_type: IceCredentialType,
35}
36
37impl IceServer {
38    pub fn new<T: Into<Vec<String>>>(urls: T) -> Self {
39        Self {
40            urls: urls.into(),
41            username: None,
42            credential: None,
43            credential_type: IceCredentialType::default(),
44        }
45    }
46
47    pub fn with_credential(
48        mut self,
49        username: impl Into<String>,
50        credential: impl Into<String>,
51    ) -> Self {
52        self.username = Some(username.into());
53        self.credential = Some(credential.into());
54        self
55    }
56
57    pub fn credential_type(mut self, kind: IceCredentialType) -> Self {
58        self.credential_type = kind;
59        self
60    }
61}
62
63impl Default for IceServer {
64    fn default() -> Self {
65        Self::new(Vec::new())
66    }
67}
68
69#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
70pub enum IceTransportPolicy {
71    #[default]
72    All,
73    Relay,
74}
75
76/// Controls ICE TCP candidate support (RFC 6544).
77#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
78pub enum IceTcpPolicy {
79    /// Do not gather or use TCP candidates.
80    #[default]
81    Disabled,
82    /// Gather and use TCP candidates (both active and passive).
83    Enabled,
84    /// Only gather and use passive TCP candidates.
85    PassiveOnly,
86}
87
88#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
89pub enum BundlePolicy {
90    #[default]
91    Balanced,
92    MaxCompat,
93    MaxBundle,
94}
95
96#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
97pub enum RtcpMuxPolicy {
98    #[default]
99    Require,
100    Negotiate,
101}
102
103#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
104pub enum TransportMode {
105    #[default]
106    WebRtc,
107    Srtp,
108    Rtp,
109}
110
111/// Strategy for dropping packets when buffer is full.
112#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
113pub enum BufferDropStrategy {
114    #[default]
115    DropNew,
116    DropOldest,
117}
118
119/// How `external_ip` is advertised in ICE candidates.
120#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
121pub enum ExternalIpCandidateType {
122    /// Replace each non-loopback host candidate's address with `external_ip`.
123    #[default]
124    Host,
125    /// Keep the host candidate on the bind address and advertise
126    /// `external_ip` alongside it as a server-reflexive candidate
127    /// (1:1 NAT, RFC 8445 ยง5.1.1.2). WebRTC mode only.
128    ServerReflexive,
129}
130
131/// Tracks user-supplied certificate material.
132#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
133pub struct CertificateConfig {
134    pub pem_chain: Vec<String>,
135    pub private_key_pem: Option<String>,
136}
137
138/// Configuration for audio/video codecs and parameters.
139#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
140pub struct AudioCapability {
141    pub payload_type: u8,
142    pub codec_name: String,
143    pub clock_rate: u32,
144    pub channels: u8,
145    pub fmtp: Option<String>,
146    pub rtcp_fbs: Vec<String>,
147}
148
149impl Default for AudioCapability {
150    fn default() -> Self {
151        Self {
152            payload_type: 111,
153            codec_name: "opus".to_string(),
154            clock_rate: 48000,
155            channels: 2,
156            fmtp: Some("minptime=10;useinbandfec=1;stereo=1".to_string()),
157            rtcp_fbs: vec![],
158        }
159    }
160}
161
162impl AudioCapability {
163    pub fn opus() -> Self {
164        Self::default()
165    }
166
167    pub fn pcmu() -> Self {
168        Self {
169            payload_type: 0,
170            codec_name: "PCMU".to_string(),
171            clock_rate: 8000,
172            channels: 1,
173            fmtp: None,
174            rtcp_fbs: vec![],
175        }
176    }
177
178    pub fn pcma() -> Self {
179        Self {
180            payload_type: 8,
181            codec_name: "PCMA".to_string(),
182            clock_rate: 8000,
183            channels: 1,
184            fmtp: None,
185            rtcp_fbs: vec![],
186        }
187    }
188
189    pub fn g722() -> Self {
190        Self {
191            payload_type: 9,
192            codec_name: "G722".to_string(),
193            clock_rate: 8000,
194            channels: 1,
195            fmtp: None,
196            rtcp_fbs: vec![],
197        }
198    }
199
200    pub fn g729() -> Self {
201        Self {
202            payload_type: 18,
203            codec_name: "G729".to_string(),
204            clock_rate: 8000,
205            channels: 1,
206            fmtp: None,
207            rtcp_fbs: vec![],
208        }
209    }
210
211    pub fn telephone_event() -> Self {
212        Self {
213            payload_type: 101,
214            codec_name: "telephone-event".to_string(),
215            clock_rate: 8000,
216            channels: 1,
217            fmtp: Some("0-16".to_string()),
218            rtcp_fbs: vec![],
219        }
220    }
221}
222
223#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
224pub struct VideoCapability {
225    pub payload_type: u8,
226    pub codec_name: String,
227    pub clock_rate: u32,
228    pub fmtp: Option<String>,
229    pub rtcp_fbs: Vec<String>,
230    /// Associated RTX payload type (RFC 4588). When set, SDP offers include
231    /// `a=rtpmap:<pt> rtx/<clock_rate>` and `a=fmtp:<pt> apt=<primary>`.
232    /// Default `None` preserves single-codec SDP; answers still accept remote RTX.
233    #[serde(default, skip_serializing_if = "Option::is_none")]
234    pub rtx_payload_type: Option<u8>,
235}
236
237impl Default for VideoCapability {
238    fn default() -> Self {
239        Self {
240            payload_type: 96,
241            codec_name: "VP8".to_string(),
242            clock_rate: 90000,
243            fmtp: None,
244            rtcp_fbs: vec![
245                "nack".to_string(),
246                "nack pli".to_string(),
247                "ccm fir".to_string(),
248                "goog-remb".to_string(),
249                "transport-cc".to_string(),
250            ],
251            rtx_payload_type: None,
252        }
253    }
254}
255
256impl VideoCapability {
257    pub fn h264() -> Self {
258        Self {
259            payload_type: 96,
260            codec_name: "H264".to_string(),
261            clock_rate: 90000,
262            fmtp: Some("packetization-mode=1;profile-level-id=42e01f".to_string()),
263            rtcp_fbs: vec![
264                "nack".to_string(),
265                "nack pli".to_string(),
266                "ccm fir".to_string(),
267            ],
268            rtx_payload_type: None,
269        }
270    }
271
272    /// VP8 with RTX enabled (common browser interop profile).
273    pub fn vp8_with_rtx(rtx_payload_type: u8) -> Self {
274        Self {
275            rtx_payload_type: Some(rtx_payload_type),
276            ..Self::default()
277        }
278    }
279
280    /// VP9 (RFC 9628), profile 0 โ€” the browser default.
281    pub fn vp9() -> Self {
282        Self {
283            payload_type: 98,
284            codec_name: "VP9".to_string(),
285            clock_rate: 90000,
286            fmtp: Some("profile-id=0".to_string()),
287            rtcp_fbs: vec![
288                "nack".to_string(),
289                "nack pli".to_string(),
290                "ccm fir".to_string(),
291                "goog-remb".to_string(),
292                "transport-cc".to_string(),
293            ],
294            rtx_payload_type: None,
295        }
296    }
297
298    /// VP9 with RTX enabled.
299    pub fn vp9_with_rtx(rtx_payload_type: u8) -> Self {
300        Self {
301            rtx_payload_type: Some(rtx_payload_type),
302            ..Self::vp9()
303        }
304    }
305}
306
307#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
308pub struct ApplicationCapability {
309    pub sctp_port: u16,
310}
311
312impl Default for ApplicationCapability {
313    fn default() -> Self {
314        Self { sctp_port: 5000 }
315    }
316}
317
318#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
319pub enum T38FaxRateManagement {
320    #[serde(rename = "transferredTCF")]
321    #[default]
322    TransferredTCF,
323    #[serde(rename = "localTCF")]
324    LocalTCF,
325}
326
327impl core::fmt::Display for T38FaxRateManagement {
328    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
329        match self {
330            Self::TransferredTCF => write!(f, "transferredTCF"),
331            Self::LocalTCF => write!(f, "localTCF"),
332        }
333    }
334}
335
336#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
337pub enum T38UdpEC {
338    #[serde(rename = "t38UDPRedundancy")]
339    #[default]
340    T38UDPRedundancy,
341    #[serde(rename = "t38UDPFEC")]
342    T38UDPFEC,
343}
344
345impl core::fmt::Display for T38UdpEC {
346    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
347        match self {
348            Self::T38UDPRedundancy => write!(f, "t38UDPRedundancy"),
349            Self::T38UDPFEC => write!(f, "t38UDPFEC"),
350        }
351    }
352}
353
354#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
355pub struct T38Capability {
356    pub payload_type: u8,
357    /// T.38 version (0-3)
358    pub version: u8,
359    /// Max bit rate in bps (e.g. 14400, 9600, 4800, 2400)
360    pub max_bitrate: u32,
361    /// Rate management method
362    pub rate_management: T38FaxRateManagement,
363    /// Max buffer size in bytes
364    pub max_buffer: u16,
365    /// Max datagram size in bytes
366    pub max_datagram: u16,
367    /// UDP error correction method
368    pub udp_ec: T38UdpEC,
369    pub fmtp: Option<String>,
370}
371
372impl Default for T38Capability {
373    fn default() -> Self {
374        Self {
375            payload_type: 98,
376            version: 0,
377            max_bitrate: 14400,
378            rate_management: T38FaxRateManagement::default(),
379            max_buffer: 1024,
380            max_datagram: 238,
381            udp_ec: T38UdpEC::default(),
382            fmtp: None,
383        }
384    }
385}
386
387impl T38Capability {
388    pub fn default_t38() -> Self {
389        Self::default()
390    }
391}
392
393#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
394pub struct MediaCapabilities {
395    pub audio: Vec<AudioCapability>,
396    pub video: Vec<VideoCapability>,
397    pub application: Option<ApplicationCapability>,
398    pub image: Vec<T38Capability>,
399}
400
401impl Default for MediaCapabilities {
402    fn default() -> Self {
403        Self {
404            audio: vec![AudioCapability::opus(), AudioCapability::pcmu()],
405            video: vec![VideoCapability::default()],
406            application: Some(ApplicationCapability::default()),
407            image: vec![],
408        }
409    }
410}
411
412#[derive(Clone)]
413pub struct DepacketizerStrategy {
414    pub factory: Arc<dyn DepacketizerFactory>,
415}
416
417impl Default for DepacketizerStrategy {
418    fn default() -> Self {
419        Self {
420            factory: Arc::new(DefaultDepacketizerFactory),
421        }
422    }
423}
424
425impl Debug for DepacketizerStrategy {
426    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
427        self.factory.fmt(f)
428    }
429}
430
431impl PartialEq for DepacketizerStrategy {
432    fn eq(&self, other: &Self) -> bool {
433        Arc::ptr_eq(&self.factory, &other.factory)
434    }
435}
436
437impl Eq for DepacketizerStrategy {}
438
439fn default_enable_gcc() -> bool {
440    true
441}
442
443fn default_rtp_buffer_capacity() -> usize {
444    100
445}
446
447fn default_buffer_stats_log_interval() -> core::time::Duration {
448    core::time::Duration::from_secs(10)
449}
450
451/// Controls SDP generation compatibility for interoperability with legacy SIP endpoints.
452#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
453#[serde(rename_all = "snake_case")]
454pub enum SdpCompatibilityMode {
455    /// Standard WebRTC / RFC-compliant SDP output (default).
456    #[default]
457    Standard,
458    /// Compatibility mode for legacy SIP endpoints (e.g. Linphone):
459    /// omits `a=mid` unless BUNDLE is active, omits `a=rtcp-mux`.
460    LegacySip,
461}
462
463fn default_enable_upnp() -> bool {
464    false
465}
466
467fn default_upnp_lease_duration() -> u32 {
468    3600
469}
470
471fn default_upnp_discovery_timeout() -> core::time::Duration {
472    core::time::Duration::from_secs(1)
473}
474
475fn default_upnp_refresh_interval() -> core::time::Duration {
476    core::time::Duration::from_secs(30)
477}
478
479/// Primary configuration for a `PeerConnection`.
480#[derive(Debug, Clone, Serialize, Deserialize)]
481pub struct RtcConfiguration {
482    pub ice_servers: Vec<IceServer>,
483    pub ice_transport_policy: IceTransportPolicy,
484    pub bundle_policy: BundlePolicy,
485    pub rtcp_mux_policy: RtcpMuxPolicy,
486    pub certificates: Vec<CertificateConfig>,
487    pub transport_mode: TransportMode,
488    pub nack_buffer_size: usize,
489    /// Enable the TWCC + GCC bandwidth-adaptation loop: stamp outgoing RTP
490    /// with the transport-cc sequence-number extension, generate TWCC feedback
491    /// for inbound streams, and expose a sender `target_bitrate` estimate.
492    /// Default: true (no in-library send-rate limiting; apps opt in via
493    /// `RtpSender::subscribe_target_bitrate`).
494    #[serde(default = "default_enable_gcc")]
495    pub enable_gcc: bool,
496    pub media_capabilities: Option<MediaCapabilities>,
497    /// Override the advertised IP address in SDP (for NAT traversal).
498    /// When set, the `c=`, `o=`, and candidate addresses in the SDP will
499    /// use this IP instead of the local bind IP. The local bind address is
500    /// stored in `related_address` on the candidate.
501    pub external_ip: Option<String>,
502    /// How ICE candidates advertise `external_ip`.
503    #[serde(default)]
504    pub external_ip_candidate_type: ExternalIpCandidateType,
505    /// Override the advertised port in SDP `m=` line and candidates
506    /// (for NAT port forwarding).
507    ///
508    /// When set, the SDP will advertise this port instead of the local
509    /// bind port. This is useful when you have configured NAT port
510    /// forwarding (e.g. external port 30000 โ†’ local port 20000) and need
511    /// the remote peer to send RTP to the external port.
512    ///
513    /// Works independently or combined with `external_ip`.
514    /// Only applies in RTP/SRTP direct mode (`TransportMode::Rtp` /
515    /// `TransportMode::Srtp`). Not used in WebRTC mode.
516    pub external_port: Option<u16>,
517    pub bind_ip: Option<String>,
518    pub disable_ipv6: bool,
519    pub ssrc_start: u32,
520    pub stun_timeout: core::time::Duration,
521    /// Upper bound on STUN/TURN *server* candidate gathering. A slow or hung
522    /// server must not delay the offer past this: candidates that arrived in
523    /// time are advertised, the rest are dropped. `ZERO` (the default) means
524    /// unbounded โ€” the historical behaviour; embedders with tight call-setup
525    /// windows (rtcembed's WebRTC profile) set a small bound.
526    pub ice_gather_timeout: core::time::Duration,
527    /// Timeout for the ICE nomination binding check (USE-CANDIDATE).
528    /// This should be larger than `stun_timeout` to allow more retransmissions
529    /// and reduce the probability of nomination failures under packet loss.
530    pub nomination_timeout: core::time::Duration,
531    /// How long to keep collecting successful pairs after the first one
532    /// before nominating. A short grace favours fast setup but lets a
533    /// low-priority relay pair (checks complete in ~1 RTT to the TURN
534    /// server) beat a higher-priority direct pair that needs a cross-ISP
535    /// round trip (~300 ms in practice) โ€” the session then stays on relay
536    /// even though a direct path validates moments later. Port-forwarding
537    /// and tunnel use cases should raise this (e.g. 500 ms) so relay
538    /// stays a true last resort.
539    pub nomination_grace: core::time::Duration,
540    pub ice_connection_timeout: core::time::Duration,
541    /// How long without receiving any packet (STUN/DTLS/SCTP) before the ICE
542    /// transport is demoted from `Connected` to `Disconnected`.
543    ///
544    /// `Disconnected` is a recoverable state โ€” the SCTP association is **not**
545    /// torn down (see `peer_connection.rs`); the transport waits for traffic to
546    /// resume. Keep this comfortably below `ice_connection_timeout`, which is
547    /// the hard, non-recoverable failure threshold.
548    ///
549    /// Default: 30s. Raise it further (e.g. 120s) for long-lived
550    /// tunnels (SSH/port-forwarding) over lossy links where brief blackouts are
551    /// expected and must not even flap the SCTP association.
552    pub ice_disconnect_threshold: core::time::Duration,
553    /// How long to wait in `Disconnected` state before tearing down the
554    /// PeerConnection (SCTP/DTLS). When ICE goes `Disconnected` the transport
555    /// is given this long to recover before the connection is closed.
556    ///
557    /// This is distinct from `ice_connection_timeout` which operates at the
558    /// ICE transport layer. This grace period gives the application a chance
559    /// to observe `PeerConnectionState::Disconnected` and react, while still
560    /// bounding how long a dead connection lingers.
561    ///
562    /// Set to 0 to tear down immediately on ICE Disconnected.
563    /// Default: 60s
564    pub ice_disconnect_grace: core::time::Duration,
565    pub sctp_rto_initial: core::time::Duration,
566    pub sctp_rto_min: core::time::Duration,
567    pub sctp_rto_max: core::time::Duration,
568    pub sctp_max_association_retransmits: u32,
569    pub sctp_receive_window: usize,
570    pub sctp_heartbeat_interval: core::time::Duration,
571    pub sctp_max_heartbeat_failures: u32,
572    pub sctp_max_tsn_retransmits: u32,
573    pub sctp_max_burst: usize,
574    pub sctp_max_cwnd: usize,
575    /// Per-data-channel send-side buffered-amount limit in bytes (sum of
576    /// in-flight + queued payload bytes). The sender blocks when the total
577    /// exceeds this threshold, bounding per-channel peak RSS regardless of
578    /// peer speed. Default 256 KB;  0 disables the gate (unbounded).
579    pub sctp_max_buffered_amount: usize,
580    pub dtls_buffer_size: usize,
581    /// Pre-provisioned DTLS leaf certificate (DER) + PKCS#8 private key.
582    /// Required for WebRtc mode without `std` (no certificate generation
583    /// on embedded); ignored in `Rtp` mode. When unset on `std`, a fresh
584    /// self-signed certificate is generated per connection.
585    #[serde(skip)]
586    pub dtls_certificate: Option<Arc<crate::transports::dtls::Certificate>>,
587    pub rtp_start_port: Option<u16>,
588    pub rtp_end_port: Option<u16>,
589    pub ice_gather_udp_hosts: bool,
590    /// Whether to gather and advertise loopback (127.0.0.1 / ::1) host
591    /// candidates when no explicit `bind_ip` is configured.
592    ///
593    /// Default: false โ€” loopback candidates are unreachable by any remote
594    /// peer: they leak host internals in SDP and make remote agents waste
595    /// TURN permissions and connectivity checks on dead candidates (a same-
596    /// host TURN relay can even forward them back to itself). Set to `true`
597    /// for same-host testing where no non-loopback interface exists. An
598    /// explicit `bind_ip = "127.0.0.1"` is unaffected by this flag.
599    #[serde(default)]
600    pub ice_include_loopback_candidates: bool,
601    pub tcp_port_range_start: Option<u16>,
602    pub tcp_port_range_end: Option<u16>,
603    pub enable_latching: bool,
604    pub probation_max_packets: Option<u8>,
605    pub enable_ice_lite: bool,
606    /// When true, demote host candidates with private (RFC 1918) local IPs
607    /// below server-reflexive candidates in the connectivity check ordering.
608    /// This avoids DTLS handshake failures behind NATs where a host candidate
609    /// can pass a single STUN binding check but cannot sustain bidirectional
610    /// DTLS traffic.  Same-LAN pairs (both sides private) are not affected.
611    /// Default: false (standard RFC 5245 behavior).
612    #[serde(default)]
613    pub prefer_srflx_over_natted_host: bool,
614    /// Enable UPnP IGD for automatic port mapping
615    #[serde(default = "default_enable_upnp")]
616    pub enable_upnp: bool,
617    /// Advertise host candidates via mDNS (draft-ietf-rtcweb-mdns): the SDP
618    /// carries `<random>.local` hostnames instead of local IPs, and an mDNS
619    /// responder answers A/AAAA lookups for them. Real addresses are kept
620    /// internally, so connectivity is unaffected. Default: false.
621    #[serde(default)]
622    pub enable_mdns: bool,
623    /// UPnP port mapping lease duration in seconds
624    #[serde(default = "default_upnp_lease_duration")]
625    pub upnp_lease_duration: u32,
626    /// UPnP gateway discovery timeout
627    #[serde(default = "default_upnp_discovery_timeout")]
628    pub upnp_discovery_timeout: core::time::Duration,
629    /// How often to refresh UPnP port mappings before the router lease expires.
630    /// Re-issuing AddPortMapping with the same external port renews the lease on
631    /// most IGDs without deleting the mapping, so long-lived sessions survive
632    /// the default lease (3600s) without inbound path loss.
633    #[serde(default = "default_upnp_refresh_interval")]
634    pub upnp_refresh_interval: core::time::Duration,
635    #[serde(skip, default)]
636    pub depacketizer_strategy: DepacketizerStrategy,
637    #[serde(default = "default_rtp_buffer_capacity")]
638    pub rtp_buffer_capacity: usize,
639    #[serde(default)]
640    pub buffer_drop_strategy: BufferDropStrategy,
641    #[serde(default = "default_buffer_stats_log_interval")]
642    pub buffer_stats_log_interval: core::time::Duration,
643    /// Controls ICE TCP candidate support (RFC 6544).
644    /// Default: Disabled โ€” only UDP candidates are gathered and used.
645    #[serde(default)]
646    pub ice_tcp_policy: IceTcpPolicy,
647    /// Enable process-wide shared ICE UDP socket (single-port multiplexing).
648    ///
649    /// When `true`, multiple `PeerConnection`s share one `UdpSocket` bound to
650    /// `ice_udp_mux_port`. Incoming UDP packets are demultiplexed by the server
651    /// ufrag embedded in the first STUN Binding Request's `USERNAME` attribute,
652    /// and โ€” once a pair is established โ€” by the remote source address.
653    ///
654    /// Requires `ice_udp_mux_port` to be set. Useful for SFU/WHEP deployments
655    /// that need to advertise a single public UDP port for many sessions.
656    #[serde(default)]
657    pub ice_udp_mux: bool,
658    /// UDP port to bind the shared mux socket on. Required when `ice_udp_mux`
659    /// is enabled. All `PeerConnection`s sharing this port must agree on it.
660    #[serde(default)]
661    pub ice_udp_mux_port: Option<u16>,
662    /// SDP generation compatibility mode.
663    #[serde(default)]
664    pub sdp_compatibility: SdpCompatibilityMode,
665    #[serde(skip, default)]
666    pub label: Option<String>,
667    #[serde(skip, default)]
668    pub cname: Option<String>,
669    /// Runtime handle for spawning internal tasks (ICE runner, DTLS, RTCP,
670    /// etc.). When set, ALL rustrtc `tokio::spawn` calls use this handle,
671    /// pinning media tasks to a dedicated runtime instead of the caller's.
672    /// Falls back to `Handle::current()` when `None` (backward-compatible).
673    #[serde(skip, default)]
674    pub runtime_handle: Option<RuntimeHandle>,
675    /// Recording / tapping interceptors installed on every transceiver
676    /// created by this PC. Receiver interceptors fire on incoming RTP
677    /// (pre-depacketize); sender interceptors fire on outgoing RTP
678    /// (post seq/timestamp rewrite, pre-wire).
679    #[serde(skip, default)]
680    pub recorder_interceptors: RecorderInterceptors,
681}
682
683impl PartialEq for RtcConfiguration {
684    fn eq(&self, other: &Self) -> bool {
685        // Compare all fields except runtime_handle (Handle does not implement Eq).
686        self.ice_servers == other.ice_servers
687            && self.ice_transport_policy == other.ice_transport_policy
688            && self.bundle_policy == other.bundle_policy
689            && self.rtcp_mux_policy == other.rtcp_mux_policy
690            && self.certificates == other.certificates
691            && self.transport_mode == other.transport_mode
692            && self.nack_buffer_size == other.nack_buffer_size
693            && self.enable_gcc == other.enable_gcc
694            && self.media_capabilities == other.media_capabilities
695            && self.external_ip == other.external_ip
696            && self.external_ip_candidate_type == other.external_ip_candidate_type
697            && self.external_port == other.external_port
698            && self.bind_ip == other.bind_ip
699            && self.disable_ipv6 == other.disable_ipv6
700            && self.ssrc_start == other.ssrc_start
701            && self.stun_timeout == other.stun_timeout
702            && self.ice_gather_timeout == other.ice_gather_timeout
703            && self.nomination_timeout == other.nomination_timeout
704            && self.nomination_grace == other.nomination_grace
705            && self.ice_connection_timeout == other.ice_connection_timeout
706            && self.ice_disconnect_threshold == other.ice_disconnect_threshold
707            && self.ice_disconnect_grace == other.ice_disconnect_grace
708            && self.sctp_rto_initial == other.sctp_rto_initial
709            && self.sctp_rto_min == other.sctp_rto_min
710            && self.sctp_rto_max == other.sctp_rto_max
711            && self.sctp_max_association_retransmits == other.sctp_max_association_retransmits
712            && self.sctp_receive_window == other.sctp_receive_window
713            && self.sctp_heartbeat_interval == other.sctp_heartbeat_interval
714            && self.sctp_max_heartbeat_failures == other.sctp_max_heartbeat_failures
715            && self.sctp_max_tsn_retransmits == other.sctp_max_tsn_retransmits
716            && self.sctp_max_burst == other.sctp_max_burst
717            && self.sctp_max_cwnd == other.sctp_max_cwnd
718            && self.sctp_max_buffered_amount == other.sctp_max_buffered_amount
719            && self.dtls_buffer_size == other.dtls_buffer_size
720            && self.dtls_certificate == other.dtls_certificate
721            && self.rtp_start_port == other.rtp_start_port
722            && self.rtp_end_port == other.rtp_end_port
723            && self.ice_gather_udp_hosts == other.ice_gather_udp_hosts
724            && self.ice_include_loopback_candidates == other.ice_include_loopback_candidates
725            && self.tcp_port_range_start == other.tcp_port_range_start
726            && self.tcp_port_range_end == other.tcp_port_range_end
727            && self.enable_latching == other.enable_latching
728            && self.probation_max_packets == other.probation_max_packets
729            && self.enable_ice_lite == other.enable_ice_lite
730            && self.prefer_srflx_over_natted_host == other.prefer_srflx_over_natted_host
731            && self.enable_upnp == other.enable_upnp
732            && self.upnp_lease_duration == other.upnp_lease_duration
733            && self.upnp_discovery_timeout == other.upnp_discovery_timeout
734            && self.upnp_refresh_interval == other.upnp_refresh_interval
735            && self.depacketizer_strategy == other.depacketizer_strategy
736            && self.rtp_buffer_capacity == other.rtp_buffer_capacity
737            && self.buffer_drop_strategy == other.buffer_drop_strategy
738            && self.buffer_stats_log_interval == other.buffer_stats_log_interval
739            && self.ice_tcp_policy == other.ice_tcp_policy
740            && self.ice_udp_mux == other.ice_udp_mux
741            && self.ice_udp_mux_port == other.ice_udp_mux_port
742            && self.sdp_compatibility == other.sdp_compatibility
743            && self.label == other.label
744            && self.cname == other.cname
745        // runtime_handle is intentionally omitted
746    }
747}
748
749impl Eq for RtcConfiguration {}
750
751impl Default for RtcConfiguration {
752    fn default() -> Self {
753        Self {
754            ice_servers: Vec::new(),
755            ice_transport_policy: IceTransportPolicy::default(),
756            bundle_policy: BundlePolicy::default(),
757            rtcp_mux_policy: RtcpMuxPolicy::default(),
758            certificates: Vec::new(),
759            transport_mode: TransportMode::default(),
760            nack_buffer_size: 200,
761            enable_gcc: default_enable_gcc(),
762            media_capabilities: None,
763            external_ip: None,
764            external_ip_candidate_type: ExternalIpCandidateType::default(),
765            external_port: None,
766            bind_ip: None,
767            disable_ipv6: false,
768            ssrc_start: 10000,
769            stun_timeout: core::time::Duration::from_secs(5),
770            ice_gather_timeout: core::time::Duration::ZERO,
771            nomination_timeout: core::time::Duration::from_secs(10),
772            nomination_grace: core::time::Duration::from_millis(200),
773            ice_connection_timeout: core::time::Duration::from_secs(120),
774            ice_disconnect_threshold: core::time::Duration::from_secs(30),
775            ice_disconnect_grace: core::time::Duration::from_secs(60),
776            sctp_rto_initial: core::time::Duration::from_secs(3),
777            sctp_rto_min: core::time::Duration::from_millis(200),
778            sctp_rto_max: core::time::Duration::from_secs(60),
779            sctp_max_association_retransmits: 20,
780            sctp_receive_window: 128 * 1024, // 128KB - reduced for lower memory footprint
781            sctp_heartbeat_interval: core::time::Duration::from_secs(15),
782            sctp_max_heartbeat_failures: 4,
783            sctp_max_tsn_retransmits: 8,
784            sctp_max_burst: 0,                    // 0 = use default heuristic
785            sctp_max_cwnd: 256 * 1024,            // 256 KB
786            sctp_max_buffered_amount: 256 * 1024, // 256 KB
787            dtls_buffer_size: 2048,
788            dtls_certificate: None,
789            rtp_start_port: None,
790            rtp_end_port: None,
791            ice_gather_udp_hosts: true,
792            ice_include_loopback_candidates: false,
793            tcp_port_range_start: None,
794            tcp_port_range_end: None,
795            enable_latching: false,
796            probation_max_packets: None,
797            enable_ice_lite: false,
798            prefer_srflx_over_natted_host: false,
799            enable_upnp: default_enable_upnp(),
800            enable_mdns: false,
801            upnp_lease_duration: default_upnp_lease_duration(),
802            upnp_discovery_timeout: default_upnp_discovery_timeout(),
803            upnp_refresh_interval: default_upnp_refresh_interval(),
804            depacketizer_strategy: DepacketizerStrategy::default(),
805            rtp_buffer_capacity: default_rtp_buffer_capacity(),
806            buffer_drop_strategy: BufferDropStrategy::default(),
807            buffer_stats_log_interval: default_buffer_stats_log_interval(),
808            ice_tcp_policy: IceTcpPolicy::default(),
809            ice_udp_mux: false,
810            ice_udp_mux_port: None,
811            sdp_compatibility: SdpCompatibilityMode::default(),
812            label: None,
813            cname: None,
814            runtime_handle: None,
815            recorder_interceptors: RecorderInterceptors::default(),
816        }
817    }
818}
819
820pub struct RtcConfigurationBuilder {
821    inner: RtcConfiguration,
822}
823
824impl Default for RtcConfigurationBuilder {
825    fn default() -> Self {
826        Self::new()
827    }
828}
829
830/// Wrapper for interceptor lists so that `RtcConfiguration` can still derive
831/// `Debug / Clone / PartialEq / Eq` โ€” the actual interceptor trait objects
832/// are opaque and only compared by count.
833#[derive(Clone, Default)]
834pub struct RecorderInterceptors {
835    #[cfg(feature = "std")]
836    pub receivers: Vec<Arc<dyn RtpReceiverInterceptor>>,
837    #[cfg(feature = "std")]
838    pub senders: Vec<Arc<dyn RtpSenderInterceptor>>,
839}
840
841impl Debug for RecorderInterceptors {
842    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
843        #[cfg(feature = "std")]
844        {
845            return f
846                .debug_struct("RecorderInterceptors")
847                .field("receivers_len", &self.receivers.len())
848                .field("senders_len", &self.senders.len())
849                .finish();
850        }
851        #[cfg(not(feature = "std"))]
852        {
853            f.debug_struct("RecorderInterceptors").finish()
854        }
855    }
856}
857
858impl PartialEq for RecorderInterceptors {
859    fn eq(&self, other: &Self) -> bool {
860        #[cfg(feature = "std")]
861        {
862            self.receivers.len() == other.receivers.len()
863                && self.senders.len() == other.senders.len()
864        }
865        #[cfg(not(feature = "std"))]
866        {
867            true
868        }
869    }
870}
871
872impl Eq for RecorderInterceptors {}
873
874impl RtcConfigurationBuilder {
875    pub fn new() -> Self {
876        Self {
877            inner: RtcConfiguration::default(),
878        }
879    }
880
881    pub fn enable_latching(mut self, enable: bool) -> Self {
882        self.inner.enable_latching = enable;
883        self
884    }
885
886    pub fn probation_max_packets(mut self, max: Option<u8>) -> Self {
887        self.inner.probation_max_packets = max;
888        self
889    }
890
891    pub fn enable_ice_lite(mut self, enable: bool) -> Self {
892        self.inner.enable_ice_lite = enable;
893        self
894    }
895
896    pub fn prefer_srflx_over_natted_host(mut self, enable: bool) -> Self {
897        self.inner.prefer_srflx_over_natted_host = enable;
898        self
899    }
900
901    pub fn enable_upnp(mut self, enable: bool) -> Self {
902        self.inner.enable_upnp = enable;
903        self
904    }
905
906    pub fn enable_mdns(mut self, enable: bool) -> Self {
907        self.inner.enable_mdns = enable;
908        self
909    }
910
911    pub fn enable_gcc(mut self, enable: bool) -> Self {
912        self.inner.enable_gcc = enable;
913        self
914    }
915
916    pub fn upnp_lease_duration(mut self, duration_secs: u32) -> Self {
917        self.inner.upnp_lease_duration = duration_secs;
918        self
919    }
920
921    pub fn upnp_discovery_timeout(mut self, timeout: core::time::Duration) -> Self {
922        self.inner.upnp_discovery_timeout = timeout;
923        self
924    }
925
926    /// Set how often UPnP port mappings are refreshed to keep the router lease alive.
927    pub fn upnp_refresh_interval(mut self, interval: core::time::Duration) -> Self {
928        self.inner.upnp_refresh_interval = interval;
929        self
930    }
931
932    pub fn ice_server(mut self, server: IceServer) -> Self {
933        self.inner.ice_servers.push(server);
934        self
935    }
936
937    pub fn ice_transport_policy(mut self, policy: IceTransportPolicy) -> Self {
938        self.inner.ice_transport_policy = policy;
939        self
940    }
941
942    pub fn bundle_policy(mut self, policy: BundlePolicy) -> Self {
943        self.inner.bundle_policy = policy;
944        self
945    }
946
947    pub fn rtcp_mux_policy(mut self, policy: RtcpMuxPolicy) -> Self {
948        self.inner.rtcp_mux_policy = policy;
949        self
950    }
951
952    pub fn certificate(mut self, cert: CertificateConfig) -> Self {
953        self.inner.certificates.push(cert);
954        self
955    }
956
957    pub fn transport_mode(mut self, mode: TransportMode) -> Self {
958        self.inner.transport_mode = mode;
959        self
960    }
961
962    pub fn media_capabilities(mut self, capabilities: MediaCapabilities) -> Self {
963        self.inner.media_capabilities = Some(capabilities);
964        self
965    }
966
967    pub fn external_ip(mut self, ip: String) -> Self {
968        self.inner.external_ip = Some(ip);
969        self
970    }
971
972    pub fn external_ip_candidate_type(mut self, typ: ExternalIpCandidateType) -> Self {
973        self.inner.external_ip_candidate_type = typ;
974        self
975    }
976
977    pub fn external_port(mut self, port: u16) -> Self {
978        self.inner.external_port = Some(port);
979        self
980    }
981
982    pub fn bind_ip(mut self, ip: String) -> Self {
983        self.inner.bind_ip = Some(ip);
984        self
985    }
986
987    pub fn disable_ipv6(mut self, disable: bool) -> Self {
988        self.inner.disable_ipv6 = disable;
989        self
990    }
991
992    pub fn ssrc_start(mut self, start: u32) -> Self {
993        self.inner.ssrc_start = start;
994        self
995    }
996
997    pub fn stun_timeout(mut self, timeout: core::time::Duration) -> Self {
998        self.inner.stun_timeout = timeout;
999        self
1000    }
1001
1002    pub fn ice_gather_timeout(mut self, timeout: core::time::Duration) -> Self {
1003        self.inner.ice_gather_timeout = timeout;
1004        self
1005    }
1006
1007    pub fn nomination_timeout(mut self, timeout: core::time::Duration) -> Self {
1008        self.inner.nomination_timeout = timeout;
1009        self
1010    }
1011
1012    /// Override the post-first-success nomination grace (see
1013    /// [`RtcConfiguration::nomination_grace`]).
1014    pub fn nomination_grace(mut self, grace: core::time::Duration) -> Self {
1015        self.inner.nomination_grace = grace;
1016        self
1017    }
1018
1019    pub fn rtp_port_range(mut self, start: u16, end: u16) -> Self {
1020        self.inner.rtp_start_port = Some(start);
1021        self.inner.rtp_end_port = Some(end);
1022        self
1023    }
1024
1025    pub fn ice_gather_udp_hosts(mut self, enable: bool) -> Self {
1026        self.inner.ice_gather_udp_hosts = enable;
1027        self
1028    }
1029
1030    /// Gather and advertise loopback host candidates (default false). See
1031    /// `RtcConfiguration::ice_include_loopback_candidates`.
1032    pub fn ice_include_loopback_candidates(mut self, enable: bool) -> Self {
1033        self.inner.ice_include_loopback_candidates = enable;
1034        self
1035    }
1036
1037    pub fn tcp_port_range(mut self, start: u16, end: u16) -> Self {
1038        self.inner.tcp_port_range_start = Some(start);
1039        self.inner.tcp_port_range_end = Some(end);
1040        self
1041    }
1042
1043    pub fn dtls_buffer_size(mut self, size: usize) -> Self {
1044        self.inner.dtls_buffer_size = size;
1045        self
1046    }
1047
1048    /// Pre-provisioned DTLS certificate (DER leaf + PKCS#8 key). Required
1049    /// for WebRtc mode on no_std; on std a self-signed certificate is
1050    /// generated when this is unset.
1051    pub fn dtls_certificate(mut self, cert: Arc<crate::transports::dtls::Certificate>) -> Self {
1052        self.inner.dtls_certificate = Some(cert);
1053        self
1054    }
1055
1056    pub fn sctp_rto_initial(mut self, duration: core::time::Duration) -> Self {
1057        self.inner.sctp_rto_initial = duration;
1058        self
1059    }
1060
1061    pub fn sctp_rto_min(mut self, duration: core::time::Duration) -> Self {
1062        self.inner.sctp_rto_min = duration;
1063        self
1064    }
1065
1066    pub fn sctp_rto_max(mut self, duration: core::time::Duration) -> Self {
1067        self.inner.sctp_rto_max = duration;
1068        self
1069    }
1070
1071    pub fn sctp_max_association_retransmits(mut self, count: u32) -> Self {
1072        self.inner.sctp_max_association_retransmits = count;
1073        self
1074    }
1075
1076    pub fn sctp_receive_window(mut self, size: usize) -> Self {
1077        self.inner.sctp_receive_window = size;
1078        self
1079    }
1080
1081    pub fn sctp_heartbeat_interval(mut self, duration: core::time::Duration) -> Self {
1082        self.inner.sctp_heartbeat_interval = duration;
1083        self
1084    }
1085
1086    pub fn sctp_max_heartbeat_failures(mut self, count: u32) -> Self {
1087        self.inner.sctp_max_heartbeat_failures = count;
1088        self
1089    }
1090
1091    /// Set the maximum burst size for SCTP in number of MTU-sized packets.
1092    /// 0 means use the default heuristic (16 packets normal, 4 in recovery).
1093    /// For rate-limited TURN relays, a value of 2-4 can reduce burst-induced
1094    /// packet loss.
1095    pub fn sctp_max_burst(mut self, packets: usize) -> Self {
1096        self.inner.sctp_max_burst = packets;
1097        self
1098    }
1099
1100    /// Set the maximum congestion window size in bytes.
1101    /// Default is 256 KB. For high-latency TURN relays, consider 512KB-1MB.
1102    pub fn sctp_max_cwnd(mut self, size: usize) -> Self {
1103        self.inner.sctp_max_cwnd = size;
1104        self
1105    }
1106
1107    /// Per-data-channel send-side buffered-amount limit in bytes.
1108    /// Default is 256 KB. Set to 0 for unbounded (compatibility with pre-0.3.114
1109    /// behavior that had no gate). A non-zero limit bounds the sum of in-flight
1110    /// and queued payload bytes per data channel, blocking `send()`/`send_text()`
1111    /// until the buffer drains below the threshold.
1112    pub fn sctp_max_buffered_amount(mut self, bytes: usize) -> Self {
1113        self.inner.sctp_max_buffered_amount = bytes;
1114        self
1115    }
1116
1117    pub fn ice_connection_timeout(mut self, timeout: core::time::Duration) -> Self {
1118        self.inner.ice_connection_timeout = timeout;
1119        self
1120    }
1121
1122    pub fn ice_disconnect_threshold(mut self, threshold: core::time::Duration) -> Self {
1123        self.inner.ice_disconnect_threshold = threshold;
1124        self
1125    }
1126
1127    pub fn ice_disconnect_grace(mut self, grace: core::time::Duration) -> Self {
1128        self.inner.ice_disconnect_grace = grace;
1129        self
1130    }
1131
1132    pub fn rtp_buffer_capacity(mut self, capacity: usize) -> Self {
1133        self.inner.rtp_buffer_capacity = capacity;
1134        self
1135    }
1136
1137    pub fn buffer_drop_strategy(mut self, strategy: BufferDropStrategy) -> Self {
1138        self.inner.buffer_drop_strategy = strategy;
1139        self
1140    }
1141
1142    pub fn buffer_stats_log_interval(mut self, interval: core::time::Duration) -> Self {
1143        self.inner.buffer_stats_log_interval = interval;
1144        self
1145    }
1146
1147    pub fn ice_tcp_policy(mut self, policy: IceTcpPolicy) -> Self {
1148        self.inner.ice_tcp_policy = policy;
1149        self
1150    }
1151
1152    /// Enable process-wide shared ICE UDP socket (single-port multiplexing).
1153    /// Requires `ice_udp_mux_port` to also be set.
1154    pub fn ice_udp_mux(mut self, enable: bool) -> Self {
1155        self.inner.ice_udp_mux = enable;
1156        self
1157    }
1158
1159    /// Set the shared UDP mux port. Must be set when `ice_udp_mux` is enabled.
1160    pub fn ice_udp_mux_port(mut self, port: u16) -> Self {
1161        self.inner.ice_udp_mux_port = Some(port);
1162        self
1163    }
1164
1165    pub fn sdp_compatibility(mut self, mode: SdpCompatibilityMode) -> Self {
1166        self.inner.sdp_compatibility = mode;
1167        self
1168    }
1169
1170    pub fn cname(mut self, cname: String) -> Self {
1171        self.inner.cname = Some(cname);
1172        self
1173    }
1174
1175    /// Append a receiver interceptor (fires on every incoming RTP packet,
1176    /// pre-depacketize).
1177    #[cfg(feature = "std")]
1178    pub fn receiver_interceptor(mut self, interceptor: Arc<dyn RtpReceiverInterceptor>) -> Self {
1179        self.inner.recorder_interceptors.receivers.push(interceptor);
1180        self
1181    }
1182
1183    /// Append a sender interceptor (fires on every outgoing RTP packet,
1184    /// post seq/timestamp rewrite).
1185    #[cfg(feature = "std")]
1186    pub fn sender_interceptor(mut self, interceptor: Arc<dyn RtpSenderInterceptor>) -> Self {
1187        self.inner.recorder_interceptors.senders.push(interceptor);
1188        self
1189    }
1190
1191    /// Set the runtime handle for spawning internal tasks (ICE runner, DTLS,
1192    /// RTCP loops, etc.). When set, all rustrtc-internal tokio::spawn calls
1193    /// go through this runtime instead of the ambient tokio runtime.
1194    pub fn runtime_handle(mut self, handle: RuntimeHandle) -> Self {
1195        self.inner.runtime_handle = Some(handle);
1196        self
1197    }
1198
1199    pub fn build(self) -> RtcConfiguration {
1200        self.inner
1201    }
1202}
1203
1204impl From<RtcConfigurationBuilder> for RtcConfiguration {
1205    fn from(builder: RtcConfigurationBuilder) -> Self {
1206        builder.build()
1207    }
1208}
1209
1210#[cfg(all(test, feature = "std"))]
1211mod tests {
1212    use super::*;
1213    use core::time::Duration;
1214
1215    #[test]
1216    fn test_rtc_configuration_defaults() {
1217        let config = RtcConfiguration::default();
1218        assert_eq!(config.ice_connection_timeout, Duration::from_secs(120));
1219        assert_eq!(config.ice_disconnect_threshold, Duration::from_secs(30));
1220        assert_eq!(config.ice_disconnect_grace, Duration::from_secs(60));
1221        assert_eq!(config.sctp_rto_initial, Duration::from_secs(3));
1222        assert_eq!(config.sctp_rto_min, Duration::from_millis(200));
1223        assert_eq!(config.sctp_rto_max, Duration::from_secs(60));
1224        assert_eq!(config.sctp_max_association_retransmits, 20);
1225        assert_eq!(config.sctp_heartbeat_interval, Duration::from_secs(15));
1226        assert_eq!(config.sctp_max_heartbeat_failures, 4);
1227        assert_eq!(config.sctp_max_burst, 0);
1228        assert_eq!(config.sctp_max_cwnd, 256 * 1024);
1229        assert_eq!(config.rtp_buffer_capacity, 100);
1230        assert_eq!(config.buffer_drop_strategy, BufferDropStrategy::DropNew);
1231        assert_eq!(config.buffer_stats_log_interval, Duration::from_secs(10));
1232    }
1233
1234    #[test]
1235    fn test_rtc_configuration_builder() {
1236        let config = RtcConfigurationBuilder::new()
1237            .stun_timeout(Duration::from_secs(10))
1238            .build();
1239        assert_eq!(config.stun_timeout, Duration::from_secs(10));
1240        // Verify other defaults are still there
1241        assert_eq!(config.ice_connection_timeout, Duration::from_secs(120));
1242    }
1243
1244    #[test]
1245    fn test_buffer_config_builder() {
1246        let config = RtcConfigurationBuilder::new()
1247            .rtp_buffer_capacity(200)
1248            .buffer_drop_strategy(BufferDropStrategy::DropOldest)
1249            .buffer_stats_log_interval(Duration::from_secs(5))
1250            .build();
1251        assert_eq!(config.rtp_buffer_capacity, 200);
1252        assert_eq!(config.buffer_drop_strategy, BufferDropStrategy::DropOldest);
1253        assert_eq!(config.buffer_stats_log_interval, Duration::from_secs(5));
1254    }
1255
1256    #[test]
1257    fn test_sctp_builder_methods() {
1258        let config = RtcConfigurationBuilder::new()
1259            .sctp_rto_initial(Duration::from_millis(500))
1260            .sctp_rto_min(Duration::from_millis(200))
1261            .sctp_rto_max(Duration::from_secs(10))
1262            .sctp_max_association_retransmits(30)
1263            .sctp_receive_window(512 * 1024)
1264            .sctp_heartbeat_interval(Duration::from_secs(10))
1265            .sctp_max_heartbeat_failures(8)
1266            .sctp_max_burst(4)
1267            .sctp_max_cwnd(512 * 1024)
1268            .ice_connection_timeout(Duration::from_secs(60))
1269            .build();
1270
1271        assert_eq!(config.sctp_rto_initial, Duration::from_millis(500));
1272        assert_eq!(config.sctp_rto_min, Duration::from_millis(200));
1273        assert_eq!(config.sctp_rto_max, Duration::from_secs(10));
1274        assert_eq!(config.sctp_max_association_retransmits, 30);
1275        assert_eq!(config.sctp_receive_window, 512 * 1024);
1276        assert_eq!(config.sctp_heartbeat_interval, Duration::from_secs(10));
1277        assert_eq!(config.sctp_max_heartbeat_failures, 8);
1278        assert_eq!(config.sctp_max_burst, 4);
1279        assert_eq!(config.sctp_max_cwnd, 512 * 1024);
1280        assert_eq!(config.ice_connection_timeout, Duration::from_secs(60));
1281    }
1282
1283    #[test]
1284    fn test_turn_optimized_config() {
1285        // Verify a TURN-optimized configuration can be expressed cleanly
1286        let config = RtcConfigurationBuilder::new()
1287            .sctp_rto_initial(Duration::from_millis(500))
1288            .sctp_rto_min(Duration::from_millis(100))
1289            .sctp_rto_max(Duration::from_secs(10))
1290            .sctp_max_association_retransmits(30)
1291            .sctp_max_heartbeat_failures(8)
1292            .sctp_max_burst(4)
1293            .stun_timeout(Duration::from_secs(10))
1294            .nomination_timeout(Duration::from_secs(20))
1295            .build();
1296
1297        // Verify the TURN-optimized values are more aggressive than defaults
1298        let defaults = RtcConfiguration::default();
1299        assert!(config.sctp_rto_initial < defaults.sctp_rto_initial);
1300        assert!(config.sctp_rto_min < defaults.sctp_rto_min);
1301        assert!(config.sctp_rto_max < defaults.sctp_rto_max);
1302        assert!(
1303            config.sctp_max_association_retransmits > defaults.sctp_max_association_retransmits
1304        );
1305        assert!(config.sctp_max_heartbeat_failures > defaults.sctp_max_heartbeat_failures);
1306        assert!(config.sctp_max_burst > 0); // Explicit burst limit vs. heuristic
1307    }
1308
1309    #[test]
1310    fn test_external_port_defaults() {
1311        let config = RtcConfiguration::default();
1312        assert_eq!(config.external_port, None);
1313    }
1314
1315    #[test]
1316    fn test_external_port_builder() {
1317        let config = RtcConfigurationBuilder::new().external_port(30000).build();
1318        assert_eq!(config.external_port, Some(30000));
1319    }
1320
1321    #[test]
1322    fn test_external_port_with_external_ip_builder() {
1323        let config = RtcConfigurationBuilder::new()
1324            .external_ip("203.0.113.5".to_string())
1325            .external_port(30000)
1326            .build();
1327        assert_eq!(config.external_ip, Some("203.0.113.5".to_string()));
1328        assert_eq!(config.external_port, Some(30000));
1329    }
1330
1331    #[test]
1332    fn test_upnp_defaults() {
1333        let config = RtcConfiguration::default();
1334        assert!(!config.enable_upnp, "UPnP should be disabled by default");
1335        assert_eq!(config.upnp_lease_duration, 3600);
1336        assert_eq!(config.upnp_refresh_interval, Duration::from_secs(30));
1337    }
1338
1339    #[test]
1340    fn test_upnp_builder_methods() {
1341        let config = RtcConfigurationBuilder::new()
1342            .enable_upnp(false)
1343            .upnp_lease_duration(7200)
1344            .build();
1345        assert!(!config.enable_upnp);
1346        assert_eq!(config.upnp_lease_duration, 7200);
1347    }
1348
1349    #[test]
1350    fn test_upnp_refresh_interval_builder() {
1351        let config = RtcConfigurationBuilder::new()
1352            .upnp_refresh_interval(Duration::from_secs(60))
1353            .build();
1354        assert_eq!(config.upnp_refresh_interval, Duration::from_secs(60));
1355
1356        // Refresh interval participates in PartialEq
1357        let a = RtcConfigurationBuilder::new()
1358            .upnp_refresh_interval(Duration::from_secs(60))
1359            .build();
1360        let b = RtcConfigurationBuilder::new()
1361            .upnp_refresh_interval(Duration::from_secs(120))
1362            .build();
1363        assert_ne!(a, b);
1364        assert_eq!(a, a.clone());
1365    }
1366
1367    #[test]
1368    fn test_upnp_optimized_config() {
1369        let config = RtcConfigurationBuilder::new()
1370            .enable_upnp(true)
1371            .upnp_lease_duration(1800)
1372            .build();
1373
1374        assert!(config.enable_upnp);
1375        assert_eq!(config.upnp_lease_duration, 1800);
1376
1377        // Verify defaults remain for other options
1378        let defaults = RtcConfiguration::default();
1379        assert_eq!(
1380            config.ice_connection_timeout,
1381            defaults.ice_connection_timeout
1382        );
1383    }
1384
1385    #[test]
1386    fn test_ice_udp_mux_defaults() {
1387        let config = RtcConfiguration::default();
1388        assert!(
1389            !config.ice_udp_mux,
1390            "ICE UDP mux should be disabled by default"
1391        );
1392        assert_eq!(config.ice_udp_mux_port, None);
1393    }
1394
1395    #[test]
1396    fn test_ice_udp_mux_builder_methods() {
1397        let config = RtcConfigurationBuilder::new()
1398            .ice_udp_mux(true)
1399            .ice_udp_mux_port(30500)
1400            .build();
1401        assert!(config.ice_udp_mux);
1402        assert_eq!(config.ice_udp_mux_port, Some(30500));
1403    }
1404}