xphone 0.6.0

SIP telephony library with event-driven API — handles SIP signaling, RTP media, codecs, and call state
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
use std::time::Duration;

use crate::sip::auth::Credentials;
use crate::sip::conn::TlsConfig;
use crate::types::{Codec, VideoCodec};

/// Selects how DTMF digits are sent and received.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DtmfMode {
    /// RFC 4733 RTP telephone-event packets (default).
    Rfc4733,
    /// SIP INFO with `application/dtmf-relay` body (RFC 2976).
    SipInfo,
    /// Send via RFC 4733; also accept incoming SIP INFO.
    Both,
}

/// Configuration for a [`Phone`](crate::phone::Phone) instance.
///
/// Use [`PhoneBuilder`] for ergonomic construction with defaults.
#[derive(Debug, Clone)]
pub struct Config {
    /// SIP username / extension.
    pub username: String,
    /// SIP password for digest authentication.
    pub password: String,
    /// Digest `username` sent in the REGISTER `Authorization` header.
    /// Falls back to [`username`](Self::username) when `None` or empty. Allows
    /// registering the SIP URI `sip:<username>@host` while authenticating as a
    /// different identity (e.g. a shared trunk auth-user). Does not affect
    /// INVITE — see [`outbound_username`](Self::outbound_username) for that.
    pub auth_username: Option<String>,
    /// SIP server hostname or IP address.
    pub host: String,
    /// SIP server port (default `5060`).
    pub port: u16,
    /// Transport protocol: `"udp"`, `"tcp"`, or `"tls"`.
    pub transport: String,
    /// TLS configuration. Required when `transport` is `"tls"`.
    pub tls_config: Option<TlsConfig>,

    /// REGISTER expiry duration advertised to the server.
    pub register_expiry: Duration,
    /// Delay between registration retry attempts.
    pub register_retry: Duration,
    /// Maximum number of consecutive registration retries.
    pub register_max_retry: u32,

    /// Interval for NAT keep-alive packets. `None` disables keep-alive.
    pub nat_keepalive_interval: Option<Duration>,

    /// Enable NAT-friendly SIP transport behaviour. When `true` **and** the
    /// transport is UDP, outgoing Via headers include the `;rport` parameter
    /// (RFC 3581) so the server sends responses to the source IP/port the
    /// request actually arrived from. Ignored on TCP/TLS where symmetric
    /// response routing happens implicitly over the existing connection.
    /// Opt-in so existing deployments see no change.
    pub nat: bool,

    /// Override the local IP advertised in the SDP `c=` line. If empty, the
    /// address is auto-detected. Scope is SDP-only — `Contact` and `Via` stay
    /// anchored to the bound SIP socket. See
    /// [`DialOptions::rtp_address`](crate::config::DialOptions::rtp_address)
    /// for a per-call override and for the rationale.
    pub local_ip: String,
    /// Minimum port in the RTP port range (0 = OS-assigned).
    ///
    /// Each concurrent call requires one RTP port (even-numbered). The maximum
    /// number of concurrent calls is `(rtp_port_max - rtp_port_min) / 2`.
    ///
    /// **Production recommendation:** `10000–20000` (5,000 concurrent calls).
    /// The default (0) lets the OS assign ports, which works for development
    /// but gives no control over firewall rules or concurrency limits.
    pub rtp_port_min: u16,
    /// Maximum port in the RTP port range (0 = OS-assigned).
    pub rtp_port_max: u16,
    /// Preferred codecs in priority order.
    pub codec_prefs: Vec<Codec>,
    /// Jitter buffer depth for inbound RTP.
    pub jitter_buffer: Duration,
    /// Duration of RTP silence before a media timeout is raised.
    pub media_timeout: Duration,
    /// PCM frame size in samples. 0 uses the codec default.
    pub pcm_frame_size: usize,
    /// PCM sample rate in Hz (default `8000`).
    pub pcm_rate: u32,
    /// Enable SRTP (SDES-SRTP with AES_CM_128_HMAC_SHA1_80).
    pub srtp: bool,
    /// STUN server address (e.g. `"stun.l.google.com:19302"`).
    /// When set, a STUN Binding Request is used to discover the
    /// NAT-mapped address for SIP and RTP instead of the local-IP heuristic.
    pub stun_server: Option<String>,
    /// DTMF transport mode (default: RFC 4733 RTP telephone-events).
    pub dtmf_mode: DtmfMode,
    /// Voicemail server URI for MWI SUBSCRIBE (RFC 3842).
    /// When set, the phone subscribes to `message-summary` events after registration.
    /// Example: `"sip:*97@pbx.local"` or left empty to default to user's AOR.
    pub voicemail_uri: Option<String>,
    /// TURN server address (e.g. `"turn.example.com:3478"`).
    /// When set, a TURN relay is allocated for media NAT traversal.
    pub turn_server: Option<String>,
    /// TURN username for long-term credentials.
    pub turn_username: Option<String>,
    /// TURN password for long-term credentials.
    pub turn_password: Option<String>,
    /// Enable ICE-Lite candidate gathering and STUN responder.
    /// Requires `stun_server` and/or `turn_server` to produce useful candidates.
    pub ice: bool,

