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
use crate::connection::Connection;
use crate::enums::{IntoResult, OtcBool, OtcError, OtcResult};
use crate::publisher::Publisher;
use crate::stream::{Stream, StreamVideoType};
use crate::subscriber::Subscriber;

use lazy_static::lazy_static;
use std::collections::HashMap;
use std::ffi::{CStr, CString};
use std::os::raw::{c_char, c_void};
use std::sync::atomic::{AtomicPtr, Ordering};
use std::sync::mpsc::{self, Sender};
use std::sync::{Arc, Mutex};
use thiserror::Error;

lazy_static! {
    pub static ref INSTANCES: Arc<Mutex<HashMap<usize, Session>>> = Default::default();
}

/// Errors associated with an OpenTok session.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Error)]
#[must_use]
#[repr(u32)]
pub enum SessionError {
    #[error("Authorization failure")]
    AuthorizationFailure,
    #[error("Block country")]
    BlockedCountry,
    #[error("Connection dropped")]
    ConnectionDropped,
    #[error("Connection failed")]
    ConnectionFailed,
    #[error("Connection limit exceeded")]
    ConnectionLimitExceeded,
    #[error("Connection refused")]
    ConnectionRefused,
    #[error("Connection timed out")]
    ConnectionTimedOut,
    #[error("Force unpublish or invalid stream")]
    ForceUnpublishOrInvalidStream,
    #[error("Illegal state")]
    IllegalState,
    #[error("Internal error")]
    InternalError,
    #[error("Invalid session")]
    InvalidSession,
    #[error("Invalid signal type")]
    InvalidSignalType,
    #[error("Not connected")]
    NotConnected,
    #[error("No messaging server")]
    NoMessagingServer,
    #[error("Null or invalid parameter")]
    NullOrInvalidParameter,
    #[error("Publisher not found")]
    PublisherNotFound,
    #[error("Signal data too long")]
    SignalDataTooLong,
    #[error("Singal type too long")]
    SignalTypeTooLong,
    #[error("State failed")]
    StateFailed,
    #[error("Subscriber not found")]
    SubscriberNotFound,
    #[error("Unexpected get session info response")]
    UnexpectedGetSessionInfoResponse,
    #[error("Unknown error")]
    __Unknown,
}

impl From<ffi::otc_session_error_code> for SessionError {
    fn from(value: ffi::otc_session_error_code) -> SessionError {
        match value {
            ffi::otc_session_error_code_OTC_SESSION_AUTHORIZATION_FAILURE => {
                SessionError::AuthorizationFailure
            }
            ffi::otc_session_error_code_OTC_SESSION_BLOCKED_COUNTRY => SessionError::BlockedCountry,
            ffi::otc_session_error_code_OTC_SESSION_CONNECTION_DROPPED => {
                SessionError::ConnectionDropped
            }
            ffi::otc_session_error_code_OTC_SESSION_CONNECTION_FAILED => {
                SessionError::ConnectionFailed
            }
            ffi::otc_session_error_code_OTC_SESSION_CONNECTION_LIMIT_EXCEEDED => {
                SessionError::ConnectionLimitExceeded
            }
            ffi::otc_session_error_code_OTC_SESSION_CONNECTION_REFUSED => {
                SessionError::ConnectionRefused
            }
            ffi::otc_session_error_code_OTC_SESSION_CONNECTION_TIMED_OUT => {
                SessionError::ConnectionTimedOut
            }
            ffi::otc_session_error_code_OTC_SESSION_FORCE_UNPUBLISH_OR_INVALID_STREAM => {
                SessionError::ForceUnpublishOrInvalidStream
            }
            ffi::otc_session_error_code_OTC_SESSION_ILLEGAL_STATE => SessionError::IllegalState,
            ffi::otc_session_error_code_OTC_SESSION_INTERNAL_ERROR => SessionError::InternalError,
            ffi::otc_session_error_code_OTC_SESSION_INVALID_SESSION => SessionError::InvalidSession,
            ffi::otc_session_error_code_OTC_SESSION_INVALID_SIGNAL_TYPE => {
                SessionError::InvalidSignalType
            }
            ffi::otc_session_error_code_OTC_SESSION_NOT_CONNECTED => SessionError::NotConnected,
            ffi::otc_session_error_code_OTC_SESSION_NO_MESSAGING_SERVER => {
                SessionError::NoMessagingServer
            }
            ffi::otc_session_error_code_OTC_SESSION_NULL_OR_INVALID_PARAMETER => {
                SessionError::NullOrInvalidParameter
            }
            ffi::otc_session_error_code_OTC_SESSION_PUBLISHER_NOT_FOUND => {
                SessionError::PublisherNotFound
            }
            ffi::otc_session_error_code_OTC_SESSION_SIGNAL_DATA_TOO_LONG => {
                SessionError::SignalDataTooLong
            }
            ffi::otc_session_error_code_OTC_SESSION_SIGNAL_TYPE_TOO_LONG => {
                SessionError::SignalTypeTooLong
            }
            ffi::otc_session_error_code_OTC_SESSION_STATE_FAILED => SessionError::StateFailed,
            ffi::otc_session_error_code_OTC_SESSION_SUBSCRIBER_NOT_FOUND => {
                SessionError::SubscriberNotFound
            }
            ffi::otc_session_error_code_OTC_SESSION_UNEXPECTED_GET_SESSION_INFO_REPONSE => {
                SessionError::UnexpectedGetSessionInfoResponse
            }
            _ => SessionError::__Unknown,
        }
    }
}

