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

use std::ffi::CStr;

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

use crate::{
    ffi, CapsRef, Element, ElementFactory, Rank, StaticPadTemplate, ELEMENT_METADATA_AUTHOR,
    ELEMENT_METADATA_DESCRIPTION, ELEMENT_METADATA_DOC_URI, ELEMENT_METADATA_ICON_NAME,
    ELEMENT_METADATA_KLASS, ELEMENT_METADATA_LONGNAME,
};

impl ElementFactory {
    #[doc(alias = "gst_element_factory_create")]
    #[doc(alias = "gst_element_factory_create_with_properties")]
    #[track_caller]
    pub fn create(&self) -> ElementBuilder {
        assert_initialized_main_thread!();

        ElementBuilder {
            name_or_factory: NameOrFactory::Factory(self),
            properties: smallvec::SmallVec::new(),
        }
    }

    #[doc(alias = "gst_element_factory_make")]
    #[doc(alias = "gst_element_factory_make_with_properties")]
    #[track_caller]
    pub fn make(factoryname: &str) -> ElementBuilder {
        assert_initialized_main_thread!();

        ElementBuilder {
            name_or_factory: NameOrFactory::Name(factoryname),
            properties: smallvec::SmallVec::new(),
        }
    }

    /// Create a new element of the type defined by the given elementfactory.
    /// It will be given the name supplied, since all elements require a name as
    /// their first argument.
    /// ## `name`
    /// name of new element, or [`None`] to automatically create
    ///  a unique name
    ///
    /// # Returns
    ///
    /// new [`Element`][crate::Element] or [`None`]
    ///  if the element couldn't be created
    #[doc(alias = "gst_element_factory_create")]
    #[track_caller]
    pub fn create_with_name(&self, name: Option<&str>) -> Result<Element, glib::BoolError> {
        let mut builder = self.create();
        if let Some(name) = name {
            builder = builder.name(name);
        }
        builder.build()
    }

    /// Create a new element of the type defined by the given element factory.
    /// If name is [`None`], then the element will receive a guaranteed unique name,
    /// consisting of the element factory name and a number.
    /// If name is given, it will be given the name supplied.
    /// ## `factoryname`
    /// a named factory to instantiate
    /// ## `name`
    /// name of new element, or [`None`] to automatically create
    ///  a unique name
    ///
    /// # Returns
    ///
    /// new [`Element`][crate::Element] or [`None`]
    /// if unable to create element
    #[doc(alias = "gst_element_factory_make")]
    #[track_caller]
    pub fn make_with_name(
        factoryname: &str,
        name: Option<&str>,
    ) -> Result<Element, glib::BoolError> {
        skip_assert_initialized!();
        let mut builder = Self::make(factoryname);
        if let Some(name) = name {
            builder = builder.name(name);
        }
        builder.build()
    }

    /// Gets the `GList` of [`StaticPadTemplate`][crate::StaticPadTemplate] for this factory.
    ///
    /// # Returns
    ///
    /// the
    ///  static pad templates
    #[doc(alias = "gst_element_factory_get_static_pad_templates")]
    #[doc(alias = "get_static_pad_templates")]
    pub fn static_pad_templates(&self) -> glib::List<StaticPadTemplate> {
        unsafe {
            glib::List::from_glib_none(ffi::gst_element_factory_get_static_pad_templates(
                self.to_glib_none().0,
            ))
        }
    }

    /// Check if `self` is of the given types.
    /// ## `type_`
    /// a `GstElementFactoryListType`
    ///
    /// # Returns
    ///
    /// [`true`] if `self` is of `type_`.
    #[doc(alias = "gst_element_factory_list_is_type")]
    pub fn has_type(&self, type_: crate::ElementFactoryType) -> bool {
        unsafe {
            from_glib(ffi::gst_element_factory_list_is_type(
                self.to_glib_none().0,
                type_.into_glib(),
            ))
        }
    }