    /// User-Agent string sent in SIP headers.
    /// Defaults to `"xphone"`. PBXes use this to identify the device.
    pub user_agent: String,

    /// Outbound proxy URI for routing **all** outbound SIP requests
    /// (e.g. `"sip:proxy.example.com:5060"`). When set, REGISTER, INVITE,
    /// SUBSCRIBE, MESSAGE, in-dialog requests (BYE, re-INVITE, REFER, INFO),
    /// ACK, and NAT keep-alives all route through this proxy instead of
    /// `host:port`. For TCP/TLS, the transport connection also targets the
    /// proxy. Mirrors how outbound-proxy deployments (Kamailio, OpenSIPS,
    /// Asterisk) actually behave.
    pub outbound_proxy: Option<String>,
    /// Username for outbound INVITE authentication. Falls back to `username` if unset.
    pub outbound_username: Option<String>,
    /// Password for outbound INVITE authentication. Falls back to `password` if unset.
    pub outbound_password: Option<String>,
}

impl Default for Config {
    fn default() -> Self {
        Config {
            username: String::new(),
            password: String::new(),
            auth_username: None,
            host: String::new(),
            port: 5060,
            transport: "udp".into(),
            tls_config: None,
            register_expiry: Duration::from_secs(60),
            register_retry: Duration::from_secs(1),
            register_max_retry: 3,
            nat_keepalive_interval: None,
            nat: false,
            local_ip: String::new(),
            rtp_port_min: 0,
            rtp_port_max: 0,
            codec_prefs: Vec::new(),
            jitter_buffer: Duration::from_millis(50),
            media_timeout: Duration::from_secs(30),
            pcm_frame_size: 0,
            pcm_rate: 8000,
            srtp: false,
            stun_server: None,
            dtmf_mode: DtmfMode::Rfc4733,
            voicemail_uri: None,
            turn_server: None,
            turn_username: None,
            turn_password: None,
            ice: false,
            user_agent: "xphone".into(),
            outbound_proxy: None,
            outbound_username: None,
            outbound_password: None,
        }
    }
}

impl Config {
    /// Extracts an embedded port from `host` (e.g. `"10.0.0.1:5060"`) into
    /// the separate `port` field. Only applies if `port` is still at the
    /// default value (5060) — an explicit `.port()` call takes precedence.
    ///
    /// Called once from [`Phone::new()`](crate::phone::Phone::new).
    pub(crate) fn normalize_host(&mut self) {
        if self.host.is_empty() {
            return;
        }
        if let Some((host, port)) = split_host_port(&self.host) {
            // Only apply embedded port if port hasn't been explicitly set.
            if self.port == 5060 {
                self.port = port;
            }
            self.host = host.to_string();
        }
    }
}

