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
// Take a look at the license at the top of the repository in the LICENSE file.

use std::mem::transmute;

use glib::{
    ffi::{gboolean, gpointer},
    prelude::*,
    source::Priority,
    translate::*,
    ControlFlow,
};

use crate::RTSPSessionPool;

unsafe extern "C" fn trampoline_watch<
    F: FnMut(&RTSPSessionPool) -> ControlFlow + Send + 'static,
>(
    pool: *mut ffi::GstRTSPSessionPool,
    func: gpointer,
) -> gboolean {
    let func: &mut F = &mut *(func as *mut F);
    func(&from_glib_borrow(pool)).into_glib()
}

unsafe extern "C" fn destroy_closure_watch<
    F: FnMut(&RTSPSessionPool) -> ControlFlow + Send + 'static,
>(
    ptr: gpointer,
) {
    let _ = Box::<F>::from_raw(ptr as *mut _);
}

fn into_raw_watch<F: FnMut(&RTSPSessionPool) -> ControlFlow + Send + 'static>(func: F) -> gpointer {
    #[allow(clippy::type_complexity)]
    let func: Box<F> = Box::new(func);
    Box::into_raw(func) as gpointer
}

mod sealed {
    pub trait Sealed {}
    impl<T: super::IsA<super::RTSPSessionPool>> Sealed for T {}
}

pub trait RTSPSessionPoolExtManual: sealed::Sealed + IsA<RTSPSessionPool> + 'static {
    /// Create a [`glib::Source`][crate::glib::Source] that will be dispatched when the session should be cleaned
    /// up.
    ///
    /// # Returns
    ///
    /// a [`glib::Source`][crate::glib::Source]
    #[doc(alias = "gst_rtsp_session_pool_create_watch")]
    fn create_watch<F>(&self, name: Option<&str>, priority: Priority, func: F) -> glib::Source
    where
        F: FnMut(&RTSPSessionPool) -> ControlFlow + Send + 'static,
    {
        skip_assert_initialized!();
        unsafe {
            let source = ffi::gst_rtsp_session_pool_create_watch(self.as_ref().to_glib_none().0);
            glib::ffi::g_source_set_callback(
                source,
                Some(transmute::<
                    _,
                    unsafe extern "C" fn(glib::ffi::gpointer) -> i32,
                >(trampoline_watch::<F> as *const ())),
                into_raw_watch(func),
                Some(destroy_closure_watch::<F>),
            );
            glib::ffi::g_source_set_priority(source, priority.into_glib());

            if let Some(name) = name {
                glib::ffi::g_source_set_name(source, name.to_glib_none().0);
            }

            from_glib_full(source)
        }
    }
}

impl<O: IsA<RTSPSessionPool>> RTSPSessionPoolExtManual for O {}