    /// Get a list of factories that match the given `type_`. Only elements
    /// with a rank greater or equal to `minrank` will be returned.
    /// The list of factories is returned by decreasing rank.
    /// ## `type_`
    /// a `GstElementFactoryListType`
    /// ## `minrank`
    /// Minimum rank
    ///
    /// # Returns
    ///
    /// a `GList` of
    ///  [`ElementFactory`][crate::ElementFactory] elements. Use `gst_plugin_feature_list_free()` after
    ///  usage.
    #[doc(alias = "gst_element_factory_list_get_elements")]
    pub fn factories_with_type(
        type_: crate::ElementFactoryType,
        minrank: Rank,
    ) -> glib::List<ElementFactory> {
        assert_initialized_main_thread!();
        unsafe {
            FromGlibPtrContainer::from_glib_full(ffi::gst_element_factory_list_get_elements(
                type_.into_glib(),
                minrank.into_glib(),
            ))
        }
    }

    /// Get the metadata on `self` with `key`.
    /// ## `key`
    /// a key
    ///
    /// # Returns
    ///
    /// the metadata with `key` on `self` or [`None`]
    /// when there was no metadata with the given `key`.
    #[doc(alias = "gst_element_factory_get_metadata")]
    #[doc(alias = "get_metadata")]
    pub fn metadata(&self, key: &str) -> Option<&str> {
        unsafe {
            let ptr =
                ffi::gst_element_factory_get_metadata(self.to_glib_none().0, key.to_glib_none().0);

            if ptr.is_null() {
                None
            } else {
                Some(CStr::from_ptr(ptr).to_str().unwrap())
            }
        }
    }

    #[doc(alias = "get_longname")]
    #[doc(alias = "gst_element_factory_get_longname")]
    pub fn longname(&self) -> &str {
        self.metadata(ELEMENT_METADATA_LONGNAME).unwrap()
    }

    #[doc(alias = "get_klass")]
    #[doc(alias = "gst_element_factory_get_klass")]
    pub fn klass(&self) -> &str {
        self.metadata(ELEMENT_METADATA_KLASS).unwrap()
    }

    #[doc(alias = "get_description")]
    #[doc(alias = "gst_element_factory_get_description")]
    pub fn description(&self) -> &str {
        self.metadata(ELEMENT_METADATA_DESCRIPTION).unwrap()
    }

    #[doc(alias = "get_author")]
    #[doc(alias = "gst_element_factory_get_author")]
    pub fn author(&self) -> &str {
        self.metadata(ELEMENT_METADATA_AUTHOR).unwrap()
    }

    #[doc(alias = "get_documentation_uri")]
    #[doc(alias = "gst_element_factory_get_documentation_uri")]
    pub fn documentation_uri(&self) -> Option<&str> {
        self.metadata(ELEMENT_METADATA_DOC_URI)
    }

    #[doc(alias = "get_icon_name")]
    #[doc(alias = "gst_element_factory_get_icon_name")]
    pub fn icon_name(&self) -> Option<&str> {
        self.metadata(ELEMENT_METADATA_ICON_NAME)
    }

    /// Checks if the factory can sink all possible capabilities.
    /// ## `caps`
    /// the caps to check
    ///
    /// # Returns
    ///
    /// [`true`] if the caps are fully compatible.
    #[doc(alias = "gst_element_factory_can_sink_all_caps")]
    pub fn can_sink_all_caps(&self, caps: &CapsRef) -> bool {
        unsafe {
            from_glib(ffi::gst_element_factory_can_sink_all_caps(
                self.to_glib_none().0,
                caps.as_ptr(),
            ))
        }
    }

    /// Checks if the factory can sink any possible capability.
    /// ## `caps`
    /// the caps to check
    ///
    /// # Returns
    ///
    /// [`true`] if the caps have a common subset.
    #[doc(alias = "gst_element_factory_can_sink_any_caps")]
    pub fn can_sink_any_caps(&self, caps: &CapsRef) -> bool {
        unsafe {
            from_glib(ffi::gst_element_factory_can_sink_any_caps(
                self.to_glib_none().0,
                caps.as_ptr(),
            ))
        }
    }