/// Split a `host:port` string. Returns `None` if no port is present.
/// Handles `[::1]:5060` (IPv6 bracket notation) and `10.0.0.1:5060`.
fn split_host_port(s: &str) -> Option<(&str, u16)> {
    // IPv6 bracket notation: [::1]:5060
    if let Some(bracket_end) = s.find(']') {
        let after = &s[bracket_end + 1..];
        if let Some(port_str) = after.strip_prefix(':') {
            if let Ok(port) = port_str.parse::<u16>() {
                return Some((&s[..bracket_end + 1], port));
            }
        }
        return None;
    }
    // Only split on the last colon, and only if there's exactly one
    // (multiple colons without brackets = bare IPv6, don't split).
    if s.matches(':').count() == 1 {
        if let Some((host, port_str)) = s.rsplit_once(':') {
            if let Ok(port) = port_str.parse::<u16>() {
                return Some((host, port));
            }
        }
    }
    None
}

/// Builder for constructing a [`Config`] using chained method calls.
pub struct PhoneBuilder {
    config: Config,
}

impl PhoneBuilder {
    /// Creates a new builder with default configuration values.
    pub fn new() -> Self {
        PhoneBuilder {
            config: Config::default(),
        }
    }

    /// Sets SIP username, password, and server host.
    ///
    /// The `host` parameter accepts `"hostname"`, `"hostname:port"`, or
    /// `"ip:port"` formats. If a port is embedded, it is extracted and
    /// applied when the `Config` is consumed by [`Phone::new()`](crate::phone::Phone::new).
    /// An explicit [`.port()`](Self::port) call always takes precedence.
    pub fn credentials(mut self, username: &str, password: &str, host: &str) -> Self {
        self.config.username = username.into();
        self.config.password = password.into();
        self.config.host = host.into();
        self
    }

    /// Sets the transport protocol (`"udp"`, `"tcp"`, or `"tls"`).
    pub fn transport(mut self, protocol: &str) -> Self {
        self.config.transport = protocol.into();
        self
    }

    /// Sets TLS configuration. Required when transport is `"tls"`.
    pub fn tls_config(mut self, tls: TlsConfig) -> Self {
        self.config.tls_config = Some(tls);
        self
    }

    /// Sets the SIP server port.
    pub fn port(mut self, port: u16) -> Self {
        self.config.port = port;
        self
    }

    /// Sets the RTP port range for media sockets.
    ///
    /// Each concurrent call needs one even-numbered RTP port.
    /// Max concurrent calls = `(max - min) / 2`.
    ///
    /// ```rust
    /// # use xphone::PhoneBuilder;
    /// let cfg = PhoneBuilder::new()
    ///     .credentials("alice", "secret", "sip.example.com")
    ///     .rtp_ports(10000, 20000) // 5,000 concurrent calls
    ///     .build();
    /// ```
    pub fn rtp_ports(mut self, min: u16, max: u16) -> Self {
        self.config.rtp_port_min = min;
        self.config.rtp_port_max = max;
        self
    }

    /// Sets the preferred codec list in priority order.
    pub fn codecs(mut self, codecs: Vec<Codec>) -> Self {
        self.config.codec_prefs = codecs;
        self
    }

    /// Sets the jitter buffer depth for inbound RTP.
    pub fn jitter_buffer(mut self, d: Duration) -> Self {
        self.config.jitter_buffer = d;
        self
    }

    /// Sets the media timeout duration.
    pub fn media_timeout(mut self, d: Duration) -> Self {
        self.config.media_timeout = d;
        self
    }

    /// Enables NAT keep-alive with the given interval.
    pub fn nat_keepalive(mut self, d: Duration) -> Self {
        self.config.nat_keepalive_interval = Some(d);
        self
    }

