pjsipua-win 0.1.26

Rust library PJSUA2
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
// src/lib.rs - Complete library implementation with panic safety
pub mod ffi;

use std::ffi::{CString, CStr};
use std::sync::{Arc, Mutex};
use std::panic::{catch_unwind, AssertUnwindSafe};
use thiserror::Error;
use lazy_static::lazy_static;

// Re-export commonly used constants
pub use ffi::{
    PJSIP_INV_STATE_NULL, PJSIP_INV_STATE_CALLING, PJSIP_INV_STATE_INCOMING,
    PJSIP_INV_STATE_EARLY, PJSIP_INV_STATE_CONNECTING, PJSIP_INV_STATE_CONFIRMED,
    PJSIP_INV_STATE_DISCONNECTED, PJSIP_SC_OK, PJSIP_SC_RINGING, PJSIP_SC_BUSY_HERE,
    PJSUA_STATE_RUNNING,
};

lazy_static! {
    static ref INITIALIZED: Arc<Mutex<bool>> = Arc::new(Mutex::new(false));
    static ref CALLBACKS: Arc<Mutex<CallbackHandlers>> = Arc::new(Mutex::new(CallbackHandlers::default()));
}

#[derive(Debug, Clone)]
pub struct CallQuality {
    pub call_id: i32,
    pub rx_level: f64,
    pub tx_level: f64,
    pub rx_quality: f64,
    pub rx_loss_percent: f64,
    pub rtt_ms: i32,
    pub jitter_ms: f64,
    pub mos_score: f64,
    pub codec: String,
}

#[derive(Debug, Clone)]
pub struct CallDetailedInfo {
    pub call_id: i32,
    pub is_on_hold: bool,
    pub is_muted: bool,
    pub conf_port: i32,
}

#[derive(Error, Debug)]
pub enum Pjsua2Error {
    #[error("Failed to create endpoint: {0}")]
    EndpointCreation(i32),

    #[error("Failed to initialize endpoint: {0}")]
    EndpointInit(i32),

    #[error("Failed to create transport: {0}")]
    TransportCreation(i32),

    #[error("Failed to start PJSUA2: {0}")]
    StartError(i32),

    #[error("Failed to create account: {0}")]
    AccountCreation(i32),

    #[error("Failed to make call: {0}")]
    CallCreation(i32),

    #[error("Failed to answer call: {0}")]
    AnswerError(i32),

    #[error("Failed to hangup call: {0}")]
    HangupError(i32),

    #[error("Failed to set audio devices: {0}")]
    AudioDeviceError(i32),

    #[error("PJSUA2 not initialized")]
    NotInitialized,