ffi_callback!(on_connected, *mut ffi::otc_session, Session);
ffi_callback!(on_reconnection_started, *mut ffi::otc_session, Session);
ffi_callback!(on_reconnected, *mut ffi::otc_session, Session);
ffi_callback!(on_disconnected, *mut ffi::otc_session, Session);
ffi_callback!(
    on_connection_created,
    *mut ffi::otc_session,
    Session,
    *const ffi::otc_connection
);
ffi_callback!(
    on_connection_dropped,
    *mut ffi::otc_session,
    Session,
    *const ffi::otc_connection
);
ffi_callback!(
    on_stream_received,
    *mut ffi::otc_session,
    Session,
    *const ffi::otc_stream
);
ffi_callback!(
    on_stream_dropped,
    *mut ffi::otc_session,
    Session,
    *const ffi::otc_stream
);
ffi_callback!(
    on_stream_has_audio_changed,
    *mut ffi::otc_session,
    Session,
    *const ffi::otc_stream,
    ffi::otc_bool
);
ffi_callback!(
    on_stream_has_video_changed,
    *mut ffi::otc_session,
    Session,
    *const ffi::otc_stream,
    ffi::otc_bool
);
ffi_callback!(
    on_stream_video_dimensions_changed,
    *mut ffi::otc_session,
    Session,
    *const ffi::otc_stream,
    i32,
    i32
);
ffi_callback!(
    on_stream_video_type_changed,
    *mut ffi::otc_session,
    Session,
    *const ffi::otc_stream,
    ffi::otc_stream_video_type
);
ffi_callback!(
    on_signal_received,
    *mut ffi::otc_session,
    Session,
    *const c_char,
    *const c_char,
    *const ffi::otc_connection
);
ffi_callback!(
    on_archive_started,
    *mut ffi::otc_session,
    Session,
    *const c_char,
    *const c_char
);
ffi_callback!(
    on_archive_stopped,
    *mut ffi::otc_session,
    Session,
    *const c_char
);
ffi_callback!(
    on_error,
    *mut ffi::otc_session,
    Session,
    *const c_char,
    ffi::otc_session_error_code
);