    /// Enables NAT-friendly SIP transport: appends `;rport` (RFC 3581) to
    /// outgoing Via headers so responses are routed back to the source IP/port
    /// observed by the server. Default is off.
    pub fn with_nat(mut self, enabled: bool) -> Self {
        self.config.nat = enabled;
        self
    }

    /// Sets the PCM sample rate in Hz.
    pub fn pcm_rate(mut self, rate: u32) -> Self {
        self.config.pcm_rate = rate;
        self
    }

    /// Sets the REGISTER expiry duration.
    pub fn register_expiry(mut self, d: Duration) -> Self {
        self.config.register_expiry = d;
        self
    }

    /// Sets the delay between registration retry attempts.
    pub fn register_retry(mut self, d: Duration) -> Self {
        self.config.register_retry = d;
        self
    }

    /// Sets the maximum number of registration retries.
    pub fn register_max_retry(mut self, n: u32) -> Self {
        self.config.register_max_retry = n;
        self
    }

    /// Enables SRTP (SDES-SRTP with AES_CM_128_HMAC_SHA1_80).
    pub fn srtp(mut self, enabled: bool) -> Self {
        self.config.srtp = enabled;
        self
    }

    /// Sets the STUN server for NAT-mapped address discovery.
    pub fn stun_server(mut self, server: &str) -> Self {
        self.config.stun_server = Some(server.into());
        self
    }

    /// Sets the DTMF transport mode.
    pub fn dtmf_mode(mut self, mode: DtmfMode) -> Self {
        self.config.dtmf_mode = mode;
        self
    }

    /// Sets the voicemail server URI for MWI SUBSCRIBE (RFC 3842).
    pub fn voicemail_uri(mut self, uri: &str) -> Self {
        self.config.voicemail_uri = Some(uri.into());
        self
    }

    /// Sets the TURN server for NAT relay allocation.
    pub fn turn_server(mut self, server: &str) -> Self {
        self.config.turn_server = Some(server.into());
        self
    }

    /// Sets TURN long-term credentials.
    pub fn turn_credentials(mut self, username: &str, password: &str) -> Self {
        self.config.turn_username = Some(username.into());
        self.config.turn_password = Some(password.into());
        self
    }

    /// Enables ICE-Lite candidate gathering and STUN responder.
    pub fn ice(mut self, enabled: bool) -> Self {
        self.config.ice = enabled;
        self
    }

    /// Sets the User-Agent string sent in SIP headers.
    /// PBXes use this to identify the device (e.g., `"MyApp/1.0"`).
    /// Defaults to `"xphone"`.
    pub fn user_agent(mut self, ua: &str) -> Self {
        self.config.user_agent = ua.into();
        self
    }

    /// Sets an outbound proxy for routing all outbound SIP requests —
    /// REGISTER, INVITE, SUBSCRIBE, MESSAGE, in-dialog sends, and NAT
    /// keep-alives (e.g. `"sip:proxy.example.com:5060"`). For TCP/TLS the
    /// transport connection also targets the proxy.
    pub fn outbound_proxy(mut self, proxy: &str) -> Self {
        self.config.outbound_proxy = Some(proxy.into());
        self
    }

    /// Sets separate credentials for outbound INVITE authentication.
    /// Falls back to the main credentials if unset.
    pub fn outbound_credentials(mut self, username: &str, password: &str) -> Self {
        self.config.outbound_username = Some(username.into());
        self.config.outbound_password = Some(password.into());
        self
    }

    /// Sets a digest auth username for REGISTER, decoupled from the SIP AOR.
    /// The REGISTER Request-URI, From, To, and Contact still use the configured
    /// [`username`](Config::username); only the digest `username` parameter changes.
    pub fn auth_username(mut self, auth_username: &str) -> Self {
        self.config.auth_username = Some(auth_username.into());
        self
    }