    #[error("Invalid UTF-8 in string")]
    Utf8Error(#[from] std::ffi::NulError),

    #[error("Device not found")]
    DeviceNotFound,

    #[error("Internal panic occurred")]
    PanicOccurred,
}

pub type Result<T> = std::result::Result<T, Pjsua2Error>;

// Callback handlers
#[derive(Default)]
struct CallbackHandlers {
    on_registration_state: Option<Box<dyn Fn(i32, bool) + Send + Sync>>,
    on_incoming_call: Option<Box<dyn Fn(i32, i32, String) + Send + Sync>>,
    on_call_state: Option<Box<dyn Fn(i32, CallState) + Send + Sync>>,
    on_call_media_state: Option<Box<dyn Fn(i32, bool) + Send + Sync>>,
}

// Call state enum
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum CallState {
    Null,
    Calling,
    Incoming,
    Early,
    Connecting,
    Confirmed,
    Disconnected,
}

impl From<i32> for CallState {
    fn from(state: i32) -> Self {
        match state {
            0 => CallState::Null,
            1 => CallState::Calling,
            2 => CallState::Incoming,
            3 => CallState::Early,
            4 => CallState::Connecting,
            5 => CallState::Confirmed,
            6 => CallState::Disconnected,
            _ => CallState::Null,
        }
    }
}

// FFI callback functions with panic safety
extern "C" fn on_reg_state_ffi(acc_id: i32, is_registered: i32) {
    let result = catch_unwind(AssertUnwindSafe(|| {
        println!("[pjsipua_win FFI] Registration callback triggered - acc_id: {}, is_registered: {}", acc_id, is_registered);

        if let Ok(callbacks) = CALLBACKS.lock() {
            if let Some(ref handler) = callbacks.on_registration_state {
                println!("[pjsipua_win FFI] Calling Rust registration handler");
                handler(acc_id, is_registered != 0);
            } else {
                println!("[pjsipua_win FFI] No registration handler set!");
            }
        } else {
            println!("[pjsipua_win FFI] Failed to lock CALLBACKS!");
        }
    }));

    if let Err(e) = result {
        eprintln!("[pjsipua_win FFI] PANIC in registration callback: {:?}", e);
    }
}

extern "C" fn on_incoming_call_ffi(acc_id: i32, call_id: i32, remote_uri: *const i8) {
    let result = catch_unwind(AssertUnwindSafe(|| {
        // Check for null pointer first
        if remote_uri.is_null() {
            eprintln!("[pjsipua_win FFI] Received null remote_uri pointer");
            return;
        }

        let uri = unsafe {
            match CStr::from_ptr(remote_uri).to_str() {
                Ok(s) => s.to_string(),
                Err(e) => {
                    eprintln!("[pjsipua_win FFI] Invalid UTF-8 in remote_uri: {}", e);
                    return;
                }
            }
        };

        println!("[pjsipua_win FFI] Incoming call - acc_id: {}, call_id: {}, uri: {}", acc_id, call_id, uri);

        if let Ok(callbacks) = CALLBACKS.lock() {
            if let Some(ref handler) = callbacks.on_incoming_call {
                handler(acc_id, call_id, uri);
            } else {
                println!("[pjsipua_win FFI] No incoming call handler set!");
            }
        } else {
            println!("[pjsipua_win FFI] Failed to lock CALLBACKS!");
        }
    }));

    if let Err(e) = result {
        eprintln!("[pjsipua_win FFI] PANIC in incoming call callback: {:?}", e);
    }
}

extern "C" fn on_call_state_ffi(call_id: i32, state: i32) {
    let result = catch_unwind(AssertUnwindSafe(|| {
        println!("[pjsipua_win FFI] Call state changed - call_id: {}, state: {}", call_id, state);

        if let Ok(callbacks) = CALLBACKS.lock() {
            if let Some(ref handler) = callbacks.on_call_state {
                handler(call_id, CallState::from(state));
            }
        }
    }));

    if let Err(e) = result {
        eprintln!("[pjsipua_win FFI] PANIC in call state callback: {:?}", e);
    }
}

extern "C" fn on_call_media_state_ffi(call_id: i32, state: i32) {
    let result = catch_unwind(AssertUnwindSafe(|| {
        println!("[pjsipua_win FFI] Call media state changed - call_id: {}, state: {}", call_id, state);

        if let Ok(callbacks) = CALLBACKS.lock() {
            if let Some(ref handler) = callbacks.on_call_media_state {
                handler(call_id, state != 0);
            }
        }
    }));

    if let Err(e) = result {
        eprintln!("[pjsipua_win FFI] PANIC in call media state callback: {:?}", e);
    }
}

// Helper macro to wrap FFI calls with panic safety
macro_rules! wrap_ffi_call {
    ($body:expr) => {{
        match catch_unwind(AssertUnwindSafe(|| $body)) {
            Ok(result) => result,
            Err(e) => {
                eprintln!("[pjsipua_win FFI] PANIC in FFI call: {:?}", e);
                Err(Pjsua2Error::PanicOccurred)
            }
        }
    }};
}

/// PJSUA2 Endpoint wrapper
pub struct Pjsua2Endpoint {
    _private: (),
}

impl Pjsua2Endpoint {
    /// Initialize PJSUA2 endpoint
    pub fn init(log_level: i32) -> Result<Self> {
        wrap_ffi_call!({
            let mut initialized = INITIALIZED.lock().unwrap();

            if *initialized {
                return Ok(Self { _private: () });
            }

            unsafe {
                // Create endpoint
                let result = ffi::pjsua2_create_endpoint();
                if result != 0 {
                    return Err(Pjsua2Error::EndpointCreation(result));
                }

                // Initialize endpoint
                let result = ffi::pjsua2_init_endpoint(log_level);
                if result != 0 {
                    return Err(Pjsua2Error::EndpointInit(result));
                }

                // Create transport
                let result = ffi::pjsua2_create_transport(5060);
                if result != 0 {
                    return Err(Pjsua2Error::TransportCreation(result));
                }

                // Start PJSUA2
                let result = ffi::pjsua2_start();
                if result != 0 {
                    return Err(Pjsua2Error::StartError(result));
                }

                *initialized = true;
                Ok(Self { _private: () })
            }
        })
    }