#[allow(clippy::type_complexity)]
pub struct SessionCallbacks {
    on_connected: Option<Box<dyn Fn(&Session) + Send + Sync + 'static>>,
    on_reconnection_started: Option<Box<dyn Fn(&Session) + Send + Sync + 'static>>,
    on_reconnected: Option<Box<dyn Fn(&Session) + Send + Sync + 'static>>,
    on_disconnected: Option<Box<dyn Fn(&Session) + Send + Sync + 'static>>,
    on_connection_created: Option<Box<dyn Fn(&Session, Connection) + Send + Sync + 'static>>,
    on_connection_dropped: Option<Box<dyn Fn(&Session, Connection) + Send + Sync + 'static>>,
    on_stream_received: Option<Box<dyn Fn(&Session, Stream) + Send + Sync + 'static>>,
    on_stream_dropped: Option<Box<dyn Fn(&Session, Stream) + Send + Sync + 'static>>,
    on_stream_has_audio_changed:
        Option<Box<dyn Fn(&Session, Stream, bool) + Send + Sync + 'static>>,
    on_stream_has_video_changed:
        Option<Box<dyn Fn(&Session, Stream, bool) + Send + Sync + 'static>>,
    on_stream_video_dimensions_changed:
        Option<Box<dyn Fn(&Session, Stream, i32, i32) + Send + Sync + 'static>>,
    on_stream_video_type_changed:
        Option<Box<dyn Fn(&Session, Stream, StreamVideoType) + Send + Sync + 'static>>,
    on_signal_received:
        Option<Box<dyn Fn(&Session, &str, &str, Connection) + Send + Sync + 'static>>,
    on_archive_started: Option<Box<dyn Fn(&Session, &str, &str) + Send + Sync + 'static>>,
    on_archive_stopped: Option<Box<dyn Fn(&Session, &str) + Send + Sync + 'static>>,
    on_error: Option<Box<dyn Fn(&Session, &str, SessionError) + Send + Sync + 'static>>,
}

impl SessionCallbacks {
    pub fn builder() -> SessionCallbacksBuilder {
        SessionCallbacksBuilder::default()
    }

    callback!(on_connected, &Session);
    callback!(on_reconnection_started, &Session);
    callback!(on_reconnected, &Session);
    callback!(on_disconnected, &Session);
    callback!(on_connection_created, &Session, Connection);
    callback!(on_connection_dropped, &Session, Connection);
    callback!(on_stream_received, &Session, Stream);
    callback!(on_stream_dropped, &Session, Stream);

    pub fn on_stream_has_audio_changed(&self, session: &Session, stream: Stream, has_audio: bool) {
        if let Some(ref callback) = self.on_stream_has_audio_changed {
            callback(session, stream, has_audio);
        }
    }

    pub fn on_stream_has_video_changed(&self, session: &Session, stream: Stream, has_video: bool) {
        if let Some(ref callback) = self.on_stream_has_video_changed {
            callback(session, stream, has_video);
        }
    }

    callback!(
        on_stream_video_dimensions_changed,
        &Session,
        Stream,
        i32,
        i32
    );
    callback!(
        on_stream_video_type_changed,
        &Session,
        Stream,
        StreamVideoType
    );

    pub fn on_signal_received(
        &self,
        session: &Session,
        type_: &str,
        signal: &str,
        connection: Connection,
    ) {
        if let Some(ref callback) = self.on_signal_received {
            callback(session, type_, signal, connection)
        }
    }

    pub fn on_archive_started(&self, session: &Session, archive_id: &str, name: &str) {
        if let Some(ref callback) = self.on_archive_started {
            callback(session, archive_id, name);
        }
    }

    pub fn on_archive_stopped(&self, session: &Session, archive_id: &str) {
        if let Some(ref callback) = self.on_archive_stopped {
            callback(session, archive_id);
        }
    }

    pub fn on_error(&self, session: &Session, error_string: &str, error: SessionError) {
        if let Some(ref callback) = self.on_error {
            callback(session, error_string, error);
        }
    }
}

