xphone 0.4.5

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
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, Instant};

use parking_lot::Mutex;

use crate::error::{Error, Result};
use crate::types::*;

#[allow(clippy::type_complexity)]
struct Inner {
    id: String,
    call_id: String,
    state: CallState,
    direction: Direction,
    from: String,
    to: String,
    from_name: String,
    remote_uri: String,
    remote_ip: String,
    remote_port: i32,
    codec: Codec,
    local_sdp: String,
    remote_sdp: String,
    start_time: Option<Instant>,
    muted: bool,
    video_muted: bool,
    video_codec: Option<VideoCodec>,
    sent_dtmf: Vec<String>,
    transfer_to: String,
    headers: HashMap<String, Vec<String>>,

    on_dtmf_fn: Vec<Arc<dyn Fn(String) + Send + Sync>>,
    on_hold_fn: Vec<Arc<dyn Fn() + Send + Sync>>,
    on_resume_fn: Vec<Arc<dyn Fn() + Send + Sync>>,
    on_mute_fn: Vec<Arc<dyn Fn() + Send + Sync>>,
    on_unmute_fn: Vec<Arc<dyn Fn() + Send + Sync>>,
    on_media_fn: Vec<Arc<dyn Fn() + Send + Sync>>,
    on_state_fn: Vec<Arc<dyn Fn(CallState) + Send + Sync>>,
    on_ended_fn: Vec<Arc<dyn Fn(EndReason) + Send + Sync>>,
}

fn mock_call_id() -> String {
    use std::sync::atomic::{AtomicU64, Ordering};
    static CTR: AtomicU64 = AtomicU64::new(0);
    format!("mock-{}", CTR.fetch_add(1, Ordering::Relaxed))
}

fn mock_call_call_id() -> String {
    use std::sync::atomic::{AtomicU64, Ordering};
    static CTR: AtomicU64 = AtomicU64::new(1);
    format!("mock-call-{}", CTR.fetch_add(1, Ordering::Relaxed))
}

/// Mock call for testing consumer code that receives Call-like objects.
/// Provides the same API surface as `Call` but with test setters and inspection.
pub struct MockCall {
    inner: Mutex<Inner>,
}

impl std::fmt::Debug for MockCall {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let inner = self.inner.lock();
        f.debug_struct("MockCall")
            .field("id", &inner.id)
            .field("state", &inner.state)
            .field("direction", &inner.direction)
            .finish()
    }
}

impl MockCall {
    /// Creates a new `MockCall` with default state (`Ringing`, `Inbound`).
    pub fn new() -> Self {
        Self {
            inner: Mutex::new(Inner {
                id: mock_call_id(),
                call_id: mock_call_call_id(),
                state: CallState::Ringing,
                direction: Direction::Inbound,
                from: String::new(),
                to: String::new(),
                from_name: String::new(),
                remote_uri: String::new(),
                remote_ip: String::new(),
                remote_port: 0,
                codec: Codec::PCMU,
                local_sdp: String::new(),
                remote_sdp: String::new(),
                start_time: None,
                muted: false,
                video_muted: false,
                video_codec: None,
                sent_dtmf: Vec::new(),
                transfer_to: String::new(),
                headers: HashMap::new(),
                on_dtmf_fn: Vec::new(),
                on_hold_fn: Vec::new(),
                on_resume_fn: Vec::new(),
                on_mute_fn: Vec::new(),
                on_unmute_fn: Vec::new(),
                on_media_fn: Vec::new(),
                on_state_fn: Vec::new(),
                on_ended_fn: Vec::new(),
            }),
        }
    }

    // --- Getters (mirror Call API) ---

    /// Returns the unique mock call identifier.
    pub fn id(&self) -> String {
        self.inner.lock().id.clone()
    }

    /// Returns the SIP Call-ID.
    pub fn call_id(&self) -> String {
        self.inner.lock().call_id.clone()
    }

    /// Returns the current call state.
    pub fn state(&self) -> CallState {
        self.inner.lock().state
    }

    /// Returns the call direction (inbound or outbound).
    pub fn direction(&self) -> Direction {
        self.inner.lock().direction
    }

    /// Returns the From URI.
    pub fn from(&self) -> String {
        self.inner.lock().from.clone()
    }

    /// Returns the To URI.
    pub fn to(&self) -> String {
        self.inner.lock().to.clone()
    }