    pub fn get_call_quality(&self, call_id: i32) -> Result<CallQuality> {
        wrap_ffi_call!({
            let initialized = INITIALIZED.lock().unwrap();
            if !*initialized {
                return Err(Pjsua2Error::NotInitialized);
            }

            unsafe {
                let mut rx_level = 0.0;
                let mut tx_level = 0.0;
                let mut rx_quality = 0.0;
                let mut rx_loss_percent = 0.0;
                let mut rtt_ms = 0;
                let mut jitter_ms = 0.0;
                let mut mos_score = 0.0;
                let mut codec_buf = vec![0u8; 64];

                let result = ffi::pjsua2_get_call_quality(
                    call_id,
                    &mut rx_level,
                    &mut tx_level,
                    &mut rx_quality,
                    &mut rx_loss_percent,
                    &mut rtt_ms,
                    &mut jitter_ms,
                    &mut mos_score,
                    codec_buf.as_mut_ptr() as *mut i8,
                    codec_buf.len() as i32,
                );

                if result != 0 {
                    return Err(Pjsua2Error::CallCreation(result));
                }

                let codec = CStr::from_ptr(codec_buf.as_ptr() as *const i8)
                    .to_string_lossy()
                    .to_string();

                Ok(CallQuality {
                    call_id,
                    rx_level,
                    tx_level,
                    rx_quality,
                    rx_loss_percent,
                    rtt_ms,
                    jitter_ms,
                    mos_score,
                    codec,
                })
            }
        })
    }

    /// Get audio devices currently used by a call
    pub fn get_call_audio_devices(&self, call_id: i32) -> Result<(i32, i32)> {
        wrap_ffi_call!({
            let initialized = INITIALIZED.lock().unwrap();
            if !*initialized {
                return Err(Pjsua2Error::NotInitialized);
            }

            unsafe {
                let mut capture_dev = -1;
                let mut playback_dev = -1;

                let result = ffi::pjsua2_get_call_audio_devices(
                    call_id,
                    &mut capture_dev,
                    &mut playback_dev,
                );

                if result != 0 {
                    return Err(Pjsua2Error::AudioDeviceError(result));
                }

                Ok((capture_dev, playback_dev))
            }
        })
    }

    /// Check if call has active media
    pub fn call_has_media(&self, call_id: i32) -> bool {
        match catch_unwind(AssertUnwindSafe(|| {
            let initialized = INITIALIZED.lock().unwrap();
            if !*initialized {
                return false;
            }

            unsafe {
                ffi::pjsua2_call_has_media(call_id) != 0
            }
        })) {
            Ok(result) => result,
            Err(e) => {
                eprintln!("[pjsipua_win FFI] PANIC in call_has_media: {:?}", e);
                false
            }
        }
    }