#[derive(Default)]
#[allow(clippy::type_complexity)]
pub struct SessionCallbacksBuilder {
    on_connected: Option<Box<dyn Fn(&Session) + Send + Sync + 'static>>,
    on_reconnection_started: Option<Box<dyn Fn(&Session) + Send + Sync + 'static>>,
    on_reconnected: Option<Box<dyn Fn(&Session) + Send + Sync + 'static>>,
    on_disconnected: Option<Box<dyn Fn(&Session) + Send + Sync + 'static>>,
    on_connection_created: Option<Box<dyn Fn(&Session, Connection) + Send + Sync + 'static>>,
    on_connection_dropped: Option<Box<dyn Fn(&Session, Connection) + Send + Sync + 'static>>,
    on_stream_received: Option<Box<dyn Fn(&Session, Stream) + Send + Sync + 'static>>,
    on_stream_dropped: Option<Box<dyn Fn(&Session, Stream) + Send + Sync + 'static>>,
    on_stream_has_audio_changed:
        Option<Box<dyn Fn(&Session, Stream, bool) + Send + Sync + 'static>>,
    on_stream_has_video_changed:
        Option<Box<dyn Fn(&Session, Stream, bool) + Send + Sync + 'static>>,
    on_stream_video_dimensions_changed:
        Option<Box<dyn Fn(&Session, Stream, i32, i32) + Send + Sync + 'static>>,
    on_stream_video_type_changed:
        Option<Box<dyn Fn(&Session, Stream, StreamVideoType) + Send + Sync + 'static>>,
    on_signal_received:
        Option<Box<dyn Fn(&Session, &str, &str, Connection) + Send + Sync + 'static>>,
    on_archive_started: Option<Box<dyn Fn(&Session, &str, &str) + Send + Sync + 'static>>,
    on_archive_stopped: Option<Box<dyn Fn(&Session, &str) + Send + Sync + 'static>>,
    on_error: Option<Box<dyn Fn(&Session, &str, SessionError) + Send + Sync + 'static>>,
}

impl SessionCallbacksBuilder {
    callback_setter!(on_connected, &Session);
    callback_setter!(on_reconnection_started, &Session);
    callback_setter!(on_reconnected, &Session);
    callback_setter!(on_disconnected, &Session);
    callback_setter!(on_connection_created, &Session, Connection);
    callback_setter!(on_connection_dropped, &Session, Connection);
    callback_setter!(on_stream_received, &Session, Stream);
    callback_setter!(on_stream_dropped, &Session, Stream);
    callback_setter!(on_stream_has_audio_changed, &Session, Stream, bool);
    callback_setter!(on_stream_has_video_changed, &Session, Stream, bool);
    callback_setter!(
        on_stream_video_dimensions_changed,
        &Session,
        Stream,
        i32,
        i32
    );
    callback_setter!(
        on_stream_video_type_changed,
        &Session,
        Stream,
        StreamVideoType
    );
    callback_setter!(on_signal_received, &Session, &str, &str, Connection);
    callback_setter!(on_archive_started, &Session, &str, &str);
    callback_setter!(on_archive_stopped, &Session, &str);
    callback_setter!(on_error, &Session, &str, SessionError);

    pub fn build(self) -> SessionCallbacks {
        SessionCallbacks {
            on_connected: self.on_connected,
            on_reconnection_started: self.on_reconnection_started,
            on_reconnected: self.on_reconnected,
            on_disconnected: self.on_disconnected,
            on_connection_created: self.on_connection_created,
            on_connection_dropped: self.on_connection_dropped,
            on_stream_received: self.on_stream_received,
            on_stream_dropped: self.on_stream_dropped,
            on_stream_has_audio_changed: self.on_stream_has_audio_changed,
            on_stream_has_video_changed: self.on_stream_has_video_changed,
            on_stream_video_dimensions_changed: self.on_stream_video_dimensions_changed,
            on_stream_video_type_changed: self.on_stream_video_type_changed,
            on_signal_received: self.on_signal_received,
            on_archive_started: self.on_archive_started,
            on_archive_stopped: self.on_archive_stopped,
            on_error: self.on_error,
        }
    }
}

/// Enumeration of all possible connection states.
#[derive(Clone, Debug, PartialEq)]
enum ConnectionState {
    Connected,
    Connecting,
    Disconnected,
    Disconnecting,
}

impl Default for ConnectionState {
    fn default() -> Self {
        Self::Disconnected
    }
}