    /// Returns the display name from the From header.
    pub fn from_name(&self) -> String {
        self.inner.lock().from_name.clone()
    }

    /// Returns the remote party's SIP URI.
    pub fn remote_uri(&self) -> String {
        self.inner.lock().remote_uri.clone()
    }

    /// Returns the remote party's IP address.
    pub fn remote_ip(&self) -> String {
        self.inner.lock().remote_ip.clone()
    }

    /// Returns the remote party's RTP port.
    pub fn remote_port(&self) -> i32 {
        self.inner.lock().remote_port
    }

    /// Returns the negotiated audio codec.
    pub fn codec(&self) -> Codec {
        self.inner.lock().codec
    }

    /// Returns the local SDP offer/answer.
    pub fn local_sdp(&self) -> String {
        self.inner.lock().local_sdp.clone()
    }

    /// Returns the remote SDP offer/answer.
    pub fn remote_sdp(&self) -> String {
        self.inner.lock().remote_sdp.clone()
    }

    /// Returns the time when the call became active, if any.
    pub fn start_time(&self) -> Option<Instant> {
        self.inner.lock().start_time
    }

    /// Returns how long the call has been active. Zero if not yet active.
    pub fn duration(&self) -> Duration {
        self.inner
            .lock()
            .start_time
            .map(|t| t.elapsed())
            .unwrap_or(Duration::ZERO)
    }

    /// Returns values for the given SIP header name (case-insensitive).
    pub fn header(&self, name: &str) -> Vec<String> {
        let inner = self.inner.lock();
        let lower = name.to_lowercase();
        for (k, v) in &inner.headers {
            if k.to_lowercase() == lower {
                return v.clone();
            }
        }
        Vec::new()
    }

    /// Returns all SIP headers as a map.
    pub fn headers(&self) -> HashMap<String, Vec<String>> {
        self.inner.lock().headers.clone()
    }

    // --- Actions (mirror Call API) ---

    /// Accepts a ringing call, transitioning it to `Active`.
    pub fn accept(&self) -> Result<()> {
        let cbs = {
            let mut inner = self.inner.lock();
            if inner.state != CallState::Ringing {
                return Err(Error::InvalidState);
            }
            inner.state = CallState::Active;
            inner.start_time = Some(Instant::now());
            inner.on_state_fn.clone()
        };
        for f in cbs {
            f(CallState::Active);
        }
        Ok(())
    }

    /// Rejects a ringing call with the given SIP status code and reason.
    pub fn reject(&self, _code: u16, _reason: &str) -> Result<()> {
        let (state_cbs, ended_cbs) = {
            let mut inner = self.inner.lock();
            if inner.state != CallState::Ringing {
                return Err(Error::InvalidState);
            }
            inner.state = CallState::Ended;
            let cbs = (inner.on_state_fn.clone(), inner.on_ended_fn.clone());
            Self::clear_callbacks(&mut inner);
            cbs
        };
        for f in state_cbs {
            f(CallState::Ended);
        }
        for f in ended_cbs {
            f(EndReason::Rejected);
        }
        Ok(())
    }

    /// Ends an active, on-hold, or dialing call.
    pub fn end(&self) -> Result<()> {
        let (reason, state_cbs, ended_cbs) = {
            let mut inner = self.inner.lock();
            let reason = match inner.state {
                CallState::Dialing | CallState::RemoteRinging | CallState::EarlyMedia => {
                    EndReason::Cancelled
                }
                CallState::Active | CallState::OnHold => EndReason::Local,
                _ => return Err(Error::InvalidState),
            };
            inner.state = CallState::Ended;
            let cbs = (reason, inner.on_state_fn.clone(), inner.on_ended_fn.clone());
            Self::clear_callbacks(&mut inner);
            cbs
        };
        for f in state_cbs {
            f(CallState::Ended);
        }
        for f in ended_cbs {
            f(reason);
        }
        Ok(())
    }

    /// Places an active call on hold.
    pub fn hold(&self) -> Result<()> {
        let (state_cbs, hold_cbs) = {
            let mut inner = self.inner.lock();
            if inner.state != CallState::Active {
                return Err(Error::InvalidState);
            }
            inner.state = CallState::OnHold;
            (inner.on_state_fn.clone(), inner.on_hold_fn.clone())
        };
        for f in state_cbs {
            f(CallState::OnHold);
        }
        for f in hold_cbs {
            f();
        }
        Ok(())
    }