    /// Answer call with audio device logging
    pub fn answer_call_with_audio_info(&self, call_id: i32, code: i32) -> Result<()> {
        wrap_ffi_call!({
            let initialized = INITIALIZED.lock().unwrap();
            if !*initialized {
                return Err(Pjsua2Error::NotInitialized);
            }

            unsafe {
                let result = ffi::pjsua2_answer_call_with_audio_info(call_id, code);

                if result != 0 {
                    Err(Pjsua2Error::AnswerError(result))
                } else {
                    Ok(())
                }
            }
        })
    }

    /// Create a SIP account - simplified version that uses global callbacks
    pub fn create_account(&self, config: &AccountConfig) -> Result<i32> {
        wrap_ffi_call!({
            let initialized = INITIALIZED.lock().unwrap();
            if !*initialized {
                return Err(Pjsua2Error::NotInitialized);
            }

            let id_uri = CString::new(&config.id_uri[..])?;
            let registrar_uri = CString::new(&config.registrar_uri[..])?;
            let username = CString::new(&config.username[..])?;
            let password = CString::new(&config.password[..])?;

            unsafe {
                let account_id = ffi::pjsua2_create_account_simple(
                    id_uri.as_ptr(),
                    registrar_uri.as_ptr(),
                    username.as_ptr(),
                    password.as_ptr(),
                );

                if account_id < 0 {
                    Err(Pjsua2Error::AccountCreation(account_id))
                } else {
                    Ok(account_id)
                }
            }
        })
    }

    /// Create account with callbacks - DEPRECATED, use set_callbacks and create_account instead
    #[deprecated(note = "Use set_callbacks() and create_account() instead")]
    pub fn create_account_with_callbacks<F1, F2>(
        &self,
        config: &AccountConfig,
        _on_reg_state: F1,
        _on_incoming_call: F2,
    ) -> Result<i32>
    where
        F1: Fn(bool) + Send + Sync + 'static,
        F2: Fn(i32, String) + Send + Sync + 'static,
    {
        // Just call the simple version - don't overwrite callbacks
        self.create_account(config)
    }

    /// Make an outgoing call
    pub fn make_call(&self, account_id: i32, uri: &str) -> Result<i32> {
        wrap_ffi_call!({
            let initialized = INITIALIZED.lock().unwrap();
            if !*initialized {
                return Err(Pjsua2Error::NotInitialized);
            }

            let uri_c = CString::new(uri)?;

            unsafe {
                let call_id = ffi::pjsua2_make_call(account_id, uri_c.as_ptr());

                if call_id < 0 {
                    Err(Pjsua2Error::CallCreation(call_id))
                } else {
                    Ok(call_id)
                }
            }
        })
    }

    /// Answer incoming call
    pub fn answer_call(&self, call_id: i32, code: i32) -> Result<()> {
        wrap_ffi_call!({
            let initialized = INITIALIZED.lock().unwrap();
            if !*initialized {
                return Err(Pjsua2Error::NotInitialized);
            }

            unsafe {
                let result = ffi::pjsua2_answer_call(call_id, code);

                if result != 0 {
                    Err(Pjsua2Error::AnswerError(result))
                } else {
                    Ok(())
                }
            }
        })
    }

    /// Hangup call
    pub fn hangup_call(&self, call_id: i32) -> Result<()> {
        wrap_ffi_call!({
            let initialized = INITIALIZED.lock().unwrap();
            if !*initialized {
                return Err(Pjsua2Error::NotInitialized);
            }

            unsafe {
                let result = ffi::pjsua2_hangup_call(call_id);

                if result != 0 {
                    Err(Pjsua2Error::HangupError(result))
                } else {
                    Ok(())
                }
            }
        })
    }

    /// Put call on hold
    pub fn hold_call(&self, call_id: i32) -> Result<()> {
        wrap_ffi_call!({
            let initialized = INITIALIZED.lock().unwrap();
            if !*initialized {
                return Err(Pjsua2Error::NotInitialized);
            }

            unsafe {
                let result = ffi::pjsua2_hold_call(call_id);
                if result != 0 {
                    Err(Pjsua2Error::CallCreation(result))
                } else {
                    Ok(())
                }
            }
        })
    }

