gstreamer/subclass/
device_provider.rs

1// Take a look at the license at the top of the repository in the LICENSE file.
2
3use std::borrow::Cow;
4
5use glib::{prelude::*, subclass::prelude::*, translate::*};
6
7use super::prelude::*;
8use crate::{ffi, Device, DeviceProvider, LoggableError};
9
10#[derive(Debug, Clone)]
11pub struct DeviceProviderMetadata {
12    long_name: Cow<'static, str>,
13    classification: Cow<'static, str>,
14    description: Cow<'static, str>,
15    author: Cow<'static, str>,
16    additional: Cow<'static, [(Cow<'static, str>, Cow<'static, str>)]>,
17}
18
19impl DeviceProviderMetadata {
20    pub fn new(long_name: &str, classification: &str, description: &str, author: &str) -> Self {
21        Self {
22            long_name: Cow::Owned(long_name.into()),
23            classification: Cow::Owned(classification.into()),
24            description: Cow::Owned(description.into()),
25            author: Cow::Owned(author.into()),
26            additional: Cow::Borrowed(&[]),
27        }
28    }
29
30    pub fn with_additional(
31        long_name: &str,
32        classification: &str,
33        description: &str,
34        author: &str,
35        additional: &[(&str, &str)],
36    ) -> Self {
37        Self {
38            long_name: Cow::Owned(long_name.into()),
39            classification: Cow::Owned(classification.into()),
40            description: Cow::Owned(description.into()),
41            author: Cow::Owned(author.into()),
42            additional: additional
43                .iter()
44                .copied()
45                .map(|(key, value)| (Cow::Owned(key.into()), Cow::Owned(value.into())))
46                .collect(),
47        }
48    }
49
50    pub const fn with_cow(
51        long_name: Cow<'static, str>,
52        classification: Cow<'static, str>,
53        description: Cow<'static, str>,
54        author: Cow<'static, str>,
55        additional: Cow<'static, [(Cow<'static, str>, Cow<'static, str>)]>,
56    ) -> Self {
57        Self {
58            long_name,
59            classification,
60            description,
61            author,
62            additional,
63        }
64    }
65}
66
67pub trait DeviceProviderImpl: GstObjectImpl + ObjectSubclass<Type: IsA<DeviceProvider>> {
68    fn metadata() -> Option<&'static DeviceProviderMetadata> {
69        None
70    }
71
72    /// Returns a list of devices that are currently available.
73    ///  This should never block. The devices should not have a parent and should
74    ///  be floating.
75    fn probe(&self) -> Vec<Device> {
76        self.parent_probe()
77    }
78
79    /// Starts providering the devices. This will cause `GST_MESSAGE_DEVICE_ADDED`
80    /// and `GST_MESSAGE_DEVICE_REMOVED` messages to be posted on the provider's bus
81    /// when devices are added or removed from the system.
82    ///
83    /// Since the [`DeviceProvider`][crate::DeviceProvider] is a singleton,
84    /// [`DeviceProviderExt::start()`][crate::prelude::DeviceProviderExt::start()] may already have been called by another
85    /// user of the object, [`DeviceProviderExt::stop()`][crate::prelude::DeviceProviderExt::stop()] needs to be called the same
86    /// number of times.
87    ///
88    /// After this function has been called, [`DeviceProviderExtManual::devices()`][crate::prelude::DeviceProviderExtManual::devices()] will
89    /// return the same objects that have been received from the
90    /// `GST_MESSAGE_DEVICE_ADDED` messages and will no longer probe.
91    ///
92    /// # Returns
93    ///
94    /// [`true`] if the device providering could be started
95    fn start(&self) -> Result<(), LoggableError> {
96        self.parent_start()
97    }
98
99    /// Decreases the use-count by one. If the use count reaches zero, this
100    /// [`DeviceProvider`][crate::DeviceProvider] will stop providering the devices. This needs to be
101    /// called the same number of times that [`DeviceProviderExt::start()`][crate::prelude::DeviceProviderExt::start()] was called.
102    fn stop(&self) {
103        self.parent_stop()
104    }
105}
106
107pub trait DeviceProviderImplExt: DeviceProviderImpl {
108    fn parent_probe(&self) -> Vec<Device> {
109        unsafe {
110            let data = Self::type_data();
111            let parent_class = data.as_ref().parent_class() as *mut ffi::GstDeviceProviderClass;
112            if let Some(f) = (*parent_class).probe {
113                FromGlibPtrContainer::from_glib_full(f(self
114                    .obj()
115                    .unsafe_cast_ref::<DeviceProvider>()
116                    .to_glib_none()
117                    .0))
118            } else {
119                Vec::new()
120            }
121        }
122    }
123
124    fn parent_start(&self) -> Result<(), LoggableError> {
125        unsafe {
126            let data = Self::type_data();
127            let parent_class = data.as_ref().parent_class() as *mut ffi::GstDeviceProviderClass;
128            let f = (*parent_class).start.ok_or_else(|| {
129                loggable_error!(crate::CAT_RUST, "Parent function `start` is not defined")
130            })?;
131            result_from_gboolean!(
132                f(self
133                    .obj()
134                    .unsafe_cast_ref::<DeviceProvider>()
135                    .to_glib_none()
136                    .0),
137                crate::CAT_RUST,
138                "Failed to start the device provider using the parent function"
139            )
140        }
141    }
142
143    fn parent_stop(&self) {
144        unsafe {
145            let data = Self::type_data();
146            let parent_class = data.as_ref().parent_class() as *mut ffi::GstDeviceProviderClass;
147            if let Some(f) = (*parent_class).stop {
148                f(self
149                    .obj()
150                    .unsafe_cast_ref::<DeviceProvider>()
151                    .to_glib_none()
152                    .0);
153            }
154        }
155    }
156}
157
158impl<T: DeviceProviderImpl> DeviceProviderImplExt for T {}
159
160unsafe impl<T: DeviceProviderImpl> IsSubclassable<T> for DeviceProvider {
161    fn class_init(klass: &mut glib::Class<Self>) {
162        Self::parent_class_init::<T>(klass);
163        let klass = klass.as_mut();
164        klass.probe = Some(device_provider_probe::<T>);
165        klass.start = Some(device_provider_start::<T>);
166        klass.stop = Some(device_provider_stop::<T>);
167
168        unsafe {
169            if let Some(metadata) = T::metadata() {
170                ffi::gst_device_provider_class_set_metadata(
171                    klass,
172                    metadata.long_name.to_glib_none().0,
173                    metadata.classification.to_glib_none().0,
174                    metadata.description.to_glib_none().0,
175                    metadata.author.to_glib_none().0,
176                );
177
178                for (key, value) in metadata.additional.iter() {
179                    ffi::gst_device_provider_class_add_metadata(
180                        klass,
181                        key.to_glib_none().0,
182                        value.to_glib_none().0,
183                    );
184                }
185            }
186        }
187    }
188}
189
190unsafe extern "C" fn device_provider_probe<T: DeviceProviderImpl>(
191    ptr: *mut ffi::GstDeviceProvider,
192) -> *mut glib::ffi::GList {
193    let instance = &*(ptr as *mut T::Instance);
194    let imp = instance.imp();
195
196    imp.probe().to_glib_full()
197}
198
199unsafe extern "C" fn device_provider_start<T: DeviceProviderImpl>(
200    ptr: *mut ffi::GstDeviceProvider,
201) -> glib::ffi::gboolean {
202    let instance = &*(ptr as *mut T::Instance);
203    let imp = instance.imp();
204
205    match imp.start() {
206        Ok(()) => true,
207        Err(err) => {
208            err.log_with_imp(imp);
209            false
210        }
211    }
212    .into_glib()
213}
214
215unsafe extern "C" fn device_provider_stop<T: DeviceProviderImpl>(ptr: *mut ffi::GstDeviceProvider) {
216    let instance = &*(ptr as *mut T::Instance);
217    let imp = instance.imp();
218
219    imp.stop();
220}