    /// Resumes a held call back to active.
    pub fn resume(&self) -> Result<()> {
        let (state_cbs, resume_cbs) = {
            let mut inner = self.inner.lock();
            if inner.state != CallState::OnHold {
                return Err(Error::InvalidState);
            }
            inner.state = CallState::Active;
            (inner.on_state_fn.clone(), inner.on_resume_fn.clone())
        };
        for f in state_cbs {
            f(CallState::Active);
        }
        for f in resume_cbs {
            f();
        }
        Ok(())
    }

    /// Mutes the call's outgoing audio.
    pub fn mute(&self) -> Result<()> {
        let cbs = {
            let mut inner = self.inner.lock();
            if inner.state != CallState::Active {
                return Err(Error::InvalidState);
            }
            if inner.muted {
                return Err(Error::AlreadyMuted);
            }
            inner.muted = true;
            inner.on_mute_fn.clone()
        };
        for f in cbs {
            f();
        }
        Ok(())
    }

    /// Unmutes the call's outgoing audio.
    pub fn unmute(&self) -> Result<()> {
        let cbs = {
            let mut inner = self.inner.lock();
            if inner.state != CallState::Active {
                return Err(Error::InvalidState);
            }
            if !inner.muted {
                return Err(Error::NotMuted);
            }
            inner.muted = false;
            inner.on_unmute_fn.clone()
        };
        for f in cbs {
            f();
        }
        Ok(())
    }

    /// Sends a DTMF digit. Records it for later inspection via [`sent_dtmf`](Self::sent_dtmf).
    pub fn send_dtmf(&self, digit: &str) -> Result<()> {
        let mut inner = self.inner.lock();
        if inner.state != CallState::Active {
            return Err(Error::InvalidState);
        }
        inner.sent_dtmf.push(digit.into());
        Ok(())
    }

    /// Initiates a blind transfer. Records the target for inspection via [`last_transfer_target`](Self::last_transfer_target).
    pub fn blind_transfer(&self, target: &str) -> Result<()> {
        let mut inner = self.inner.lock();
        if inner.state != CallState::Active && inner.state != CallState::OnHold {
            return Err(Error::InvalidState);
        }
        inner.transfer_to = target.into();
        Ok(())
    }

    /// Returns whether the call has an active video stream.
    pub fn has_video(&self) -> bool {
        self.inner.lock().video_codec.is_some()
    }

    /// Returns the negotiated video codec, if any.
    pub fn video_codec(&self) -> Option<VideoCodec> {
        self.inner.lock().video_codec
    }

    /// Mutes outbound video.
    pub fn mute_video(&self) -> Result<()> {
        let mut inner = self.inner.lock();
        if inner.state != CallState::Active {
            return Err(Error::InvalidState);
        }
        if inner.video_codec.is_none() {
            return Err(Error::NoVideoStream);
        }
        if inner.video_muted {
            return Err(Error::VideoAlreadyMuted);
        }
        inner.video_muted = true;
        Ok(())
    }

    /// Unmutes outbound video.
    pub fn unmute_video(&self) -> Result<()> {
        let mut inner = self.inner.lock();
        if inner.state != CallState::Active {
            return Err(Error::InvalidState);
        }
        if inner.video_codec.is_none() {
            return Err(Error::NoVideoStream);
        }
        if !inner.video_muted {
            return Err(Error::VideoNotMuted);
        }
        inner.video_muted = false;
        Ok(())
    }

    /// Requests a keyframe from the remote video sender (no-op in mock).
    pub fn request_keyframe(&self) -> Result<()> {
        let inner = self.inner.lock();
        if inner.state != CallState::Active {
            return Err(Error::InvalidState);
        }
        if inner.video_codec.is_none() {
            return Err(Error::NoVideoStream);
        }
        Ok(())
    }