    /// Resume call from hold
    pub fn unhold_call(&self, call_id: i32) -> Result<()> {
        wrap_ffi_call!({
            let initialized = INITIALIZED.lock().unwrap();
            if !*initialized {
                return Err(Pjsua2Error::NotInitialized);
            }

            unsafe {
                let result = ffi::pjsua2_unhold_call(call_id);
                if result != 0 {
                    Err(Pjsua2Error::CallCreation(result))
                } else {
                    Ok(())
                }
            }
        })
    }

    /// Check if call is on hold
    pub fn is_call_on_hold(&self, call_id: i32) -> bool {
        match catch_unwind(AssertUnwindSafe(|| {
            let initialized = INITIALIZED.lock().unwrap();
            if !*initialized {
                return false;
            }

            unsafe {
                ffi::pjsua2_is_call_on_hold(call_id) != 0
            }
        })) {
            Ok(result) => result,
            Err(e) => {
                eprintln!("[pjsipua_win FFI] PANIC in is_call_on_hold: {:?}", e);
                false
            }
        }
    }

    /// Mute or unmute call
    pub fn mute_call(&self, call_id: i32, mute: bool) -> Result<()> {
        wrap_ffi_call!({
            let initialized = INITIALIZED.lock().unwrap();
            if !*initialized {
                return Err(Pjsua2Error::NotInitialized);
            }

            unsafe {
                let result = ffi::pjsua2_mute_call(call_id, if mute { 1 } else { 0 });
                if result != 0 {
                    Err(Pjsua2Error::CallCreation(result))
                } else {
                    Ok(())
                }
            }
        })
    }

    /// Check if call is muted
    pub fn is_call_muted(&self, call_id: i32) -> bool {
        match catch_unwind(AssertUnwindSafe(|| {
            let initialized = INITIALIZED.lock().unwrap();
            if !*initialized {
                return false;
            }

            unsafe {
                ffi::pjsua2_is_call_muted(call_id) != 0
            }
        })) {
            Ok(result) => result,
            Err(e) => {
                eprintln!("[pjsipua_win FFI] PANIC in is_call_muted: {:?}", e);
                false
            }
        }
    }

    /// Send DTMF digits
    pub fn send_dtmf(&self, call_id: i32, digits: &str) -> Result<()> {
        wrap_ffi_call!({
            let initialized = INITIALIZED.lock().unwrap();
            if !*initialized {
                return Err(Pjsua2Error::NotInitialized);
            }

            let digits_c = CString::new(digits)?;

            unsafe {
                let result = ffi::pjsua2_send_dtmf(call_id, digits_c.as_ptr());
                if result != 0 {
                    Err(Pjsua2Error::CallCreation(result))
                } else {
                    Ok(())
                }
            }
        })
    }

    /// Conference two calls together
    pub fn conference_calls(&self, call_id1: i32, call_id2: i32) -> Result<()> {
        wrap_ffi_call!({
            let initialized = INITIALIZED.lock().unwrap();
            if !*initialized {
                return Err(Pjsua2Error::NotInitialized);
            }

            unsafe {
                let result = ffi::pjsua2_conference_calls(call_id1, call_id2);
                if result != 0 {
                    Err(Pjsua2Error::CallCreation(result))
                } else {
                    Ok(())
                }
            }
        })
    }

    /// Get conference port for a call
    pub fn get_conf_port(&self, call_id: i32) -> Result<i32> {
        wrap_ffi_call!({
            let initialized = INITIALIZED.lock().unwrap();
            if !*initialized {
                return Err(Pjsua2Error::NotInitialized);
            }

            unsafe {
                let port = ffi::pjsua2_get_conf_port(call_id);
                if port < 0 {
                    Err(Pjsua2Error::CallCreation(port))
                } else {
                    Ok(port)
                }
            }
        })
    }