    /// Consumes the builder and returns the finished [`Config`].
    pub fn build(self) -> Config {
        self.config
    }
}

impl Default for PhoneBuilder {
    fn default() -> Self {
        Self::new()
    }
}

/// Configuration for an outbound call.
///
/// Use [`DialOptionsBuilder`] for ergonomic construction with defaults.
#[derive(Debug, Clone)]
pub struct DialOptions {
    /// Caller-ID string to place in the From header. `None` uses the default.
    pub caller_id: Option<String>,
    /// Extra SIP headers to include in the INVITE.
    pub custom_headers: std::collections::HashMap<String, String>,
    /// Whether to accept early media (183 Session Progress).
    pub early_media: bool,
    /// Maximum time to wait for the callee to answer.
    pub timeout: Duration,
    /// Codec list that overrides the phone-level preferences for this call.
    pub codec_override: Vec<Codec>,
    /// Per-call auth credentials for 401/407 challenges. Overrides config-level
    /// `outbound_username` / `outbound_password` for this call only.
    pub auth: Option<Credentials>,
    /// Enable video in the SDP offer.
    pub video: bool,
    /// Video codecs in preference order. Defaults to `[H264, VP8]` when
    /// `video` is enabled. Only used when `video` is `true`.
    pub video_codecs: Vec<VideoCodec>,
    /// Override the local IP advertised in SDP (the `c=` line) for this call
    /// only. Takes precedence over [`Config::local_ip`](Config::local_ip).
    /// Useful on multi-homed hosts when individual calls need different
    /// source-routable media addresses. `None` falls through to
    /// `Config::local_ip` → STUN-mapped address → route-lookup heuristic.
    ///
    /// **Scope is intentionally SDP-only.** This does **not** modify the SIP
    /// `Contact` header or `Via` — those stay anchored to the socket the SIP
    /// client actually bound. Rewriting Contact with a routable-looking IP but
    /// the ephemeral bound SIP port breaks inbound signaling behind NAT: the
    /// port isn't forwarded, so registrars that trust a plausible-looking
    /// Contact over their own NAT learning (rport / `received` on REGISTER,
    /// keepalives) send INVITEs into the void. xphone-go's `WithRTPAddress`
    /// conflated these scopes and tripped exactly this failure in
    /// Docker-bridge deployments — keeping the scope SDP-only avoids it.
    pub rtp_address: Option<String>,
}

impl Default for DialOptions {
    fn default() -> Self {
        DialOptions {
            caller_id: None,
            custom_headers: std::collections::HashMap::new(),
            early_media: false,
            timeout: Duration::from_secs(30),
            codec_override: Vec::new(),
            auth: None,
            video: false,
            video_codecs: Vec::new(),
            rtp_address: None,
        }
    }
}

/// Builder for constructing [`DialOptions`].
pub struct DialOptionsBuilder {
    opts: DialOptions,
}

impl DialOptionsBuilder {
    /// Creates a new builder with default dial options.
    pub fn new() -> Self {
        DialOptionsBuilder {
            opts: DialOptions::default(),
        }
    }

    /// Sets the caller-ID string for the From header.
    pub fn caller_id(mut self, id: &str) -> Self {
        self.opts.caller_id = Some(id.into());
        self
    }

    /// Adds a custom SIP header to the INVITE.
    pub fn header(mut self, name: &str, value: &str) -> Self {
        self.opts.custom_headers.insert(name.into(), value.into());
        self
    }

    /// Enables early media (183 Session Progress).
    pub fn early_media(mut self) -> Self {
        self.opts.early_media = true;
        self
    }

    /// Sets the dial timeout.
    pub fn timeout(mut self, d: Duration) -> Self {
        self.opts.timeout = d;
        self
    }

