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

use std::mem::transmute;

use glib::{prelude::*, subclass::prelude::*, translate::*};

use crate::{ffi, RTSPMediaFactory};

pub trait RTSPMediaFactoryImpl: RTSPMediaFactoryImplExt + ObjectImpl + Send + Sync {
    /// convert `url` to a key for caching shared [`RTSPMedia`][crate::RTSPMedia] objects.
    ///  The default implementation of this function will use the complete URL
    ///  including the query parameters to return a key.
    fn gen_key(&self, url: &gst_rtsp::RTSPUrl) -> Option<glib::GString> {
        self.parent_gen_key(url)
    }

    /// Construct and return a [`gst::Element`][crate::gst::Element] that is a [`gst::Bin`][crate::gst::Bin] containing
    /// the elements to use for streaming the media.
    ///
    /// The bin should contain payloaders pay\`d` for each stream. The default
    /// implementation of this function returns the bin created from the
    /// launch parameter.
    /// ## `url`
    /// the url used
    ///
    /// # Returns
    ///
    /// a new [`gst::Element`][crate::gst::Element].
    fn create_element(&self, url: &gst_rtsp::RTSPUrl) -> Option<gst::Element> {
        self.parent_create_element(url)
    }

    /// Construct the media object and create its streams. Implementations
    /// should create the needed gstreamer elements and add them to the result
    /// object. No state changes should be performed on them yet.
    ///
    /// One or more GstRTSPStream objects should be created from the result
    /// with gst_rtsp_media_create_stream ().
    ///
    /// After the media is constructed, it can be configured and then prepared
    /// with gst_rtsp_media_prepare ().
    ///
    /// The returned media will be locked and must be unlocked afterwards.
    /// ## `url`
    /// the url used
    ///
    /// # Returns
    ///
    /// a new [`RTSPMedia`][crate::RTSPMedia] if the media could be prepared.
    fn construct(&self, url: &gst_rtsp::RTSPUrl) -> Option<crate::RTSPMedia> {
        self.parent_construct(url)
    }

    /// create a new pipeline or re-use an existing one and
    ///  add the [`RTSPMedia`][crate::RTSPMedia]'s element created by `construct` to the pipeline.
    fn create_pipeline(&self, media: &crate::RTSPMedia) -> Option<gst::Pipeline> {
        self.parent_create_pipeline(media)
    }

    /// configure the media created with `construct`. The default
    ///  implementation will configure the 'shared' property of the media.
    fn configure(&self, media: &crate::RTSPMedia) {
        self.parent_configure(media)
    }

    /// signal emitted when a media was constructed
    fn media_constructed(&self, media: &crate::RTSPMedia) {
        self.parent_media_constructed(media)
    }

    /// signal emitted when a media should be configured
    fn media_configure(&self, media: &crate::RTSPMedia) {
        self.parent_media_configure(media)
    }
}

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

pub trait RTSPMediaFactoryImplExt: sealed::Sealed + ObjectSubclass {
    fn parent_gen_key(&self, url: &gst_rtsp::RTSPUrl) -> Option<glib::GString> {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GstRTSPMediaFactoryClass;
            (*parent_class)
                .gen_key
                .map(|f| {
                    from_glib_full(f(
                        self.obj()
                            .unsafe_cast_ref::<RTSPMediaFactory>()
                            .to_glib_none()
                            .0,
                        url.to_glib_none().0,
                    ))
                })
                .unwrap_or(None)
        }
    }

    fn parent_create_element(&self, url: &gst_rtsp::RTSPUrl) -> Option<gst::Element> {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GstRTSPMediaFactoryClass;
            (*parent_class)
                .create_element
                .map(|f| {
                    from_glib_none(f(
                        self.obj()
                            .unsafe_cast_ref::<RTSPMediaFactory>()
                            .to_glib_none()
                            .0,
                        url.to_glib_none().0,
                    ))
                })
                .unwrap_or(None)
        }
    }

    fn parent_construct(&self, url: &gst_rtsp::RTSPUrl) -> Option<crate::RTSPMedia> {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GstRTSPMediaFactoryClass;
            (*parent_class)
                .construct
                .map(|f| {
                    from_glib_full(f(
                        self.obj()
                            .unsafe_cast_ref::<RTSPMediaFactory>()
                            .to_glib_none()
                            .0,
                        url.to_glib_none().0,
                    ))
                })
                .unwrap_or(None)
        }
    }

    fn parent_create_pipeline(&self, media: &crate::RTSPMedia) -> Option<gst::Pipeline> {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GstRTSPMediaFactoryClass;
            (*parent_class)
                .create_pipeline
                .map(|f| {
                    let ptr = f(
                        self.obj()
                            .unsafe_cast_ref::<RTSPMediaFactory>()
                            .to_glib_none()
                            .0,
                        media.to_glib_none().0,
                    ) as *mut gst::ffi::GstPipeline;

                    // See https://gitlab.freedesktop.org/gstreamer/gst-rtsp-server/merge_requests/109
                    if glib::gobject_ffi::g_object_is_floating(ptr as *mut _) != glib::ffi::GFALSE {
                        glib::gobject_ffi::g_object_ref_sink(ptr as *mut _);
                    }
                    from_glib_none(ptr)
                })
                .unwrap_or(None)
        }
    }

    fn parent_configure(&self, media: &crate::RTSPMedia) {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GstRTSPMediaFactoryClass;
            if let Some(f) = (*parent_class).configure {
                f(
                    self.obj()
                        .unsafe_cast_ref::<RTSPMediaFactory>()
                        .to_glib_none()
                        .0,
                    media.to_glib_none().0,
                );
            }
        }
    }

    fn parent_media_constructed(&self, media: &crate::RTSPMedia) {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GstRTSPMediaFactoryClass;
            if let Some(f) = (*parent_class).media_constructed {
                f(
                    self.obj()
                        .unsafe_cast_ref::<RTSPMediaFactory>()
                        .to_glib_none()
                        .0,
                    media.to_glib_none().0,
                );
            }
        }
    }

    fn parent_media_configure(&self, media: &crate::RTSPMedia) {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GstRTSPMediaFactoryClass;
            if let Some(f) = (*parent_class).media_configure {
                f(
                    self.obj()
                        .unsafe_cast_ref::<RTSPMediaFactory>()
                        .to_glib_none()
                        .0,
                    media.to_glib_none().0,
                );
            }
        }
    }
}