    /// Checks if the factory can src all possible capabilities.
    /// ## `caps`
    /// the caps to check
    ///
    /// # Returns
    ///
    /// [`true`] if the caps are fully compatible.
    #[doc(alias = "gst_element_factory_can_src_all_caps")]
    pub fn can_src_all_caps(&self, caps: &CapsRef) -> bool {
        unsafe {
            from_glib(ffi::gst_element_factory_can_src_all_caps(
                self.to_glib_none().0,
                caps.as_ptr(),
            ))
        }
    }

    /// Checks if the factory can src any possible capability.
    /// ## `caps`
    /// the caps to check
    ///
    /// # Returns
    ///
    /// [`true`] if the caps have a common subset.
    #[doc(alias = "gst_element_factory_can_src_any_caps")]
    pub fn can_src_any_caps(&self, caps: &CapsRef) -> bool {
        unsafe {
            from_glib(ffi::gst_element_factory_can_src_any_caps(
                self.to_glib_none().0,
                caps.as_ptr(),
            ))
        }
    }
}

// rustdoc-stripper-ignore-next
/// Builder for `Element`s.
#[must_use = "The builder must be built to be used"]
pub struct ElementBuilder<'a> {
    name_or_factory: NameOrFactory<'a>,
    properties: smallvec::SmallVec<[(&'a str, ValueOrStr<'a>); 16]>,
}