    /// Sets per-call authentication credentials for 401/407 proxy auth.
    /// Overrides config-level `outbound_username` / `outbound_password` for this call only.
    pub fn auth(mut self, username: &str, password: &str) -> Self {
        self.opts.auth = Some(Credentials {
            username: username.into(),
            password: password.into(),
        });
        self
    }

    /// Overrides the phone-level codec preferences for this call.
    pub fn codec_override(mut self, codecs: Vec<Codec>) -> Self {
        self.opts.codec_override = codecs;
        self
    }

    /// Enables video in the SDP offer. Also sets default video codecs
    /// `[H264, VP8]` if none were explicitly set.
    pub fn video(mut self) -> Self {
        self.opts.video = true;
        if self.opts.video_codecs.is_empty() {
            self.opts.video_codecs = vec![VideoCodec::H264, VideoCodec::VP8];
        }
        self
    }

    /// Sets the preferred video codecs (default: `[H264, VP8]`).
    pub fn video_codecs(mut self, codecs: Vec<VideoCodec>) -> Self {
        self.opts.video_codecs = codecs;
        self
    }

    /// Overrides the local IP advertised in SDP for this call only.
    pub fn rtp_address(mut self, ip: &str) -> Self {
        self.opts.rtp_address = Some(ip.into());
        self
    }

    /// Consumes the builder and returns the finished [`DialOptions`].
    pub fn build(self) -> DialOptions {
        self.opts
    }
}

impl Default for DialOptionsBuilder {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // ── host:port parsing ──

    #[test]
    fn normalize_splits_host_port() {
        let mut cfg = Config {
            host: "10.0.0.7:5061".into(),
            ..Config::default()
        };
        cfg.normalize_host();
        assert_eq!(cfg.host, "10.0.0.7");
        assert_eq!(cfg.port, 5061);
    }

    #[test]
    fn normalize_host_only() {
        let mut cfg = Config {
            host: "10.0.0.7".into(),
            ..Config::default()
        };
        cfg.normalize_host();
        assert_eq!(cfg.host, "10.0.0.7");
        assert_eq!(cfg.port, 5060); // default
    }

    #[test]
    fn normalize_hostname_with_port() {
        let mut cfg = Config {
            host: "sip.example.com:5080".into(),
            ..Config::default()
        };
        cfg.normalize_host();
        assert_eq!(cfg.host, "sip.example.com");
        assert_eq!(cfg.port, 5080);
    }

    #[test]
    fn normalize_ipv6_bracket_with_port() {
        let mut cfg = Config {
            host: "[::1]:5060".into(),
            ..Config::default()
        };
        cfg.normalize_host();
        assert_eq!(cfg.host, "[::1]");
        assert_eq!(cfg.port, 5060);
    }

    #[test]
    fn normalize_bare_ipv6_no_split() {
        let mut cfg = Config {
            host: "::1".into(),
            ..Config::default()
        };
        cfg.normalize_host();
        assert_eq!(cfg.host, "::1");
        assert_eq!(cfg.port, 5060);
    }

    #[test]
    fn normalize_host_direct_config() {
        let mut cfg = Config {
            host: "10.0.0.7:5061".into(),
            ..Config::default()
        };
        cfg.normalize_host();
        assert_eq!(cfg.host, "10.0.0.7");
        assert_eq!(cfg.port, 5061);
    }

    #[test]
    fn normalize_host_invalid_port_ignored() {
        let mut cfg = Config {
            host: "10.0.0.7:notaport".into(),
            ..Config::default()
        };
        cfg.normalize_host();
        // Invalid port — host unchanged.
        assert_eq!(cfg.host, "10.0.0.7:notaport");
        assert_eq!(cfg.port, 5060);
    }

    #[test]
    fn builder_explicit_port_wins_over_default() {
        // If .port() is called after .credentials(), it should take precedence.
        let cfg = PhoneBuilder::new()
            .credentials("1001", "secret", "10.0.0.7")
            .port(5061)
            .build();
        assert_eq!(cfg.host, "10.0.0.7");
        assert_eq!(cfg.port, 5061);
    }