    /// Returns the dialog identifiers `(call_id, local_tag, remote_tag)`.
    /// Tags are extracted from the From/To headers if set via [`set_header`](Self::set_header).
    pub fn dialog_id(&self) -> (String, String, String) {
        // Use case-insensitive lookup matching MockCall::header().
        let from_tag = self
            .header("From")
            .first()
            .map(|v| crate::call::sip_header_tag(v).to_string())
            .unwrap_or_default();
        let to_tag = self
            .header("To")
            .first()
            .map(|v| crate::call::sip_header_tag(v).to_string())
            .unwrap_or_default();
        let inner = self.inner.lock();
        match inner.direction {
            Direction::Outbound => (inner.call_id.clone(), from_tag, to_tag),
            Direction::Inbound => (inner.call_id.clone(), to_tag, from_tag),
        }
    }

    /// Ends the call with a specific reason (mirrors `Call::end_with_reason`).
    pub fn end_with_reason(&self, reason: EndReason) {
        let (state_cbs, ended_cbs) = {
            let mut inner = self.inner.lock();
            if inner.state == CallState::Ended {
                return;
            }
            inner.state = CallState::Ended;
            let cbs = (inner.on_state_fn.clone(), inner.on_ended_fn.clone());
            Self::clear_callbacks(&mut inner);
            cbs
        };
        for f in state_cbs {
            f(CallState::Ended);
        }
        for f in ended_cbs {
            f(reason);
        }
    }

    /// Clears all callbacks to break circular Arc references (MockCall → callback → Arc<MockCall>).
    fn clear_callbacks(inner: &mut Inner) {
        inner.on_state_fn.clear();
        inner.on_ended_fn.clear();
        inner.on_dtmf_fn.clear();
        inner.on_hold_fn.clear();
        inner.on_resume_fn.clear();
        inner.on_mute_fn.clear();
        inner.on_unmute_fn.clear();
        inner.on_media_fn.clear();
    }

    // --- Callback setters ---

    /// Registers a callback fired when a DTMF digit is received.
    pub fn on_dtmf(&self, f: impl Fn(String) + Send + Sync + 'static) {
        self.inner.lock().on_dtmf_fn.push(Arc::new(f));
    }

    /// Registers a callback fired when the call is placed on hold.
    /// Multiple callbacks can be registered; all will fire.
    pub fn on_hold(&self, f: impl Fn() + Send + Sync + 'static) {
        self.inner.lock().on_hold_fn.push(Arc::new(f));
    }

    /// Registers a callback fired when the call is resumed from hold.
    /// Multiple callbacks can be registered; all will fire.
    pub fn on_resume(&self, f: impl Fn() + Send + Sync + 'static) {
        self.inner.lock().on_resume_fn.push(Arc::new(f));
    }

    /// Registers a callback fired when the call is muted.
    /// Multiple callbacks can be registered; all will fire.
    pub fn on_mute(&self, f: impl Fn() + Send + Sync + 'static) {
        self.inner.lock().on_mute_fn.push(Arc::new(f));
    }

    /// Registers a callback fired when the call is unmuted.
    /// Multiple callbacks can be registered; all will fire.
    pub fn on_unmute(&self, f: impl Fn() + Send + Sync + 'static) {
        self.inner.lock().on_unmute_fn.push(Arc::new(f));
    }

    /// Registers a callback fired when media starts flowing.
    /// Multiple callbacks can be registered; all will fire.
    pub fn on_media(&self, f: impl Fn() + Send + Sync + 'static) {
        self.inner.lock().on_media_fn.push(Arc::new(f));
    }

    /// Registers a callback fired on every state transition.
    /// Multiple callbacks can be registered; all will fire.
    pub fn on_state(&self, f: impl Fn(CallState) + Send + Sync + 'static) {
        self.inner.lock().on_state_fn.push(Arc::new(f));
    }

    /// Registers a callback fired when the call ends, with the reason.
    /// Multiple callbacks can be registered; all will fire.
    pub fn on_ended(&self, f: impl Fn(EndReason) + Send + Sync + 'static) {
        self.inner.lock().on_ended_fn.push(Arc::new(f));
    }

    // --- Test setters ---

    /// Sets the call state directly (test helper).
    pub fn set_state(&self, s: CallState) {
        self.inner.lock().state = s;
    }

    /// Sets the call direction (test helper).
    pub fn set_direction(&self, d: Direction) {
        self.inner.lock().direction = d;
    }

    /// Sets the From URI (test helper).
    pub fn set_from(&self, from: &str) {
        self.inner.lock().from = from.into();
    }

    /// Sets the To URI (test helper).
    pub fn set_to(&self, to: &str) {
        self.inner.lock().to = to.into();
    }