#[derive(Copy, Clone)]
enum NameOrFactory<'a> {
    Name(&'a str),
    Factory(&'a ElementFactory),
}

enum ValueOrStr<'a> {
    Value(glib::Value),
    Str(&'a str),
}

impl<'a> ElementBuilder<'a> {
    // rustdoc-stripper-ignore-next
    /// Sets the name property to the given `name`.
    #[inline]
    pub fn name(self, name: impl Into<glib::GString>) -> Self {
        self.property("name", name.into())
    }

    // rustdoc-stripper-ignore-next
    /// Sets the name property to the given `name` if it is `Some`.
    #[inline]
    pub fn name_if_some(self, name: Option<impl Into<glib::GString>>) -> Self {
        if let Some(name) = name {
            self.name(name)
        } else {
            self
        }
    }

    // rustdoc-stripper-ignore-next
    /// Sets property `name` to the given value `value`.
    ///
    /// Overrides any default or previously defined value for `name`.
    #[inline]
    pub fn property(self, name: &'a str, value: impl Into<glib::Value> + 'a) -> Self {
        Self {
            name_or_factory: self.name_or_factory,
            properties: {
                let mut properties = self.properties;
                properties.push((name, ValueOrStr::Value(value.into())));
                properties
            },
        }
    }

    impl_builder_gvalue_extra_setters!(property);

    // rustdoc-stripper-ignore-next
    /// Sets property `name` to the given string value `value`.
    #[inline]
    pub fn property_from_str(self, name: &'a str, value: &'a str) -> Self {
        Self {
            name_or_factory: self.name_or_factory,
            properties: {
                let mut properties = self.properties;
                properties.push((name, ValueOrStr::Str(value)));
                properties
            },
        }
    }

    // rustdoc-stripper-ignore-next
    /// Sets property `name` to the given string value `value` if it is `Some`.
    #[inline]
    pub fn property_from_str_if_some(self, name: &'a str, value: Option<&'a str>) -> Self {
        if let Some(value) = value {
            self.property_from_str(name, value)
        } else {
            self
        }
    }

    // rustdoc-stripper-ignore-next
    /// Builds the element with the provided properties.
    ///
    /// This fails if there is no such element factory or the element factory can't be loaded.
    ///
    /// # Panics
    ///
    /// This panics if the element is not instantiable, doesn't have all the given properties or
    /// property values of the wrong type are provided.
    #[track_caller]
    #[must_use = "Building the element without using it has no effect"]
    pub fn build(self) -> Result<Element, glib::BoolError> {
        let mut _factory_found = None;
        let factory = match self.name_or_factory {
            NameOrFactory::Name(name) => {
                let factory = ElementFactory::find(name).ok_or_else(|| {
                    crate::warning!(crate::CAT_RUST, "element factory '{}' not found", name);
                    glib::bool_error!(
                        "Failed to find element factory with name '{}' for creating element",
                        name
                    )
                })?;
                _factory_found = Some(factory);
                _factory_found.as_ref().unwrap()
            }
            NameOrFactory::Factory(factory) => factory,
        };

        // The below is basically a reimplementation of the C function. We want to call
        // glib::Object::with_type() ourselves here for checking properties and their values
        // correctly and to provide consistent behaviour.
        use crate::prelude::{
            ElementExtManual, GstObjectExt, GstObjectExtManual, PluginFeatureExtManual,
        };

        let factory = factory.load().map_err(|_| {
            crate::warning!(
                crate::CAT_RUST,
                obj = factory,
                "loading element factory '{}' failed",
                factory.name(),
            );
            glib::bool_error!(
                "Failed to load element factory '{}' for creating element",
                factory.name()
            )
        })?;

        let element_type = factory.element_type();
        if !element_type.is_valid() {
            crate::warning!(
                crate::CAT_RUST,
                obj = &factory,
                "element factory '{}' has no type",
                factory.name()
            );
            return Err(glib::bool_error!(
                "Failed to create element from factory '{}'",
                factory.name()
            ));
        }

        let mut properties = smallvec::SmallVec::<[_; 16]>::with_capacity(self.properties.len());
        let klass = glib::Class::<Element>::from_type(element_type).unwrap();
        for (name, value) in self.properties {
            match value {
                ValueOrStr::Value(value) => {
                    properties.push((name, value));
                }
                ValueOrStr::Str(value) => {
                    use crate::value::GstValueExt;

                    let pspec = match klass.find_property(name) {
                        Some(pspec) => pspec,
                        None => {
                            panic!(
                                "property '{}' of element factory '{}' not found",
                                name,
                                factory.name()
                            );
                        }
                    };

                    let value = {
                        if pspec.value_type() == crate::Structure::static_type() && value == "NULL"
                        {
                            None::<crate::Structure>.to_value()
                        } else {
                            #[cfg(feature = "v1_20")]
                            {
                                glib::Value::deserialize_with_pspec(value, &pspec)
                                    .unwrap_or_else(|_| {
                                        panic!(
                                            "property '{}' of element factory '{}' can't be set from string '{}'",
                                            name,
                                            factory.name(),
                                            value,
                                        )
                                    })
                            }
                            #[cfg(not(feature = "v1_20"))]
                            {
                                glib::Value::deserialize(value, pspec.value_type())
                                    .unwrap_or_else(|_| {
                                        panic!(
                                            "property '{}' of element factory '{}' can't be set from string '{}'",
                                            name,
                                            factory.name(),
                                            value,
                                        )
                                    })
                            }
                        }
                    };

                    properties.push((name, value));
                }
            }
        }

        let element = unsafe {
            glib::Object::with_mut_values(element_type, &mut properties)
                .unsafe_cast::<crate::Element>()
        };

        unsafe {
            use std::sync::atomic;

            let klass = element.element_class();
            let factory_ptr: &atomic::AtomicPtr<ffi::GstElementFactory> =
                &*(&klass.as_ref().elementfactory as *const *mut ffi::GstElementFactory
                    as *const atomic::AtomicPtr<ffi::GstElementFactory>);
            if factory_ptr
                .compare_exchange(
                    std::ptr::null_mut(),
                    factory.as_ptr(),
                    atomic::Ordering::SeqCst,
                    atomic::Ordering::SeqCst,
                )
                .is_ok()
            {
                factory.set_object_flags(crate::ObjectFlags::MAY_BE_LEAKED);
            }

            if glib::gobject_ffi::g_object_is_floating(factory.as_ptr() as *mut _)
                != glib::ffi::GFALSE
            {
                glib::g_critical!(
                    "GStreamer",
                    "The created element should be floating, this is probably caused by faulty bindings",
                );
            }
        }

        crate::log!(
            crate::CAT_RUST,
            obj = &factory,
            "created element \"{}\"",
            factory.name()
        );

        Ok(element)
    }
}