    #[test]
    fn explicit_port_wins_over_embedded() {
        // Explicit .port() takes precedence over embedded port in host.
        let mut cfg = PhoneBuilder::new()
            .credentials("1001", "secret", "10.0.0.7:5080")
            .port(9999)
            .build();
        cfg.normalize_host();
        assert_eq!(cfg.host, "10.0.0.7"); // host part still stripped
        assert_eq!(cfg.port, 9999); // explicit port preserved
    }

    // ── existing tests ──

    #[test]
    fn config_defaults() {
        let cfg = Config::default();
        assert_eq!(cfg.transport, "udp");
        assert_eq!(cfg.port, 5060);
        assert_eq!(cfg.register_expiry, Duration::from_secs(60));
        assert_eq!(cfg.register_retry, Duration::from_secs(1));
        assert_eq!(cfg.register_max_retry, 3);
        assert_eq!(cfg.media_timeout, Duration::from_secs(30));
        assert_eq!(cfg.jitter_buffer, Duration::from_millis(50));
        assert_eq!(cfg.pcm_rate, 8000);
    }

    #[test]
    fn phone_builder() {
        let cfg = PhoneBuilder::new()
            .credentials("alice", "secret", "sip.example.com")
            .transport("tcp")
            .port(5061)
            .rtp_ports(10000, 20000)
            .codecs(vec![Codec::PCMU, Codec::PCMA])
            .jitter_buffer(Duration::from_millis(100))
            .media_timeout(Duration::from_secs(60))
            .nat_keepalive(Duration::from_secs(30))
            .pcm_rate(16000)
            .build();

        assert_eq!(cfg.username, "alice");
        assert_eq!(cfg.password, "secret");
        assert_eq!(cfg.host, "sip.example.com");
        assert_eq!(cfg.transport, "tcp");
        assert_eq!(cfg.port, 5061);
        assert_eq!(cfg.rtp_port_min, 10000);
        assert_eq!(cfg.rtp_port_max, 20000);
        assert_eq!(cfg.codec_prefs, vec![Codec::PCMU, Codec::PCMA]);
        assert_eq!(cfg.jitter_buffer, Duration::from_millis(100));
        assert_eq!(cfg.media_timeout, Duration::from_secs(60));
        assert_eq!(cfg.nat_keepalive_interval, Some(Duration::from_secs(30)));
        assert_eq!(cfg.pcm_rate, 16000);
    }

    #[test]
    fn phone_builder_auth_username() {
        let cfg = PhoneBuilder::new()
            .credentials("1003", "pw", "pbx.local")
            .auth_username("trunk-auth-user")
            .build();
        assert_eq!(cfg.username, "1003");
        assert_eq!(cfg.auth_username.as_deref(), Some("trunk-auth-user"));
    }

    #[test]
    fn auth_username_defaults_to_none() {
        let cfg = Config::default();
        assert!(cfg.auth_username.is_none());
    }

    #[test]
    fn phone_builder_auth_username_empty_string_kept_on_config() {
        // Builder stores the string as-is; the client-level helper treats
        // empty as equivalent to unset (see client::register_auth_username).
        let cfg = PhoneBuilder::new()
            .credentials("1003", "pw", "pbx.local")
            .auth_username("")
            .build();
        assert_eq!(cfg.auth_username.as_deref(), Some(""));
    }

    #[test]
    fn dial_options_defaults() {
        let opts = DialOptions::default();
        assert_eq!(opts.timeout, Duration::from_secs(30));
        assert!(!opts.early_media);
        assert!(opts.caller_id.is_none());
        assert!(opts.custom_headers.is_empty());
        assert!(opts.codec_override.is_empty());
    }

    #[test]
    fn nat_default_is_off() {
        let cfg = Config::default();
        assert!(!cfg.nat);
    }