    /// Get detailed call info including hold and mute status
    pub fn get_call_detailed_info(&self, call_id: i32) -> Result<CallDetailedInfo> {
        wrap_ffi_call!({
            let initialized = INITIALIZED.lock().unwrap();
            if !*initialized {
                return Err(Pjsua2Error::NotInitialized);
            }

            unsafe {
                let mut is_on_hold = 0;
                let mut is_muted = 0;
                let mut conf_port = -1;

                let result = ffi::pjsua2_get_call_detailed_info(
                    call_id,
                    &mut is_on_hold,
                    &mut is_muted,
                    &mut conf_port,
                );

                if result != 0 {
                    Err(Pjsua2Error::CallCreation(result))
                } else {
                    Ok(CallDetailedInfo {
                        call_id,
                        is_on_hold: is_on_hold != 0,
                        is_muted: is_muted != 0,
                        conf_port,
                    })
                }
            }
        })
    }

    /// Get audio devices
    pub fn get_audio_devices(&self) -> Result<Vec<AudioDevice>> {
        wrap_ffi_call!({
            let initialized = INITIALIZED.lock().unwrap();
            if !*initialized {
                return Err(Pjsua2Error::NotInitialized);
            }

            unsafe {
                let count = ffi::pjsua2_get_audio_device_count();
                let mut devices = Vec::new();

                for i in 0..count {
                    let mut name_buf = vec![0u8; 256];
                    let mut is_capture = 0;
                    let mut is_playback = 0;

                    let dev_id = ffi::pjsua2_get_audio_device_info(
                        i,
                        name_buf.as_mut_ptr() as *mut i8,
                        name_buf.len() as i32,
                        &mut is_capture,
                        &mut is_playback,
                    );

                    if dev_id >= 0 {
                        let name = CStr::from_ptr(name_buf.as_ptr() as *const i8)
                            .to_string_lossy()
                            .to_string();

                        devices.push(AudioDevice {
                            id: dev_id,
                            name,
                            is_capture: is_capture != 0,
                            is_playback: is_playback != 0,
                        });
                    }
                }

                Ok(devices)
            }
        })
    }

    /// Set audio devices
    pub fn set_audio_devices(&self, capture_id: i32, playback_id: i32) -> Result<()> {
        wrap_ffi_call!({
            let initialized = INITIALIZED.lock().unwrap();
            if !*initialized {
                return Err(Pjsua2Error::NotInitialized);
            }

            unsafe {
                let result = ffi::pjsua2_set_audio_devices(capture_id, playback_id);

                if result != 0 {
                    Err(Pjsua2Error::AudioDeviceError(result))
                } else {
                    Ok(())
                }
            }
        })
    }

    /// Set callback handlers and register them with FFI
    pub fn set_callbacks<F1, F2, F3, F4>(
        &self,
        on_registration_state: F1,
        on_incoming_call: F2,
        on_call_state: F3,
        on_call_media_state: F4,
    ) where
        F1: Fn(i32, bool) + Send + Sync + 'static,
        F2: Fn(i32, i32, String) + Send + Sync + 'static,
        F3: Fn(i32, CallState) + Send + Sync + 'static,
        F4: Fn(i32, bool) + Send + Sync + 'static,
    {
        let result = catch_unwind(AssertUnwindSafe(|| {
            // Store the callbacks
            if let Ok(mut callbacks) = CALLBACKS.lock() {
                callbacks.on_registration_state = Some(Box::new(on_registration_state));
                callbacks.on_incoming_call = Some(Box::new(on_incoming_call));
                callbacks.on_call_state = Some(Box::new(on_call_state));
                callbacks.on_call_media_state = Some(Box::new(on_call_media_state));
            }

            // IMPORTANT: Set up the FFI callbacks
            unsafe {
                ffi::pjsua2_set_callbacks(
                    Some(on_reg_state_ffi),
                    Some(on_incoming_call_ffi),
                    Some(on_call_state_ffi),
                    Some(on_call_media_state_ffi),
                );
            }
        }));

        if let Err(e) = result {
            eprintln!("[pjsipua_win FFI] PANIC in set_callbacks: {:?}", e);
        }
    }