#[derive(Clone)]
pub struct Session {
    ptr: Arc<AtomicPtr<*mut ffi::otc_session>>,
    callbacks: Arc<Mutex<SessionCallbacks>>,
    connection_state: Arc<Mutex<ConnectionState>>,
    disconnect_watcher: Arc<Mutex<Option<Sender<()>>>>,
}

unsafe impl Send for Session {}
unsafe impl Sync for Session {}

impl Session {
    /// Creates a new OpenTok session.
    ///
    /// * api_key: Your OpenTok API key. You can get it from <https://tokbox.com/account>
    /// * session_id: The identifier of the session.
    /// * callbacks: An instance of SessionCallbacks containing the handlers for events
    /// related to the session.
    pub fn new(
        api_key: &str,
        session_id: &str,
        callbacks: SessionCallbacks,
    ) -> Result<Session, OtcError> {
        let api_key = CString::new(api_key).map_err(|_| OtcError::InvalidParam("api_key"))?;
        let session_id =
            CString::new(session_id).map_err(|_| OtcError::InvalidParam("session_id"))?;
        let ffi_callbacks = ffi::otc_session_callbacks {
            on_connected: Some(on_connected),
            on_reconnection_started: Some(on_reconnection_started),
            on_reconnected: Some(on_reconnected),
            on_disconnected: Some(on_disconnected),
            on_connection_created: Some(on_connection_created),
            on_connection_dropped: Some(on_connection_dropped),
            on_stream_received: Some(on_stream_received),
            on_stream_dropped: Some(on_stream_dropped),
            on_stream_has_audio_changed: Some(on_stream_has_audio_changed),
            on_stream_has_video_changed: Some(on_stream_has_video_changed),
            on_stream_video_dimensions_changed: Some(on_stream_video_dimensions_changed),
            on_stream_video_type_changed: Some(on_stream_video_type_changed),
            on_signal_received: Some(on_signal_received),
            on_archive_started: Some(on_archive_started),
            on_archive_stopped: Some(on_archive_stopped),
            on_error: Some(on_error),
            user_data: std::ptr::null_mut(),
            reserved: std::ptr::null_mut(),
        };
        let session_ptr =
            unsafe { ffi::otc_session_new(api_key.as_ptr(), session_id.as_ptr(), &ffi_callbacks) };
        if session_ptr.is_null() {
            return Err(OtcError::NullError);
        }
        let session = Session {
            ptr: Arc::new(AtomicPtr::new(session_ptr as *mut _)),
            callbacks: Arc::new(Mutex::new(callbacks)),
            connection_state: Arc::new(Mutex::new(ConnectionState::Disconnected)),
            disconnect_watcher: Default::default(),
        };
        INSTANCES
            .lock()
            .unwrap()
            .insert(session_ptr as usize, session.clone());
        Ok(session)
    }

    string_getter!(
        /// Gets the uniquer identifier for this session.
        => (id, otc_session_get_id)
    );

    /// Connects a client to an OpenTok session.
    ///
    /// * token - The client token for connecting to the session. Check
    /// <https://tokbox.com/developer/guides/create-token/>
    pub fn connect(&self, token: &str) -> OtcResult {
        let connection_state = self.connection_state.lock().unwrap().clone();
        if connection_state == ConnectionState::Connected
            || connection_state == ConnectionState::Connecting
        {
            return Ok(());
        }
        if self.ptr.load(Ordering::Relaxed).is_null() {
            return Err(OtcError::NullError);
        }
        let token = std::ffi::CString::new(token).map_err(|_| OtcError::InvalidParam("token"))?;
        *self.connection_state.lock().unwrap() = ConnectionState::Connecting;
        unsafe {
            ffi::otc_session_connect(self.ptr.load(Ordering::Relaxed) as *mut _, token.as_ptr())
        }
        .into_result()
    }