    /// Sets the From display name (test helper).
    pub fn set_from_name(&self, name: &str) {
        self.inner.lock().from_name = name.into();
    }

    /// Sets the remote SIP URI (test helper).
    pub fn set_remote_uri(&self, uri: &str) {
        self.inner.lock().remote_uri = uri.into();
    }

    /// Sets the remote IP address (test helper).
    pub fn set_remote_ip(&self, ip: &str) {
        self.inner.lock().remote_ip = ip.into();
    }

    /// Sets the remote RTP port (test helper).
    pub fn set_remote_port(&self, port: i32) {
        self.inner.lock().remote_port = port;
    }

    /// Sets the negotiated codec (test helper).
    pub fn set_codec(&self, codec: Codec) {
        self.inner.lock().codec = codec;
    }

    /// Sets the local SDP (test helper).
    pub fn set_local_sdp(&self, sdp: &str) {
        self.inner.lock().local_sdp = sdp.into();
    }

    /// Sets the remote SDP (test helper).
    pub fn set_remote_sdp(&self, sdp: &str) {
        self.inner.lock().remote_sdp = sdp.into();
    }

    /// Sets the video codec (test helper).
    pub fn set_video_codec(&self, codec: VideoCodec) {
        self.inner.lock().video_codec = Some(codec);
    }

    /// Sets a SIP header value (test helper).
    pub fn set_header(&self, name: &str, value: &str) {
        self.inner
            .lock()
            .headers
            .insert(name.into(), vec![value.into()]);
    }

    // --- Test inspection ---

    /// Returns whether the call is currently muted.
    pub fn muted(&self) -> bool {
        self.inner.lock().muted
    }

    /// Returns whether video is currently muted.
    pub fn video_muted(&self) -> bool {
        self.inner.lock().video_muted
    }

    /// Returns all DTMF digits sent via [`send_dtmf`](Self::send_dtmf).
    pub fn sent_dtmf(&self) -> Vec<String> {
        self.inner.lock().sent_dtmf.clone()
    }

    /// Returns the target URI from the last [`blind_transfer`](Self::blind_transfer) call.
    pub fn last_transfer_target(&self) -> String {
        self.inner.lock().transfer_to.clone()
    }

    // --- Simulation ---

    /// Simulates receiving a DTMF digit, firing the on_dtmf callback.
    pub fn simulate_dtmf(&self, digit: &str) {
        let cbs = self.inner.lock().on_dtmf_fn.clone();
        for f in cbs {
            f(digit.to_string());
        }
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicBool, Ordering};

    #[test]
    fn new_mock_call_defaults() {
        let c = MockCall::new();
        assert_eq!(c.state(), CallState::Ringing);
        assert_eq!(c.direction(), Direction::Inbound);
        assert!(c.call_id().starts_with("mock-call-"));
    }

    #[test]
    fn accept_transitions_to_active() {
        let c = MockCall::new();
        c.accept().unwrap();
        assert_eq!(c.state(), CallState::Active);
        assert!(c.start_time().is_some());
    }

    #[test]
    fn reject_transitions_to_ended() {
        let c = MockCall::new();
        c.reject(486, "Busy Here").unwrap();
        assert_eq!(c.state(), CallState::Ended);
    }

    #[test]
    fn end_active_call() {
        let c = MockCall::new();
        c.accept().unwrap();
        c.end().unwrap();
        assert_eq!(c.state(), CallState::Ended);
    }

    #[test]
    fn end_ringing_returns_error() {
        let c = MockCall::new();
        assert!(c.end().is_err());
    }

    #[test]
    fn hold_and_resume() {
        let c = MockCall::new();
        c.accept().unwrap();
        c.hold().unwrap();
        assert_eq!(c.state(), CallState::OnHold);
        c.resume().unwrap();
        assert_eq!(c.state(), CallState::Active);
    }

    #[test]
    fn mute_unmute() {
        let c = MockCall::new();
        c.accept().unwrap();
        assert!(!c.muted());
        c.mute().unwrap();
        assert!(c.muted());
        c.unmute().unwrap();
        assert!(!c.muted());
    }

    #[test]
    fn send_dtmf_records() {
        let c = MockCall::new();
        c.accept().unwrap();
        c.send_dtmf("1").unwrap();
        c.send_dtmf("2").unwrap();
        assert_eq!(c.sent_dtmf(), vec!["1", "2"]);
    }