    // Test functions with panic safety
    pub fn test_basic() -> i32 {
        match catch_unwind(|| unsafe { ffi::pjsua2_test_basic() }) {
            Ok(result) => result,
            Err(e) => {
                eprintln!("[pjsipua_win FFI] PANIC in test_basic: {:?}", e);
                -1
            }
        }
    }

    pub fn test_object_creation() -> i32 {
        match catch_unwind(|| unsafe { ffi::pjsua2_test_object_creation() }) {
            Ok(result) => result,
            Err(e) => {
                eprintln!("[pjsipua_win FFI] PANIC in test_object_creation: {:?}", e);
                -1
            }
        }
    }

    pub fn test_account_config() -> i32 {
        match catch_unwind(|| unsafe { ffi::pjsua2_test_account_config() }) {
            Ok(result) => result,
            Err(e) => {
                eprintln!("[pjsipua_win FFI] PANIC in test_account_config: {:?}", e);
                -1
            }
        }
    }

    pub fn get_state(&self) -> i32 {
        match catch_unwind(|| unsafe { ffi::pjsua2_test_endpoint_state() }) {
            Ok(result) => result,
            Err(e) => {
                eprintln!("[pjsipua_win FFI] PANIC in get_state: {:?}", e);
                -1
            }
        }
    }

    /// Get active call count with panic safety
    pub fn get_active_call_count(&self) -> i32 {
        match catch_unwind(|| unsafe { ffi::pjsua2_get_active_call_count() }) {
            Ok(result) => result,
            Err(e) => {
                eprintln!("[pjsipua_win FFI] PANIC in get_active_call_count: {:?}", e);
                0
            }
        }
    }

    /// Clean up orphaned calls with panic safety
    pub fn cleanup_calls(&self) -> i32 {
        match catch_unwind(|| unsafe { ffi::pjsua2_cleanup_calls() }) {
            Ok(result) => result,
            Err(e) => {
                eprintln!("[pjsipua_win FFI] PANIC in cleanup_calls: {:?}", e);
                0
            }
        }
    }
}

impl Drop for Pjsua2Endpoint {
    fn drop(&mut self) {
        let result = catch_unwind(AssertUnwindSafe(|| {
            let mut initialized = INITIALIZED.lock().unwrap();
            if *initialized {
                unsafe {
                    ffi::pjsua2_destroy();
                }
                *initialized = false;
            }
        }));

        if let Err(e) = result {
            eprintln!("[pjsipua_win FFI] PANIC in Drop: {:?}", e);
        }
    }
}

/// Audio device information
#[derive(Debug, Clone)]
pub struct AudioDevice {
    pub id: i32,
    pub name: String,
    pub is_capture: bool,
    pub is_playback: bool,
}

/// SIP Account configuration
#[derive(Debug, Clone)]
pub struct AccountConfig {
    pub id_uri: String,
    pub registrar_uri: String,
    pub username: String,
    pub password: String,
}

impl AccountConfig {
    pub fn new(username: &str, domain: &str, password: &str) -> Self {
        Self {
            id_uri: format!("sip:{}@{}", username, domain),
            registrar_uri: format!("sip:{}", domain),
            username: username.to_string(),
            password: password.to_string(),
        }
    }
}

/// Run all diagnostic tests with panic safety
pub fn run_diagnostics() -> DiagnosticResults {
    DiagnosticResults {
        basic_test: Pjsua2Endpoint::test_basic(),
        object_creation: Pjsua2Endpoint::test_object_creation(),
        account_config: Pjsua2Endpoint::test_account_config(),
    }
}

#[derive(Debug)]
pub struct DiagnosticResults {
    pub basic_test: i32,
    pub object_creation: i32,
    pub account_config: i32,
}