Skip to main content

rtc/peer_connection/configuration/
setting_engine.rs

1//! Advanced configuration engine for WebRTC peer connections.
2//!
3//! The `SettingEngine` provides low-level control over WebRTC transport behavior,
4//! timeouts, security settings, and network configuration. Unlike the standard
5//! `RTCConfiguration` which focuses on standards-compliant WebRTC settings, the
6//! `SettingEngine` allows for advanced customization and optimization for specific
7//! deployment scenarios.
8//!
9//! # Key Configuration Areas
10//!
11//! - **ICE Timeouts**: Configure connection health monitoring and keepalive intervals
12//! - **NAT Traversal**: Set up 1:1 NAT mappings for cloud deployments (e.g., AWS EC2)
13//! - **DTLS Security**: Control certificate verification and DTLS role behavior
14//! - **Replay Protection**: Configure anti-replay windows for DTLS, SRTP, and SRTCP
15//! - **Network Types**: Restrict candidate gathering to specific network types
16//!
17//! # Examples
18//!
19//! ## Configuring ICE timeouts for unstable networks
20//!
21//! ```
22//! use rtc::peer_connection::configuration::setting_engine::SettingEngine;
23//! use std::time::Duration;
24//!
25//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
26//! let mut setting_engine = SettingEngine::default();
27//!
28//! // Increase timeouts for mobile or unstable networks
29//! setting_engine.set_ice_timeouts(
30//!     Some(Duration::from_secs(10)),  // disconnected_timeout (default: 5s)
31//!     Some(Duration::from_secs(30)),  // failed_timeout (default: 25s)
32//!     Some(Duration::from_secs(3)),   // keep_alive_interval (default: 2s)
33//! );
34//!
35//! // Use with RTCConfiguration
36//! // let mut config = RTCConfiguration::default();
37//! // config.setting_engine = Some(setting_engine);
38//! # Ok(())
39//! # }
40//! ```
41//!
42//! ## Setting up 1:1 NAT for cloud deployments
43//!
44//! ```
45//! use rtc::peer_connection::configuration::setting_engine::SettingEngine;
46//! use rtc::peer_connection::transport::RTCIceCandidateType;
47//!
48//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
49//! let mut setting_engine = SettingEngine::default();
50//!
51//! // Configure for AWS EC2 instance with Elastic IP
52//! // Private IP: 10.0.1.5, Public IP: 54.123.45.67
53//! setting_engine.set_nat_1to1_ips(
54//!     vec!["54.123.45.67".to_string()],
55//!     RTCIceCandidateType::Host, // Use public IP for host candidates
56//! );
57//!
58//! // This tells ICE to advertise the public IP instead of the private one
59//! # Ok(())
60//! # }
61//! ```
62//!
63//! ## Configuring replay protection for security-critical applications
64//!
65//! ```
66//! use rtc::peer_connection::configuration::setting_engine::SettingEngine;
67//!
68//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
69//! let mut setting_engine = SettingEngine::default();
70//!
71//! // Increase replay protection window sizes
72//! setting_engine.set_dtls_replay_protection_window(128);  // DTLS anti-replay
73//! setting_engine.set_srtp_replay_protection_window(256);  // SRTP anti-replay
74//! setting_engine.set_srtcp_replay_protection_window(128); // SRTCP anti-replay
75//!
76//! // Larger windows protect against more packet reordering but use more memory
77//! # Ok(())
78//! # }
79//! ```
80//!
81//! ## Restricting network types for controlled environments
82//!
83//! ```
84//! use rtc::peer_connection::configuration::setting_engine::SettingEngine;
85//! use ice::network_type::NetworkType;
86//!
87//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
88//! let mut setting_engine = SettingEngine::default();
89//!
90//! // Only gather IPv4 UDP candidates (no IPv6, no TCP)
91//! setting_engine.set_network_types(vec![NetworkType::Udp4]);
92//!
93//! // This reduces candidate gathering time and SDP size
94//! # Ok(())
95//! # }
96//! ```
97//!
98//! # See Also
99//!
100//! - [`RTCConfiguration`](crate::peer_connection::configuration::RTCConfiguration) - Standard WebRTC configuration
101//! - [`MediaEngine`](crate::peer_connection::configuration::media_engine::MediaEngine) - Codec registration
102//! - [RFC 8445 - ICE](https://datatracker.ietf.org/doc/html/rfc8445)
103//! - [RFC 8446 - TLS 1.3 (DTLS basis)](https://datatracker.ietf.org/doc/html/rfc8446)
104
105//TODO:#[cfg(test)]
106//mod setting_engine_test;
107
108use std::net::IpAddr;
109use std::sync::Arc;
110
111use dtls::extension::extension_use_srtp::SrtpProtectionProfile;
112//TODO: use ice::agent::agent_config::{InterfaceFilterFn, IpFilterFn};
113//TODO: use ice::mdns::MulticastDnsMode;
114use ice::network_type::NetworkType;
115//TODO: use ice::udp_network::UDPNetwork;
116use crate::peer_connection::transport::dtls::role::RTCDtlsRole;
117use crate::peer_connection::transport::ice::candidate_type::RTCIceCandidateType;
118use ice::mdns::MulticastDnsMode;
119use shared::error::{Error, Result};
120use std::time::Duration;
121
122/// Equal to UDP MTU
123pub(crate) const RECEIVE_MTU: usize = 1460;
124
125/// ICE timeout configuration for connection health monitoring.
126///
127/// These timeouts control how ICE determines connection state transitions
128/// and when to send keepalive packets. Adjust these for different network
129/// conditions (mobile, satellite, etc.).
130#[derive(Default, Clone)]
131pub struct Timeout {
132    /// Duration without network activity before ICE is considered disconnected.
133    /// Default: 5 seconds.
134    pub ice_disconnected_timeout: Option<Duration>,
135
136    /// Duration without network activity before ICE is considered failed after disconnected.
137    /// Default: 25 seconds.
138    pub ice_failed_timeout: Option<Duration>,
139
140    /// How often ICE sends keepalive packets when there's no media flow.
141    /// Default: 2 seconds. If media is flowing, no keepalives are sent.
142    pub ice_keepalive_interval: Option<Duration>,
143
144    /// Minimum wait time before accepting host candidates.
145    pub ice_host_acceptance_min_wait: Option<Duration>,
146
147    /// Minimum wait time before accepting server reflexive candidates.
148    pub ice_srflx_acceptance_min_wait: Option<Duration>,
149
150    /// Minimum wait time before accepting peer reflexive candidates.
151    pub ice_prflx_acceptance_min_wait: Option<Duration>,
152
153    /// Minimum wait time before accepting relay candidates.
154    pub ice_relay_acceptance_min_wait: Option<Duration>,
155}
156
157/// MulticastDNS configuration for mDNS.
158#[derive(Clone)]
159pub struct MulticastDNS {
160    /// Duration without network activity before mDNS query is considered failed.
161    /// Default: 10 seconds.
162    pub timeout: Option<Duration>,
163    /// Represents the different Multicast modes that ICE can run.
164    pub mode: MulticastDnsMode,
165    /// Controls the local name for this agent. If none is specified a random one will be generated.
166    pub local_name: String,
167    /// Control mDNS local IP address
168    pub local_ip: Option<IpAddr>,
169}
170
171impl Default for MulticastDNS {
172    fn default() -> Self {
173        Self {
174            timeout: Some(Duration::from_secs(10)),
175            mode: MulticastDnsMode::Disabled, //TODO: Re-enable it to QueryOnly
176            local_name: "".to_string(),
177            local_ip: None,
178        }
179    }
180}
181
182/// ICE candidate gathering and filtering configuration.
183///
184/// Controls which types of candidates are gathered, NAT mappings,
185/// and custom network filtering.
186#[derive(Default, Clone)]
187pub struct Candidates {
188    /// Enable ICE Lite mode (only respond to connectivity checks, don't initiate).
189    pub ice_lite: bool,
190
191    /// Restrict candidate gathering to specific network types (e.g., UDP4, UDP6, TCP4).
192    pub ice_network_types: Vec<NetworkType>,
193    //TODO: pub interface_filter: Arc<Option<InterfaceFilterFn>>,
194    //TODO: pub ip_filter: Arc<Option<IpFilterFn>>,
195    /// External IP addresses for 1:1 NAT mappings (e.g., AWS Elastic IP).
196    pub nat_1to1_ips: Vec<String>,
197
198    /// Candidate type to use for NAT 1:1 IPs (Host or Srflx).
199    pub nat_1to1_ip_candidate_type: RTCIceCandidateType,
200    /// Static ICE username fragment (ufrag) for reproducible sessions.
201    pub username_fragment: String,
202
203    /// Static ICE password for reproducible sessions.
204    pub password: String,
205
206    /// Whether to discard local candidates during ICE restart.
207    pub discard_local_candidates_during_ice_restart: bool,
208
209    /// Allow gathering loopback candidates (useful for some VM configurations).
210    /// Note: This is non-standard per RFC 8445.
211    pub include_loopback_candidate: bool,
212}
213
214/// Replay attack protection window sizes.
215///
216/// Larger windows provide better protection against packet reordering
217/// but consume more memory. Set to 0 to disable replay protection (not recommended).
218#[derive(Default, Copy, Clone)]
219pub struct ReplayProtection {
220    /// DTLS replay protection window size (in packets).
221    pub dtls: usize,
222
223    /// SRTP replay protection window size (in packets).
224    pub srtp: usize,
225
226    /// SRTCP replay protection window size (in packets).
227    pub srtcp: usize,
228}
229
230/// Maximum message size for SCTP data channels.
231///
232/// Controls the maximum size of messages that can be sent through data channels.
233/// Per [RFC 8841](https://datatracker.ietf.org/doc/html/rfc8841), the default is 64KB.
234#[derive(Copy, Clone)]
235pub enum SctpMaxMessageSize {
236    /// Fixed maximum message size in bytes.
237    Bounded(u32),
238
239    /// No practical limit (uses MAX_MESSAGE_SIZE internally).
240    Unbounded,
241}
242
243impl SctpMaxMessageSize {
244    /// Default message size per RFC 8841 (64KB).
245    pub const DEFAULT_MESSAGE_SIZE: u32 = 65536;
246
247    /// Maximum message size (256KB).
248    pub const MAX_MESSAGE_SIZE: u32 = 262144;
249
250    /// Returns the message size as `usize`.
251    pub fn as_usize(&self) -> usize {
252        match self {
253            Self::Bounded(result) => *result as usize,
254            Self::Unbounded => Self::MAX_MESSAGE_SIZE as usize,
255        }
256    }
257}
258
259impl Default for SctpMaxMessageSize {
260    fn default() -> Self {
261        // https://datatracker.ietf.org/doc/html/rfc8841#section-6.1-4
262        // > If the SDP "max-message-size" attribute is not present, the default value is 64K.
263        Self::Bounded(Self::DEFAULT_MESSAGE_SIZE)
264    }
265}
266
267/// Advanced configuration engine for fine-tuning WebRTC behavior.
268///
269/// `SettingEngine` provides granular control over transport-level settings that
270/// are not exposed through the standard WebRTC API. Use this to optimize for
271/// specific deployment scenarios, network conditions, or security requirements.
272///
273/// # Configuration Categories
274///
275/// - **Timeout**: ICE connection health monitoring and keepalive
276/// - **Candidates**: NAT traversal, network filtering, ICE credentials
277/// - **Replay Protection**: Anti-replay window sizes for DTLS/SRTP/SRTCP
278/// - **DTLS**: Certificate verification and role selection
279/// - **Media Engine**: Codec registration behavior
280/// - **SCTP**: Data channel message size limits
281///
282/// # Examples
283///
284/// ## Basic usage with RTCConfiguration
285///
286/// ```
287/// use rtc::peer_connection::configuration::setting_engine::SettingEngine;
288/// use std::time::Duration;
289///
290/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
291/// let mut setting_engine = SettingEngine::default();
292///
293/// // Configure timeouts
294/// setting_engine.set_ice_timeouts(
295///     Some(Duration::from_secs(10)),
296///     Some(Duration::from_secs(30)),
297///     Some(Duration::from_secs(3)),
298/// );
299///
300/// // Enable loopback for testing
301/// setting_engine.set_include_loopback_candidate(true);
302///
303/// // Use with peer connection configuration
304/// // let api = APIBuilder::new().with_setting_engine(setting_engine).build();
305/// # Ok(())
306/// # }
307/// ```
308///
309/// # See Also
310///
311/// - [W3C WebRTC Spec](https://www.w3.org/TR/webrtc/)
312/// - [RFC 8445 - ICE](https://datatracker.ietf.org/doc/html/rfc8445)
313#[derive(Default, Clone)]
314pub struct SettingEngine {
315    pub(crate) timeout: Timeout,
316    pub(crate) candidates: Candidates,
317    pub(crate) multicast_dns: MulticastDNS,
318    pub(crate) replay_protection: ReplayProtection,
319    pub(crate) sdp_media_level_fingerprints: bool,
320    pub(crate) answering_dtls_role: RTCDtlsRole,
321    pub(crate) disable_certificate_fingerprint_verification: bool,
322    pub(crate) allow_insecure_verification_algorithm: bool,
323
324    //BufferFactory                             :func(packetType packetio.BufferPacketType, ssrc uint32) io.ReadWriteCloser,
325    //iceTCPMux                                 :ice.TCPMux,?
326    //iceProxyDialer                            :proxy.Dialer,?
327    //TODO: pub(crate) udp_network: UDPNetwork,
328    pub(crate) disable_media_engine_copy: bool,
329    pub(crate) disable_media_engine_multiple_codecs: bool,
330    pub(crate) srtp_protection_profiles: Vec<SrtpProtectionProfile>,
331    pub(crate) receive_mtu: usize,
332    pub(crate) mid_generator: Option<Arc<dyn Fn(isize) -> String + Send + Sync>>,
333    /// Determines the max size of any message that may be sent through an SCTP transport.
334    pub(crate) sctp_max_message_size: SctpMaxMessageSize,
335    pub(crate) ignore_rid_pause_for_recv: bool,
336    pub(crate) write_ssrc_attributes_for_simulcast: bool,
337}
338
339impl SettingEngine {
340    /// Returns the configured receive MTU, or the default if not set.
341    pub(crate) fn get_receive_mtu(&self) -> usize {
342        if self.receive_mtu != 0 {
343            self.receive_mtu
344        } else {
345            RECEIVE_MTU
346        }
347    }
348
349    /// Overrides the default SRTP protection profiles.
350    ///
351    /// SRTP profiles define the encryption algorithms used for media streams.
352    /// Only override this if you need specific security requirements or
353    /// compatibility with non-standard implementations.
354    ///
355    /// # Parameters
356    ///
357    /// * `profiles` - List of SRTP protection profiles to use
358    ///
359    /// # Examples
360    ///
361    /// ```
362    /// use rtc::peer_connection::configuration::setting_engine::SettingEngine;
363    /// use dtls::extension::extension_use_srtp::SrtpProtectionProfile;
364    ///
365    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
366    /// let mut setting_engine = SettingEngine::default();
367    ///
368    /// // Use specific SRTP profile
369    /// setting_engine.set_srtp_protection_profiles(vec![
370    ///     SrtpProtectionProfile::Srtp_Aes128_Cm_Hmac_Sha1_80,
371    /// ]);
372    /// # Ok(())
373    /// # }
374    /// ```
375    pub fn set_srtp_protection_profiles(&mut self, profiles: Vec<SrtpProtectionProfile>) {
376        self.srtp_protection_profiles = profiles
377    }
378
379    /// Configures ICE timeout behavior for connection health monitoring.
380    ///
381    /// These timeouts control when ICE transitions between connection states
382    /// and when keepalive packets are sent. Adjust these for different network
383    /// conditions:
384    /// - Increase for unstable networks (mobile, satellite)
385    /// - Decrease for low-latency applications
386    ///
387    /// # Parameters
388    ///
389    /// * `disconnected_timeout` - Duration without activity before considered disconnected (default: 5s)
390    /// * `failed_timeout` - Duration after disconnected before considered failed (default: 25s)
391    /// * `keep_alive_interval` - How often to send keepalives when idle (default: 2s)
392    ///
393    /// # Examples
394    ///
395    /// ```
396    /// use rtc::peer_connection::configuration::setting_engine::SettingEngine;
397    /// use std::time::Duration;
398    ///
399    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
400    /// let mut setting_engine = SettingEngine::default();
401    ///
402    /// // Conservative settings for mobile networks
403    /// setting_engine.set_ice_timeouts(
404    ///     Some(Duration::from_secs(10)),  // Longer before disconnected
405    ///     Some(Duration::from_secs(40)),  // Longer before failed
406    ///     Some(Duration::from_secs(5)),   // Less frequent keepalives
407    /// );
408    /// # Ok(())
409    /// # }
410    /// ```
411    ///
412    /// # See Also
413    ///
414    /// - [RFC 8445 §16 - Timers](https://datatracker.ietf.org/doc/html/rfc8445#section-16)
415    pub fn set_ice_timeouts(
416        &mut self,
417        disconnected_timeout: Option<Duration>,
418        failed_timeout: Option<Duration>,
419        keep_alive_interval: Option<Duration>,
420    ) {
421        self.timeout.ice_disconnected_timeout = disconnected_timeout;
422        self.timeout.ice_failed_timeout = failed_timeout;
423        self.timeout.ice_keepalive_interval = keep_alive_interval;
424    }
425
426    /// Sets minimum wait time before accepting host candidates.
427    ///
428    /// # Parameters
429    ///
430    /// * `t` - Minimum wait duration, or `None` for immediate acceptance
431    pub fn set_host_acceptance_min_wait(&mut self, t: Option<Duration>) {
432        self.timeout.ice_host_acceptance_min_wait = t;
433    }
434
435    /// Sets minimum wait time before accepting server reflexive candidates.
436    ///
437    /// Server reflexive candidates are discovered through STUN servers.
438    ///
439    /// # Parameters
440    ///
441    /// * `t` - Minimum wait duration, or `None` for immediate acceptance
442    pub fn set_srflx_acceptance_min_wait(&mut self, t: Option<Duration>) {
443        self.timeout.ice_srflx_acceptance_min_wait = t;
444    }
445
446    /// Sets minimum wait time before accepting peer reflexive candidates.
447    ///
448    /// Peer reflexive candidates are discovered during connectivity checks.
449    ///
450    /// # Parameters
451    ///
452    /// * `t` - Minimum wait duration, or `None` for immediate acceptance
453    pub fn set_prflx_acceptance_min_wait(&mut self, t: Option<Duration>) {
454        self.timeout.ice_prflx_acceptance_min_wait = t;
455    }
456
457    /// Sets minimum wait time before accepting relay candidates.
458    ///
459    /// Relay candidates are provided by TURN servers.
460    ///
461    /// # Parameters
462    ///
463    /// * `t` - Minimum wait duration, or `None` for immediate acceptance
464    pub fn set_relay_acceptance_min_wait(&mut self, t: Option<Duration>) {
465        self.timeout.ice_relay_acceptance_min_wait = t;
466    }
467
468    /*todo:
469    /// set_udp_network allows ICE traffic to come through Ephemeral or UDPMux.
470    /// UDPMux drastically simplifying deployments where ports will need to be opened/forwarded.
471    /// UDPMux should be started prior to creating PeerConnections.
472    pub fn set_udp_network(&mut self, udp_network: UDPNetwork) {
473        self.udp_network = udp_network;
474    }*/
475
476    /// Configures ICE Lite mode.
477    ///
478    /// In ICE Lite mode, the agent only responds to connectivity checks
479    /// but does not initiate them. This is typically used by servers that
480    /// have public IP addresses and don't need full ICE functionality.
481    ///
482    /// # Parameters
483    ///
484    /// * `lite` - `true` to enable ICE Lite, `false` for full ICE
485    ///
486    /// # Examples
487    ///
488    /// ```
489    /// use rtc::peer_connection::configuration::setting_engine::SettingEngine;
490    ///
491    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
492    /// let mut setting_engine = SettingEngine::default();
493    ///
494    /// // Enable ICE Lite for a publicly accessible server
495    /// setting_engine.set_lite(true);
496    /// # Ok(())
497    /// # }
498    /// ```
499    ///
500    /// # See Also
501    ///
502    /// - [RFC 8445 §2.7 - Lite Implementation](https://datatracker.ietf.org/doc/html/rfc8445#section-2.7)
503    pub fn set_lite(&mut self, lite: bool) {
504        self.candidates.ice_lite = lite;
505    }
506
507    /// Restricts candidate gathering to specific network types.
508    ///
509    /// This reduces the number of candidates gathered, which can speed up
510    /// connection establishment and reduce SDP size. Useful when you know
511    /// certain network types won't work in your deployment.
512    ///
513    /// # Parameters
514    ///
515    /// * `candidate_types` - List of allowed network types (e.g., UDP4, UDP6, TCP4)
516    ///
517    /// # Examples
518    ///
519    /// ```
520    /// use rtc::peer_connection::configuration::setting_engine::SettingEngine;
521    /// use ice::network_type::NetworkType;
522    ///
523    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
524    /// let mut setting_engine = SettingEngine::default();
525    ///
526    /// // Only use IPv4 UDP (most common case)
527    /// setting_engine.set_network_types(vec![NetworkType::Udp4]);
528    ///
529    /// // Or allow both IPv4 and IPv6 UDP
530    /// setting_engine.set_network_types(vec![
531    ///     NetworkType::Udp4,
532    ///     NetworkType::Udp6,
533    /// ]);
534    /// # Ok(())
535    /// # }
536    /// ```
537    pub fn set_network_types(&mut self, candidate_types: Vec<NetworkType>) {
538        self.candidates.ice_network_types = candidate_types;
539    }
540
541    /*todo:
542    /// set_interface_filter sets the filtering functions when gathering ICE candidates
543    /// This can be used to exclude certain network interfaces from ICE. Which may be
544    /// useful if you know a certain interface will never succeed, or if you wish to reduce
545    /// the amount of information you wish to expose to the remote peer
546    pub fn set_interface_filter(&mut self, filter: InterfaceFilterFn) {
547        self.candidates.interface_filter = Arc::new(Some(filter));
548    }
549
550    /// set_ip_filter sets the filtering functions when gathering ICE candidates
551    /// This can be used to exclude certain ip from ICE. Which may be
552    /// useful if you know a certain ip will never succeed, or if you wish to reduce
553    /// the amount of information you wish to expose to the remote peer
554    pub fn set_ip_filter(&mut self, filter: IpFilterFn) {
555        self.candidates.ip_filter = Arc::new(Some(filter));
556    }*/
557
558    /// Configures 1:1 NAT IP mapping for cloud deployments.
559    ///
560    /// This is essential for WebRTC servers running on cloud instances (e.g., AWS EC2)
561    /// that have a private IP address but are accessible via a public IP through 1:1 NAT.
562    ///
563    /// # Parameters
564    ///
565    /// * `ips` - List of external/public IP addresses
566    /// * `candidate_type` - How to advertise the public IPs:
567    ///   - `RTCIceCandidateType::Host`: Replace private IP with public IP (mDNS disabled)
568    ///   - `RTCIceCandidateType::Srflx`: Add public IP as server reflexive candidate
569    ///
570    /// # Examples
571    ///
572    /// ```
573    /// use rtc::peer_connection::configuration::setting_engine::SettingEngine;
574    /// use rtc::peer_connection::transport::RTCIceCandidateType;
575    ///
576    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
577    /// let mut setting_engine = SettingEngine::default();
578    ///
579    /// // AWS EC2: Private IP 10.0.1.5, Elastic IP 54.123.45.67
580    /// setting_engine.set_nat_1to1_ips(
581    ///     vec!["54.123.45.67".to_string()],
582    ///     RTCIceCandidateType::Host,
583    /// );
584    ///
585    /// // Or use Srflx to keep private IP available
586    /// setting_engine.set_nat_1to1_ips(
587    ///     vec!["54.123.45.67".to_string()],
588    ///     RTCIceCandidateType::Srflx,
589    /// );
590    /// # Ok(())
591    /// # }
592    /// ```
593    ///
594    /// # Notes
595    ///
596    /// - With `Host` type, the private IP is not advertised to the peer
597    /// - With `Srflx` type, both private and public IPs are available
598    /// - Cannot use STUN servers when using `Srflx` type
599    /// - Cannot use with mDNS when using `Host` type
600    pub fn set_nat_1to1_ips(&mut self, ips: Vec<String>, candidate_type: RTCIceCandidateType) {
601        self.candidates.nat_1to1_ips = ips;
602        self.candidates.nat_1to1_ip_candidate_type = candidate_type;
603    }
604
605    /// Sets the DTLS role to use when answering an offer.
606    ///
607    /// The DTLS role determines whether this peer acts as a DTLS client
608    /// (initiating the handshake) or server (waiting for handshake). Normally
609    /// this is negotiated automatically, but you can override it for debugging
610    /// or compatibility with non-compliant implementations.
611    ///
612    /// # Parameters
613    ///
614    /// * `role` - DTLS role to use:
615    ///   - `DTLSRole::Client`: Act as DTLS client, send ClientHello
616    ///   - `DTLSRole::Server`: Act as DTLS server, wait for ClientHello
617    ///
618    /// # Returns
619    ///
620    /// * `Ok(())` on success
621    /// * `Err(Error)` if role is not Client or Server
622    ///
623    /// # Examples
624    ///
625    /// ```
626    /// use rtc::peer_connection::configuration::setting_engine::SettingEngine;
627    /// use rtc::peer_connection::transport::RTCDtlsRole;
628    ///
629    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
630    /// let mut setting_engine = SettingEngine::default();
631    ///
632    /// // Force this peer to always act as DTLS client when answering
633    /// setting_engine.set_answering_dtls_role(RTCDtlsRole::Client)?;
634    /// # Ok(())
635    /// # }
636    /// ```
637    ///
638    /// # See Also
639    ///
640    /// - [RFC 8842 - DTLS for WebRTC](https://datatracker.ietf.org/doc/html/rfc8842)
641    pub fn set_answering_dtls_role(&mut self, role: RTCDtlsRole) -> Result<()> {
642        if role != RTCDtlsRole::Client && role != RTCDtlsRole::Server {
643            return Err(Error::ErrSettingEngineSetAnsweringDTLSRole);
644        }
645
646        self.answering_dtls_role = role;
647        Ok(())
648    }
649
650    pub fn set_multicast_dns_timeout(&mut self, timeout: Option<Duration>) {
651        self.multicast_dns.timeout = timeout;
652    }
653
654    /// set_ice_multicast_dns_mode controls if ice queries and generates mDNS ICE Candidates
655    pub fn set_multicast_dns_mode(&mut self, multicast_dns_mode: MulticastDnsMode) {
656        self.multicast_dns.mode = multicast_dns_mode
657    }
658
659    /// set_ice_multicast_dns_host_name sets a static HostName to be used by ice instead of generating one on startup
660    /// This should only be used for a single PeerConnection. Having multiple PeerConnections with the same HostName will cause
661    /// undefined behavior
662    pub fn set_multicast_dns_local_name(&mut self, local_name: String) {
663        self.multicast_dns.local_name = local_name;
664    }
665
666    pub fn set_multicast_dns_local_ip(&mut self, local_ip: Option<IpAddr>) {
667        self.multicast_dns.local_ip = local_ip;
668    }
669
670    /// Sets static ICE credentials for reproducible sessions.
671    ///
672    /// By default, ICE generates random credentials (ufrag/password) for each
673    /// session. Setting static credentials allows for signalless WebRTC or
674    /// reproducible testing environments.
675    ///
676    /// # Parameters
677    ///
678    /// * `username_fragment` - ICE username fragment (ufrag)
679    /// * `password` - ICE password
680    ///
681    /// # Examples
682    ///
683    /// ```
684    /// use rtc::peer_connection::configuration::setting_engine::SettingEngine;
685    ///
686    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
687    /// let mut setting_engine = SettingEngine::default();
688    ///
689    /// // Set static credentials for reproducible testing
690    /// setting_engine.set_ice_credentials(
691    ///     "test_ufrag".to_string(),
692    ///     "test_password".to_string(),
693    /// );
694    /// # Ok(())
695    /// # }
696    /// ```
697    ///
698    /// # Security Note
699    ///
700    /// Only use static credentials in controlled environments. Random credentials
701    /// provide better security for production deployments.
702    pub fn set_ice_credentials(&mut self, username_fragment: String, password: String) {
703        self.candidates.username_fragment = username_fragment;
704        self.candidates.password = password;
705    }
706
707    /// Disables DTLS certificate fingerprint verification.
708    ///
709    /// **Warning**: Disabling fingerprint verification removes a critical
710    /// security check and should only be used for testing or debugging.
711    ///
712    /// # Parameters
713    ///
714    /// * `is_disabled` - `true` to disable verification, `false` to enable
715    ///
716    /// # Examples
717    ///
718    /// ```
719    /// use rtc::peer_connection::configuration::setting_engine::SettingEngine;
720    ///
721    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
722    /// let mut setting_engine = SettingEngine::default();
723    ///
724    /// // Only for testing/debugging!
725    /// setting_engine.disable_certificate_fingerprint_verification(true);
726    /// # Ok(())
727    /// # }
728    /// ```
729    pub fn disable_certificate_fingerprint_verification(&mut self, is_disabled: bool) {
730        self.disable_certificate_fingerprint_verification = is_disabled;
731    }
732
733    /// Allows insecure signature verification algorithms.
734    ///
735    /// Some signature algorithms are known to be vulnerable or deprecated.
736    /// This setting allows their use for compatibility with legacy systems.
737    ///
738    /// **Warning**: Only enable this if absolutely necessary for compatibility.
739    ///
740    /// # Parameters
741    ///
742    /// * `is_allowed` - `true` to allow insecure algorithms, `false` to disallow
743    pub fn allow_insecure_verification_algorithm(&mut self, is_allowed: bool) {
744        self.allow_insecure_verification_algorithm = is_allowed;
745    }
746
747    /// Sets the DTLS replay protection window size.
748    ///
749    /// The replay protection window prevents attackers from re-sending captured
750    /// packets. Larger windows protect against more packet reordering but use
751    /// more memory. Set to 0 to disable (not recommended).
752    ///
753    /// # Parameters
754    ///
755    /// * `n` - Window size in packets (0 = disabled)
756    ///
757    /// # Examples
758    ///
759    /// ```
760    /// use rtc::peer_connection::configuration::setting_engine::SettingEngine;
761    ///
762    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
763    /// let mut setting_engine = SettingEngine::default();
764    ///
765    /// // Increase window for high-latency or reordering networks
766    /// setting_engine.set_dtls_replay_protection_window(128);
767    /// # Ok(())
768    /// # }
769    /// ```
770    ///
771    /// # See Also
772    ///
773    /// - [RFC 6347 §4.1.2.6 - Anti-Replay](https://datatracker.ietf.org/doc/html/rfc6347#section-4.1.2.6)
774    pub fn set_dtls_replay_protection_window(&mut self, n: usize) {
775        self.replay_protection.dtls = n;
776    }
777
778    /// Sets the SRTP replay protection window size.
779    ///
780    /// SRTP replay protection prevents replay attacks on encrypted media packets.
781    /// Adjust the window size based on expected packet reordering in your network.
782    ///
783    /// # Parameters
784    ///
785    /// * `n` - Window size in packets (0 = disabled, not recommended)
786    ///
787    /// # Examples
788    ///
789    /// ```
790    /// use rtc::peer_connection::configuration::setting_engine::SettingEngine;
791    ///
792    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
793    /// let mut setting_engine = SettingEngine::default();
794    ///
795    /// // Standard size for most applications
796    /// setting_engine.set_srtp_replay_protection_window(256);
797    /// # Ok(())
798    /// # }
799    /// ```
800    ///
801    /// # See Also
802    ///
803    /// - [RFC 3711 §3.3.2 - Replay Protection](https://datatracker.ietf.org/doc/html/rfc3711#section-3.3.2)
804    pub fn set_srtp_replay_protection_window(&mut self, n: usize) {
805        self.replay_protection.srtp = n;
806    }
807
808    /// Sets the SRTCP replay protection window size.
809    ///
810    /// SRTCP replay protection applies to RTCP control packets. Usually
811    /// a smaller window is sufficient since RTCP packets are less frequent.
812    ///
813    /// # Parameters
814    ///
815    /// * `n` - Window size in packets (0 = disabled, not recommended)
816    ///
817    /// # Examples
818    ///
819    /// ```
820    /// use rtc::peer_connection::configuration::setting_engine::SettingEngine;
821    ///
822    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
823    /// let mut setting_engine = SettingEngine::default();
824    ///
825    /// // Smaller window sufficient for RTCP
826    /// setting_engine.set_srtcp_replay_protection_window(64);
827    /// # Ok(())
828    /// # }
829    /// ```
830    pub fn set_srtcp_replay_protection_window(&mut self, n: usize) {
831        self.replay_protection.srtcp = n;
832    }
833
834    /// Allows gathering of loopback candidates.
835    ///
836    /// By default, loopback candidates (127.x.x.x, ::1) are not gathered per
837    /// RFC 8445. However, some VM configurations map public IPs to the loopback
838    /// interface, making this necessary.
839    ///
840    /// # Parameters
841    ///
842    /// * `allow_loopback` - `true` to gather loopback candidates, `false` to skip
843    ///
844    /// # Examples
845    ///
846    /// ```
847    /// use rtc::peer_connection::configuration::setting_engine::SettingEngine;
848    ///
849    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
850    /// let mut setting_engine = SettingEngine::default();
851    ///
852    /// // Enable for certain VM configurations
853    /// setting_engine.set_include_loopback_candidate(true);
854    /// # Ok(())
855    /// # }
856    /// ```
857    ///
858    /// # Note
859    ///
860    /// This is non-standard behavior per [RFC 8445 §5.1.1.1](https://www.rfc-editor.org/rfc/rfc8445#section-5.1.1.1).
861    /// Use with caution.
862    pub fn set_include_loopback_candidate(&mut self, allow_loopback: bool) {
863        self.candidates.include_loopback_candidate = allow_loopback;
864    }
865
866    /// Controls where DTLS fingerprints are placed in SDP.
867    ///
868    /// By default, fingerprints are placed at the session level. Setting this
869    /// to `true` places them at the media level instead, which improves
870    /// compatibility with some WebRTC implementations.
871    ///
872    /// # Parameters
873    ///
874    /// * `sdp_media_level_fingerprints` - `true` for media-level, `false` for session-level
875    ///
876    /// # Examples
877    ///
878    /// ```
879    /// use rtc::peer_connection::configuration::setting_engine::SettingEngine;
880    ///
881    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
882    /// let mut setting_engine = SettingEngine::default();
883    ///
884    /// // Use media-level fingerprints for better compatibility
885    /// setting_engine.set_sdp_media_level_fingerprints(true);
886    /// # Ok(())
887    /// # }
888    /// ```
889    pub fn set_sdp_media_level_fingerprints(&mut self, sdp_media_level_fingerprints: bool) {
890        self.sdp_media_level_fingerprints = sdp_media_level_fingerprints;
891    }
892
893    // SetICETCPMux enables ICE-TCP when set to a non-nil value. Make sure that
894    // NetworkTypeTCP4 or NetworkTypeTCP6 is enabled as well.
895    //pub fn SetICETCPMux(&mut self, tcpMux ice.TCPMux) {
896    //    self.iceTCPMux = tcpMux
897    //}
898
899    // SetICEProxyDialer sets the proxy dialer interface based on golang.org/x/net/proxy.
900    //pub fn SetICEProxyDialer(&mut self, d proxy.Dialer) {
901    //    self.iceProxyDialer = d
902    //}
903
904    /// Prevents the MediaEngine from being copied for each PeerConnection.
905    ///
906    /// By default, each PeerConnection gets a copy of the MediaEngine, allowing
907    /// independent codec configurations. Disabling this allows sharing a single
908    /// MediaEngine and modifying it after PeerConnection creation.
909    ///
910    /// # Parameters
911    ///
912    /// * `is_disabled` - `true` to share MediaEngine, `false` to copy (default)
913    ///
914    /// # Examples
915    ///
916    /// ```
917    /// use rtc::peer_connection::configuration::setting_engine::SettingEngine;
918    ///
919    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
920    /// let mut setting_engine = SettingEngine::default();
921    ///
922    /// // Share MediaEngine across connections
923    /// setting_engine.disable_media_engine_copy(true);
924    ///
925    /// // Warning: Don't share MediaEngine between multiple PeerConnections
926    /// // unless you understand the implications
927    /// # Ok(())
928    /// # }
929    /// ```
930    ///
931    /// # Warning
932    ///
933    /// When disabled, ensure you don't share the same MediaEngine between
934    /// multiple PeerConnections unless you specifically intend to do so.
935    pub fn disable_media_engine_copy(&mut self, is_disabled: bool) {
936        self.disable_media_engine_copy = is_disabled;
937    }
938
939    /// Disables negotiating different codecs for different media sections.
940    ///
941    /// By default, each media section in the SDP can negotiate different codecs,
942    /// which is the spec-compliant behavior. This setting forces all media
943    /// sections to use the same codecs.
944    ///
945    /// # Parameters
946    ///
947    /// * `is_disabled` - `true` to use single codec set, `false` for per-section (default)
948    ///
949    /// # Examples
950    ///
951    /// ```
952    /// use rtc::peer_connection::configuration::setting_engine::SettingEngine;
953    ///
954    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
955    /// let mut setting_engine = SettingEngine::default();
956    ///
957    /// // Force same codecs for all media sections
958    /// setting_engine.disable_media_engine_multiple_codecs(true);
959    /// # Ok(())
960    /// # }
961    /// ```
962    ///
963    /// # Deprecation Note
964    ///
965    /// This setting is targeted for removal in a future release (4.2.0 or later).
966    pub fn disable_media_engine_multiple_codecs(&mut self, is_disabled: bool) {
967        self.disable_media_engine_multiple_codecs = is_disabled;
968    }
969
970    /// Sets the MTU size for the receive buffer.
971    ///
972    /// This controls the maximum size of packets that can be received. Leave
973    /// at 0 to use the default MTU (1460 bytes, equal to UDP MTU).
974    ///
975    /// # Parameters
976    ///
977    /// * `receive_mtu` - MTU size in bytes, or 0 for default
978    ///
979    /// # Examples
980    ///
981    /// ```
982    /// use rtc::peer_connection::configuration::setting_engine::SettingEngine;
983    ///
984    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
985    /// let mut setting_engine = SettingEngine::default();
986    ///
987    /// // Use larger MTU for jumbo frames
988    /// setting_engine.set_receive_mtu(9000);
989    ///
990    /// // Or use default
991    /// setting_engine.set_receive_mtu(0);
992    /// # Ok(())
993    /// # }
994    /// ```
995    pub fn set_receive_mtu(&mut self, receive_mtu: usize) {
996        self.receive_mtu = receive_mtu;
997    }
998
999    /// Sets a custom MID (media stream ID) generator function.
1000    ///
1001    /// By default, MIDs are generated automatically. This allows you to provide
1002    /// a custom generation scheme, useful for reducing complexity when handling
1003    /// SDP offer/answer collisions.
1004    ///
1005    /// # Parameters
1006    ///
1007    /// * `f` - Function that takes the highest seen numeric MID and returns a new MID string
1008    ///
1009    /// # Examples
1010    ///
1011    /// ```
1012    /// use rtc::peer_connection::configuration::setting_engine::SettingEngine;
1013    ///
1014    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
1015    /// let mut setting_engine = SettingEngine::default();
1016    ///
1017    /// // Generate MIDs with a custom prefix
1018    /// setting_engine.set_mid_generator(|max_mid| {
1019    ///     format!("custom_{}", max_mid + 1)
1020    /// });
1021    /// # Ok(())
1022    /// # }
1023    /// ```
1024    ///
1025    /// # Notes
1026    ///
1027    /// - MIDs should be generated without leaking user information (e.g., randomly)
1028    /// - MIDs should be 3 bytes or less for efficient RTP header extension encoding
1029    /// - The `isize` argument is the greatest seen _numeric_ MID (doesn't include non-numeric MIDs)
1030    ///
1031    /// # See Also
1032    ///
1033    /// - [RFC 8843 - MID](https://datatracker.ietf.org/doc/html/rfc8843)
1034    pub fn set_mid_generator(&mut self, f: impl Fn(isize) -> String + Send + Sync + 'static) {
1035        self.mid_generator = Some(Arc::new(f));
1036    }
1037
1038    /// Sets the maximum message size for SCTP data channels.
1039    ///
1040    /// This controls the largest message that can be sent through a data channel.
1041    /// Larger messages will be fragmented or rejected depending on the configuration.
1042    ///
1043    /// # Parameters
1044    ///
1045    /// * `max_message_size` - Maximum size (Bounded or Unbounded)
1046    ///
1047    /// # Examples
1048    ///
1049    /// ```
1050    /// use rtc::peer_connection::configuration::setting_engine::{SettingEngine, SctpMaxMessageSize};
1051    ///
1052    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
1053    /// let mut setting_engine = SettingEngine::default();
1054    ///
1055    /// // Use default 64KB
1056    /// setting_engine.set_sctp_max_message_size(
1057    ///     SctpMaxMessageSize::Bounded(SctpMaxMessageSize::DEFAULT_MESSAGE_SIZE)
1058    /// );
1059    ///
1060    /// // Or allow larger messages
1061    /// setting_engine.set_sctp_max_message_size(
1062    ///     SctpMaxMessageSize::Bounded(256 * 1024) // 256KB
1063    /// );
1064    ///
1065    /// // Or unbounded (uses MAX_MESSAGE_SIZE internally)
1066    /// setting_engine.set_sctp_max_message_size(SctpMaxMessageSize::Unbounded);
1067    /// # Ok(())
1068    /// # }
1069    /// ```
1070    ///
1071    /// # See Also
1072    ///
1073    /// - [RFC 8841 §6.1 - max-message-size](https://datatracker.ietf.org/doc/html/rfc8841#section-6.1)
1074    pub fn set_sctp_max_message_size(&mut self, max_message_size: SctpMaxMessageSize) {
1075        self.sctp_max_message_size = max_message_size;
1076    }
1077
1078    /// Controls whether to ignore RID pause signals for receiving transceivers.
1079    ///
1080    /// RID (RTP Stream Identifier) can signal pause/resume for individual streams
1081    /// in simulcast scenarios. This setting controls whether to honor those signals.
1082    ///
1083    /// # Parameters
1084    ///
1085    /// * `ignore_rid_pause_for_recv` - `true` to ignore pause signals, `false` to honor them
1086    pub fn set_ignore_rid_pause_for_recv(&mut self, ignore_rid_pause_for_recv: bool) {
1087        self.ignore_rid_pause_for_recv = ignore_rid_pause_for_recv;
1088    }
1089
1090    /// Controls whether to ignore SSRC attribute in SDP's sendonly or sendrecv for simulcast
1091    ///
1092    /// # Parameters
1093    ///
1094    /// * `write_ssrc_attributes_for_simulcast` - `true` to write, `false` to ignore
1095    pub fn set_write_ssrc_attributes_for_simulcast(
1096        &mut self,
1097        write_ssrc_attributes_for_simulcast: bool,
1098    ) {
1099        self.write_ssrc_attributes_for_simulcast = write_ssrc_attributes_for_simulcast;
1100    }
1101}