    #[test]
    fn blind_transfer_records() {
        let c = MockCall::new();
        c.accept().unwrap();
        c.blind_transfer("sip:1003@pbx.local").unwrap();
        assert_eq!(c.last_transfer_target(), "sip:1003@pbx.local");
    }

    #[test]
    fn setters_work() {
        let c = MockCall::new();
        c.set_remote_uri("sip:1001@host");
        c.set_remote_ip("10.0.0.1");
        c.set_remote_port(5060);
        c.set_codec(Codec::PCMA);
        c.set_local_sdp("v=0...");
        c.set_remote_sdp("v=0...");
        c.set_header("From", "<sip:1001@host>");

        assert_eq!(c.remote_uri(), "sip:1001@host");
        assert_eq!(c.remote_ip(), "10.0.0.1");
        assert_eq!(c.remote_port(), 5060);
        assert_eq!(c.codec(), Codec::PCMA);
        assert_eq!(c.local_sdp(), "v=0...");
        assert_eq!(c.remote_sdp(), "v=0...");
        assert_eq!(c.header("from"), vec!["<sip:1001@host>"]);
    }

    #[test]
    fn on_state_fires() {
        let c = MockCall::new();
        let fired = Arc::new(AtomicBool::new(false));
        let fired_clone = Arc::clone(&fired);
        c.on_state(move |s| {
            if s == CallState::Active {
                fired_clone.store(true, Ordering::Relaxed);
            }
        });
        c.accept().unwrap();
        assert!(fired.load(Ordering::Relaxed));
    }

    #[test]
    fn on_ended_fires() {
        let c = MockCall::new();
        c.accept().unwrap();
        let fired = Arc::new(AtomicBool::new(false));
        let fired_clone = Arc::clone(&fired);
        c.on_ended(move |r| {
            if r == EndReason::Local {
                fired_clone.store(true, Ordering::Relaxed);
            }
        });
        c.end().unwrap();
        assert!(fired.load(Ordering::Relaxed));
    }

    #[test]
    fn simulate_dtmf_fires_callback() {
        let c = MockCall::new();
        let received = Arc::new(Mutex::new(String::new()));
        let received_clone = Arc::clone(&received);
        c.on_dtmf(move |d| {
            *received_clone.lock() = d;
        });
        c.simulate_dtmf("5");
        assert_eq!(*received.lock(), "5");
    }

    #[test]
    fn end_dialing_gives_cancelled() {
        let c = MockCall::new();
        c.set_state(CallState::Dialing);
        let reason = Arc::new(Mutex::new(None));
        let reason_clone = Arc::clone(&reason);
        c.on_ended(move |r| {
            *reason_clone.lock() = Some(r);
        });
        c.end().unwrap();
        assert_eq!(*reason.lock(), Some(EndReason::Cancelled));
    }

    #[test]
    fn on_hold_callback_fires() {
        let c = MockCall::new();
        c.accept().unwrap();
        let fired = Arc::new(AtomicBool::new(false));
        let fired_clone = Arc::clone(&fired);
        c.on_hold(move || {
            fired_clone.store(true, Ordering::Relaxed);
        });
        c.hold().unwrap();
        assert!(fired.load(Ordering::Relaxed));
    }

    #[test]
    fn on_mute_callback_fires() {
        let c = MockCall::new();
        c.accept().unwrap();
        let fired = Arc::new(AtomicBool::new(false));
        let fired_clone = Arc::clone(&fired);
        c.on_mute(move || {
            fired_clone.store(true, Ordering::Relaxed);
        });
        c.mute().unwrap();
        assert!(fired.load(Ordering::Relaxed));
    }

    #[test]
    fn duration_zero_before_active() {
        let c = MockCall::new();
        assert_eq!(c.duration(), Duration::ZERO);
    }

    #[test]
    fn duration_grows_after_accept() {
        let c = MockCall::new();
        c.accept().unwrap();
        std::thread::sleep(Duration::from_millis(10));
        assert!(c.duration() >= Duration::from_millis(10));
    }

    #[test]
    fn callback_can_query_state() {
        let c = Arc::new(MockCall::new());
        let c2 = Arc::clone(&c);
        let state = Arc::new(Mutex::new(CallState::Ringing));
        let state_clone = Arc::clone(&state);
        c.on_state(move |_| {
            *state_clone.lock() = c2.state();
        });
        c.accept().unwrap();
        assert_eq!(*state.lock(), CallState::Active);
    }