    /// Disconnects the client from this session. All of the client's subscribers
    /// and publishers will also be disconnected from the session.
    pub fn disconnect(&self) -> OtcResult {
        let connection_state = self.connection_state.lock().unwrap().clone();
        if connection_state == ConnectionState::Disconnected
            || connection_state == ConnectionState::Disconnecting
        {
            return Ok(());
        }
        if self.ptr.load(Ordering::Relaxed).is_null() {
            return Err(OtcError::NullError);
        }
        *self.connection_state.lock().unwrap() = ConnectionState::Disconnecting;
        unsafe { ffi::otc_session_disconnect(self.ptr.load(Ordering::Relaxed) as *mut _) }
            .into_result()
    }

    /// Starts a publisher streaming to the session.
    pub fn publish(&self, publisher: &Publisher) -> OtcResult {
        if self.ptr.load(Ordering::Relaxed).is_null() {
            return Err(OtcError::NullError);
        }
        unsafe {
            ffi::otc_session_publish(
                self.ptr.load(Ordering::Relaxed) as *mut _,
                publisher.inner() as *mut _,
            )
        }
        .into_result()
    }

    /// Stops publishing from a session, causing the publisher stream to stop.
    pub fn unpublish(&self, publisher: &Publisher) -> OtcResult {
        if self.ptr.load(Ordering::Relaxed).is_null() {
            return Err(OtcError::NullError);
        }

        let publisher = publisher.inner();
        if publisher.is_null() {
            return Err(OtcError::NullError);
        }

        unsafe {
            ffi::otc_session_unpublish(
                self.ptr.load(Ordering::Relaxed) as *mut _,
                publisher as *mut _,
            )
        }
        .into_result()
    }

    /// Starts subscribing to an audio/video stream in this session.
    pub fn subscribe(&self, subscriber: &Subscriber) -> OtcResult {
        let ptr = self.ptr.load(Ordering::Relaxed);
        if ptr.is_null() {
            return Err(OtcError::NullError);
        }

        let subscriber = subscriber.inner();
        if subscriber.is_null() {
            return Err(OtcError::NullError);
        }

        unsafe { ffi::otc_session_subscribe(ptr as *mut _, subscriber as *mut _) }.into_result()
    }

    /// Stops subscribing to a specific audio/video stream in this session.
    pub fn unsubscribe(&self, subscriber: &Subscriber) -> OtcResult {
        let ptr = self.ptr.load(Ordering::Relaxed);
        if ptr.is_null() {
            return Err(OtcError::NullError);
        }

        let subscriber = subscriber.inner();
        if subscriber.is_null() {
            return Err(OtcError::NullError);
        }

        unsafe { ffi::otc_session_unsubscribe(ptr as *mut _, subscriber as *mut _) }.into_result()
    }

    callback_call!(on_connection_created, *const ffi::otc_connection);
    callback_call!(on_connection_dropped, *const ffi::otc_connection);
    callback_call!(on_stream_received, *const ffi::otc_stream);
    callback_call!(on_stream_dropped, *const ffi::otc_stream);
    callback_call!(
        on_stream_video_dimensions_changed,
        *const ffi::otc_stream,
        i32,
        i32
    );
    callback_call!(
        on_stream_video_type_changed,
        *const ffi::otc_stream,
        ffi::otc_stream_video_type
    );

    fn on_connected(&self) {
        *self.connection_state.lock().unwrap() = ConnectionState::Connected;
        if let Ok(callbacks) = self.callbacks.try_lock() {
            callbacks.on_connected(self);
        }
    }

    fn on_reconnection_started(&self) {
        *self.connection_state.lock().unwrap() = ConnectionState::Connecting;
        if let Ok(callbacks) = self.callbacks.try_lock() {
            callbacks.on_reconnection_started(self);
        }
    }

    fn on_reconnected(&self) {
        *self.connection_state.lock().unwrap() = ConnectionState::Connected;
        if let Ok(callbacks) = self.callbacks.try_lock() {
            callbacks.on_reconnected(self);
        }
    }

    fn on_disconnected(&self) {
        *self.connection_state.lock().unwrap() = ConnectionState::Disconnected;
        if let Ok(callbacks) = self.callbacks.try_lock() {
            callbacks.on_disconnected(self);
        }
        if let Some(ref disconnect_watcher) = *self.disconnect_watcher.lock().unwrap() {
            let _ = disconnect_watcher.send(());
        }
    }