impl<T: RTSPMediaFactoryImpl> RTSPMediaFactoryImplExt for T {}
unsafe impl<T: RTSPMediaFactoryImpl> IsSubclassable<T> for RTSPMediaFactory {
    fn class_init(klass: &mut glib::Class<Self>) {
        Self::parent_class_init::<T>(klass);
        let klass = klass.as_mut();
        klass.gen_key = Some(factory_gen_key::<T>);
        klass.create_element = Some(factory_create_element::<T>);
        klass.construct = Some(factory_construct::<T>);
        klass.create_pipeline = Some(factory_create_pipeline::<T>);
        klass.configure = Some(factory_configure::<T>);
        klass.media_constructed = Some(factory_media_constructed::<T>);
        klass.media_configure = Some(factory_media_configure::<T>);
    }
}

unsafe extern "C" fn factory_gen_key<T: RTSPMediaFactoryImpl>(
    ptr: *mut ffi::GstRTSPMediaFactory,
    url: *const gst_rtsp::ffi::GstRTSPUrl,
) -> *mut std::os::raw::c_char {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    imp.gen_key(&from_glib_borrow(url)).into_glib_ptr()
}

unsafe extern "C" fn factory_create_element<T: RTSPMediaFactoryImpl>(
    ptr: *mut ffi::GstRTSPMediaFactory,
    url: *const gst_rtsp::ffi::GstRTSPUrl,
) -> *mut gst::ffi::GstElement {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    let element = imp.create_element(&from_glib_borrow(url)).into_glib_ptr();
    glib::gobject_ffi::g_object_force_floating(element as *mut _);
    element
}

unsafe extern "C" fn factory_construct<T: RTSPMediaFactoryImpl>(
    ptr: *mut ffi::GstRTSPMediaFactory,
    url: *const gst_rtsp::ffi::GstRTSPUrl,
) -> *mut ffi::GstRTSPMedia {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    imp.construct(&from_glib_borrow(url)).into_glib_ptr()
}

unsafe extern "C" fn factory_create_pipeline<T: RTSPMediaFactoryImpl>(
    ptr: *mut ffi::GstRTSPMediaFactory,
    media: *mut ffi::GstRTSPMedia,
) -> *mut gst::ffi::GstElement {
    static PIPELINE_QUARK: std::sync::OnceLock<glib::Quark> = std::sync::OnceLock::new();

    let pipeline_quark =
        PIPELINE_QUARK.get_or_init(|| glib::Quark::from_str("gstreamer-rs-rtsp-media-pipeline"));

    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    let pipeline: *mut gst::ffi::GstPipeline = imp
        .create_pipeline(&from_glib_borrow(media))
        .into_glib_ptr();

    // FIXME We somehow need to ensure the pipeline actually stays alive...
    glib::gobject_ffi::g_object_set_qdata_full(
        media as *mut _,
        pipeline_quark.into_glib(),
        pipeline as *mut _,
        Some(transmute::<
            *const (),
            unsafe extern "C" fn(glib::ffi::gpointer),
        >(glib::gobject_ffi::g_object_unref as *const ())),
    );

    pipeline as *mut _
}

unsafe extern "C" fn factory_configure<T: RTSPMediaFactoryImpl>(
    ptr: *mut ffi::GstRTSPMediaFactory,
    media: *mut ffi::GstRTSPMedia,
) {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    imp.configure(&from_glib_borrow(media));
}

unsafe extern "C" fn factory_media_constructed<T: RTSPMediaFactoryImpl>(
    ptr: *mut ffi::GstRTSPMediaFactory,
    media: *mut ffi::GstRTSPMedia,
) {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    imp.media_constructed(&from_glib_borrow(media));
}

unsafe extern "C" fn factory_media_configure<T: RTSPMediaFactoryImpl>(
    ptr: *mut ffi::GstRTSPMediaFactory,
    media: *mut ffi::GstRTSPMedia,
) {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    imp.media_configure(&from_glib_borrow(media));
}