    #[test]
    fn phone_builder_with_nat_enables_rport() {
        let cfg = PhoneBuilder::new()
            .credentials("1001", "pw", "pbx.local")
            .with_nat(true)
            .build();
        assert!(cfg.nat);
    }

    #[test]
    fn dtmf_mode_default_is_rfc4733() {
        let cfg = Config::default();
        assert_eq!(cfg.dtmf_mode, DtmfMode::Rfc4733);
    }

    #[test]
    fn phone_builder_dtmf_mode() {
        let cfg = PhoneBuilder::new()
            .credentials("alice", "secret", "sip.example.com")
            .dtmf_mode(DtmfMode::SipInfo)
            .build();
        assert_eq!(cfg.dtmf_mode, DtmfMode::SipInfo);

        let cfg2 = PhoneBuilder::new()
            .credentials("alice", "secret", "sip.example.com")
            .dtmf_mode(DtmfMode::Both)
            .build();
        assert_eq!(cfg2.dtmf_mode, DtmfMode::Both);
    }

    #[test]
    fn dial_options_builder() {
        let opts = DialOptionsBuilder::new()
            .caller_id("Bob")
            .header("X-Custom", "value")
            .early_media()
            .timeout(Duration::from_secs(60))
            .codec_override(vec![Codec::G722])
            .build();

        assert_eq!(opts.caller_id, Some("Bob".into()));
        assert_eq!(opts.custom_headers.get("X-Custom"), Some(&"value".into()));
        assert!(opts.early_media);
        assert_eq!(opts.timeout, Duration::from_secs(60));
        assert_eq!(opts.codec_override, vec![Codec::G722]);
    }

    #[test]
    fn dial_options_video_default_off() {
        let opts = DialOptions::default();
        assert!(!opts.video);
        assert!(opts.video_codecs.is_empty());
    }

    #[test]
    fn dial_options_builder_video() {
        let opts = DialOptionsBuilder::new()
            .video()
            .video_codecs(vec![VideoCodec::H264, VideoCodec::VP8])
            .build();
        assert!(opts.video);
        assert_eq!(opts.video_codecs, vec![VideoCodec::H264, VideoCodec::VP8]);
    }

    #[test]
    fn dial_options_builder_video_default_codecs() {
        // .video() without .video_codecs() should default to [H264, VP8].
        let opts = DialOptionsBuilder::new().video().build();
        assert!(opts.video);
        assert_eq!(opts.video_codecs, vec![VideoCodec::H264, VideoCodec::VP8]);
    }

    #[test]
    fn dial_options_builder_video_h264_only() {
        // Explicit .video_codecs() before .video() is preserved.
        let opts = DialOptionsBuilder::new()
            .video_codecs(vec![VideoCodec::H264])
            .video()
            .build();
        assert!(opts.video);
        assert_eq!(opts.video_codecs, vec![VideoCodec::H264]);
    }

    #[test]
    fn dial_options_defaults_no_auth() {
        let opts = DialOptions::default();
        assert!(opts.auth.is_none());
    }

    #[test]
    fn dial_options_builder_auth() {
        let opts = DialOptionsBuilder::new()
            .auth("trunk-user", "trunk-pass")
            .build();
        let creds = opts.auth.unwrap();
        assert_eq!(creds.username, "trunk-user");
        assert_eq!(creds.password, "trunk-pass");
    }

    #[test]
    fn dial_options_builder_auth_with_other_options() {
        let opts = DialOptionsBuilder::new()
            .caller_id("Bob")
            .auth("proxy-user", "proxy-pass")
            .early_media()
            .build();
        assert_eq!(opts.caller_id, Some("Bob".into()));
        let creds = opts.auth.unwrap();
        assert_eq!(creds.username, "proxy-user");
        assert_eq!(creds.password, "proxy-pass");
        assert!(opts.early_media);
    }
}