    #[test]
    fn dialog_id_outbound_from_headers() {
        let c = MockCall::new();
        c.set_direction(Direction::Outbound);
        c.set_header("From", "<sip:1001@host>;tag=local1");
        c.set_header("To", "<sip:1002@host>;tag=remote2");
        let (cid, local, remote) = c.dialog_id();
        assert!(!cid.is_empty());
        assert_eq!(local, "local1");
        assert_eq!(remote, "remote2");
    }

    #[test]
    fn dialog_id_inbound_swaps_tags() {
        let c = MockCall::new();
        c.set_direction(Direction::Inbound);
        c.set_header("From", "<sip:1001@host>;tag=remote1");
        c.set_header("To", "<sip:1002@host>;tag=local2");
        let (_, local, remote) = c.dialog_id();
        assert_eq!(local, "local2");
        assert_eq!(remote, "remote1");
    }

    #[test]
    fn has_video_default_false() {
        let c = MockCall::new();
        assert!(!c.has_video());
        assert_eq!(c.video_codec(), None);
    }

    #[test]
    fn set_video_codec_enables_video() {
        let c = MockCall::new();
        c.set_video_codec(VideoCodec::H264);
        assert!(c.has_video());
        assert_eq!(c.video_codec(), Some(VideoCodec::H264));
    }

    #[test]
    fn mute_video_requires_active_and_video() {
        let c = MockCall::new();
        // Not active → InvalidState
        assert!(matches!(c.mute_video(), Err(Error::InvalidState)));

        c.accept().unwrap();
        // No video → NoVideoStream
        assert!(matches!(c.mute_video(), Err(Error::NoVideoStream)));

        c.set_video_codec(VideoCodec::VP8);
        c.mute_video().unwrap();
        assert!(c.video_muted());

        // Already muted
        assert!(matches!(c.mute_video(), Err(Error::VideoAlreadyMuted)));
    }

    #[test]
    fn unmute_video_requires_muted() {
        let c = MockCall::new();
        c.accept().unwrap();
        c.set_video_codec(VideoCodec::H264);
        // Not muted → VideoNotMuted
        assert!(matches!(c.unmute_video(), Err(Error::VideoNotMuted)));

        c.mute_video().unwrap();
        c.unmute_video().unwrap();
        assert!(!c.video_muted());
    }

    #[test]
    fn request_keyframe_mock() {
        let c = MockCall::new();
        c.accept().unwrap();
        assert!(matches!(c.request_keyframe(), Err(Error::NoVideoStream)));

        c.set_video_codec(VideoCodec::H264);
        c.request_keyframe().unwrap();
    }

    #[test]
    fn end_with_reason_fires_callback() {
        let c = MockCall::new();
        c.accept().unwrap();
        let reason = Arc::new(Mutex::new(None));
        let reason_clone = Arc::clone(&reason);
        c.on_ended(move |r| {
            *reason_clone.lock() = Some(r);
        });
        c.end_with_reason(EndReason::Transfer);
        assert_eq!(c.state(), CallState::Ended);
        assert_eq!(*reason.lock(), Some(EndReason::Transfer));
    }

    #[test]
    fn multiple_on_ended_callbacks_all_fire() {
        let c = MockCall::new();
        c.accept().unwrap();

        let count = Arc::new(std::sync::atomic::AtomicU32::new(0));
        let c1 = Arc::clone(&count);
        c.on_ended(move |_| {
            c1.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        });
        let c2 = Arc::clone(&count);
        c.on_ended(move |_| {
            c2.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        });

        c.end().unwrap();
        assert_eq!(count.load(std::sync::atomic::Ordering::Relaxed), 2);
    }

    #[test]
    fn multiple_on_state_callbacks_all_fire() {
        let c = MockCall::new();

        let count = Arc::new(std::sync::atomic::AtomicU32::new(0));
        let c1 = Arc::clone(&count);
        c.on_state(move |_| {
            c1.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        });
        let c2 = Arc::clone(&count);
        c.on_state(move |_| {
            c2.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        });

        c.accept().unwrap();
        assert_eq!(count.load(std::sync::atomic::Ordering::Relaxed), 2);
    }
}