    fn on_stream_has_audio_changed(
        &self,
        stream: *const ffi::otc_stream,
        has_audio: ffi::otc_bool,
    ) {
        if stream.is_null() {
            return;
        }
        let stream = unsafe { ffi::otc_stream_copy(stream) };
        if let Ok(callbacks) = self.callbacks.try_lock() {
            callbacks.on_stream_has_audio_changed(
                self,
                (stream as *const ffi::otc_stream).into(),
                *OtcBool(has_audio),
            )
        }
    }

    fn on_stream_has_video_changed(
        &self,
        stream: *const ffi::otc_stream,
        has_video: ffi::otc_bool,
    ) {
        if stream.is_null() {
            return;
        }
        let stream = unsafe { ffi::otc_stream_copy(stream) };
        if let Ok(callbacks) = self.callbacks.try_lock() {
            callbacks.on_stream_has_video_changed(
                self,
                (stream as *const ffi::otc_stream).into(),
                *OtcBool(has_video),
            )
        }
    }

    fn on_signal_received(
        &self,
        type_: *const c_char,
        signal: *const c_char,
        connection: *const ffi::otc_connection,
    ) {
        if type_.is_null() || signal.is_null() || connection.is_null() {
            return;
        }
        let type_ = unsafe { CStr::from_ptr(type_) };
        let signal = unsafe { CStr::from_ptr(signal) };
        if let Ok(callbacks) = self.callbacks.try_lock() {
            callbacks.on_signal_received(
                self,
                type_.to_str().unwrap_or_default(),
                signal.to_str().unwrap_or_default(),
                (connection as *const ffi::otc_connection).into(),
            );
        }
    }

    fn on_archive_started(&self, archive_id: *const c_char, name: *const c_char) {
        if archive_id.is_null() || name.is_null() {
            return;
        }
        let archive_id = unsafe { CStr::from_ptr(archive_id) };
        let name = unsafe { CStr::from_ptr(name) };
        if let Ok(callbacks) = self.callbacks.try_lock() {
            callbacks.on_archive_started(
                self,
                archive_id.to_str().unwrap_or_default(),
                name.to_str().unwrap_or_default(),
            );
        }
    }

    fn on_archive_stopped(&self, archive_id: *const c_char) {
        if archive_id.is_null() {
            return;
        }
        let archive_id = unsafe { CStr::from_ptr(archive_id) };
        if let Ok(callbacks) = self.callbacks.try_lock() {
            callbacks.on_archive_stopped(self, archive_id.to_str().unwrap_or_default());
        }
    }

    fn on_error(&self, error_string: *const c_char, error: ffi::otc_session_error_code) {
        if error_string.is_null() {
            return;
        }
        let error_string = unsafe { CStr::from_ptr(error_string) };
        if let Ok(callbacks) = self.callbacks.try_lock() {
            callbacks.on_error(
                self,
                error_string.to_str().unwrap_or_default(),
                error.into(),
            );
        }
    }
}

impl Drop for Session {
    fn drop(&mut self) {
        let ptr = self.ptr.load(Ordering::Relaxed);

        // 2 because we keep a reference in INSTANCES.
        if Arc::strong_count(&self.ptr) > 2 {
            return;
        }

        if ptr.is_null() {
            return;
        }

        let connection_state = self.connection_state.lock().unwrap().clone();
        if connection_state == ConnectionState::Connected {
            let (sender, receiver) = mpsc::channel();
            *self.disconnect_watcher.lock().unwrap() = Some(sender);
            if self.disconnect().is_ok() {
                receiver.recv().unwrap();
            }
        }

        self.ptr.store(std::ptr::null_mut(), Ordering::Relaxed);

        unsafe {
            ffi::otc_session_delete(ptr as *mut _);
        }

        if let Ok(ref mut instances) = INSTANCES.try_lock() {
            instances.remove(&(ptr as usize));
        }
    }
}